xref: /titanic_51/usr/src/uts/common/inet/ip/ip.c (revision ad1592816585b2f21f25dcc07a8626676a7cec20)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 /* Copyright (c) 1990 Mentat Inc. */
27 
28 #pragma ident	"%Z%%M%	%I%	%E% SMI"
29 
30 #include <sys/types.h>
31 #include <sys/stream.h>
32 #include <sys/dlpi.h>
33 #include <sys/stropts.h>
34 #include <sys/sysmacros.h>
35 #include <sys/strsubr.h>
36 #include <sys/strlog.h>
37 #include <sys/strsun.h>
38 #include <sys/zone.h>
39 #define	_SUN_TPI_VERSION 2
40 #include <sys/tihdr.h>
41 #include <sys/xti_inet.h>
42 #include <sys/ddi.h>
43 #include <sys/sunddi.h>
44 #include <sys/cmn_err.h>
45 #include <sys/debug.h>
46 #include <sys/kobj.h>
47 #include <sys/modctl.h>
48 #include <sys/atomic.h>
49 #include <sys/policy.h>
50 #include <sys/priv.h>
51 
52 #include <sys/systm.h>
53 #include <sys/param.h>
54 #include <sys/kmem.h>
55 #include <sys/sdt.h>
56 #include <sys/socket.h>
57 #include <sys/vtrace.h>
58 #include <sys/isa_defs.h>
59 #include <net/if.h>
60 #include <net/if_arp.h>
61 #include <net/route.h>
62 #include <sys/sockio.h>
63 #include <netinet/in.h>
64 #include <net/if_dl.h>
65 
66 #include <inet/common.h>
67 #include <inet/mi.h>
68 #include <inet/mib2.h>
69 #include <inet/nd.h>
70 #include <inet/arp.h>
71 #include <inet/snmpcom.h>
72 #include <inet/optcom.h>
73 #include <inet/kstatcom.h>
74 
75 #include <netinet/igmp_var.h>
76 #include <netinet/ip6.h>
77 #include <netinet/icmp6.h>
78 #include <netinet/sctp.h>
79 
80 #include <inet/ip.h>
81 #include <inet/ip_impl.h>
82 #include <inet/ip6.h>
83 #include <inet/ip6_asp.h>
84 #include <inet/tcp.h>
85 #include <inet/tcp_impl.h>
86 #include <inet/ip_multi.h>
87 #include <inet/ip_if.h>
88 #include <inet/ip_ire.h>
89 #include <inet/ip_ftable.h>
90 #include <inet/ip_rts.h>
91 #include <inet/ip_ndp.h>
92 #include <inet/ip_listutils.h>
93 #include <netinet/igmp.h>
94 #include <netinet/ip_mroute.h>
95 #include <inet/ipp_common.h>
96 
97 #include <net/pfkeyv2.h>
98 #include <inet/ipsec_info.h>
99 #include <inet/sadb.h>
100 #include <inet/ipsec_impl.h>
101 #include <sys/iphada.h>
102 #include <inet/tun.h>
103 #include <inet/ipdrop.h>
104 #include <inet/ip_netinfo.h>
105 
106 #include <sys/ethernet.h>
107 #include <net/if_types.h>
108 #include <sys/cpuvar.h>
109 
110 #include <ipp/ipp.h>
111 #include <ipp/ipp_impl.h>
112 #include <ipp/ipgpc/ipgpc.h>
113 
114 #include <sys/multidata.h>
115 #include <sys/pattr.h>
116 
117 #include <inet/ipclassifier.h>
118 #include <inet/sctp_ip.h>
119 #include <inet/sctp/sctp_impl.h>
120 #include <inet/udp_impl.h>
121 #include <inet/rawip_impl.h>
122 #include <inet/rts_impl.h>
123 #include <sys/sunddi.h>
124 
125 #include <sys/tsol/label.h>
126 #include <sys/tsol/tnet.h>
127 
128 #include <rpc/pmap_prot.h>
129 
130 /*
131  * Values for squeue switch:
132  * IP_SQUEUE_ENTER_NODRAIN: squeue_enter_nodrain
133  * IP_SQUEUE_ENTER: squeue_enter
134  * IP_SQUEUE_FILL: squeue_fill
135  */
136 int ip_squeue_enter = 2;	/* Setable in /etc/system */
137 
138 squeue_func_t ip_input_proc;
139 #define	SET_BPREV_FLAG(x)	((mblk_t *)(uintptr_t)(x))
140 
141 /*
142  * Setable in /etc/system
143  */
144 int ip_poll_normal_ms = 100;
145 int ip_poll_normal_ticks = 0;
146 int ip_modclose_ackwait_ms = 3000;
147 
148 /*
149  * It would be nice to have these present only in DEBUG systems, but the
150  * current design of the global symbol checking logic requires them to be
151  * unconditionally present.
152  */
153 uint_t ip_thread_data;			/* TSD key for debug support */
154 krwlock_t ip_thread_rwlock;
155 list_t	ip_thread_list;
156 
157 /*
158  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
159  */
160 
161 struct listptr_s {
162 	mblk_t	*lp_head;	/* pointer to the head of the list */
163 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
164 };
165 
166 typedef struct listptr_s listptr_t;
167 
168 /*
169  * This is used by ip_snmp_get_mib2_ip_route_media and
170  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
171  */
172 typedef struct iproutedata_s {
173 	uint_t		ird_idx;
174 	listptr_t	ird_route;	/* ipRouteEntryTable */
175 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
176 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
177 } iproutedata_t;
178 
179 /*
180  * Cluster specific hooks. These should be NULL when booted as a non-cluster
181  */
182 
183 /*
184  * Hook functions to enable cluster networking
185  * On non-clustered systems these vectors must always be NULL.
186  *
187  * Hook function to Check ip specified ip address is a shared ip address
188  * in the cluster
189  *
190  */
191 int (*cl_inet_isclusterwide)(uint8_t protocol,
192     sa_family_t addr_family, uint8_t *laddrp) = NULL;
193 
194 /*
195  * Hook function to generate cluster wide ip fragment identifier
196  */
197 uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
198     uint8_t *laddrp, uint8_t *faddrp) = NULL;
199 
200 /*
201  * Synchronization notes:
202  *
203  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
204  * MT level protection given by STREAMS. IP uses a combination of its own
205  * internal serialization mechanism and standard Solaris locking techniques.
206  * The internal serialization is per phyint (no IPMP) or per IPMP group.
207  * This is used to serialize plumbing operations, IPMP operations, certain
208  * multicast operations, most set ioctls, igmp/mld timers etc.
209  *
210  * Plumbing is a long sequence of operations involving message
211  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
212  * involved in plumbing operations. A natural model is to serialize these
213  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
214  * parallel without any interference. But various set ioctls on hme0 are best
215  * serialized. However if the system uses IPMP, the operations are easier if
216  * they are serialized on a per IPMP group basis since IPMP operations
217  * happen across ill's of a group. Thus the lowest common denominator is to
218  * serialize most set ioctls, multicast join/leave operations, IPMP operations
219  * igmp/mld timer operations, and processing of DLPI control messages received
220  * from drivers on a per IPMP group basis. If the system does not employ
221  * IPMP the serialization is on a per phyint basis. This serialization is
222  * provided by the ipsq_t and primitives operating on this. Details can
223  * be found in ip_if.c above the core primitives operating on ipsq_t.
224  *
225  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
226  * Simiarly lookup of an ire by a thread also returns a refheld ire.
227  * In addition ipif's and ill's referenced by the ire are also indirectly
228  * refheld. Thus no ipif or ill can vanish nor can critical parameters like
229  * the ipif's address or netmask change as long as an ipif is refheld
230  * directly or indirectly. For example an SIOCLIFADDR ioctl that changes the
231  * address of an ipif has to go through the ipsq_t. This ensures that only
232  * 1 such exclusive operation proceeds at any time on the ipif. It then
233  * deletes all ires associated with this ipif, and waits for all refcnts
234  * associated with this ipif to come down to zero. The address is changed
235  * only after the ipif has been quiesced. Then the ipif is brought up again.
236  * More details are described above the comment in ip_sioctl_flags.
237  *
238  * Packet processing is based mostly on IREs and are fully multi-threaded
239  * using standard Solaris MT techniques.
240  *
241  * There are explicit locks in IP to handle:
242  * - The ip_g_head list maintained by mi_open_link() and friends.
243  *
244  * - The reassembly data structures (one lock per hash bucket)
245  *
246  * - conn_lock is meant to protect conn_t fields. The fields actually
247  *   protected by conn_lock are documented in the conn_t definition.
248  *
249  * - ire_lock to protect some of the fields of the ire, IRE tables
250  *   (one lock per hash bucket). Refer to ip_ire.c for details.
251  *
252  * - ndp_g_lock and nce_lock for protecting NCEs.
253  *
254  * - ill_lock protects fields of the ill and ipif. Details in ip.h
255  *
256  * - ill_g_lock: This is a global reader/writer lock. Protects the following
257  *	* The AVL tree based global multi list of all ills.
258  *	* The linked list of all ipifs of an ill
259  *	* The <ill-ipsq> mapping
260  *	* The ipsq->ipsq_phyint_list threaded by phyint_ipsq_next
261  *	* The illgroup list threaded by ill_group_next.
262  *	* <ill-phyint> association
263  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
264  *   into an ill, changing the <ill-ipsq> mapping of an ill, insertion/deletion
265  *   of an ill into the illgrp list, changing the <ill-phyint> assoc of an ill
266  *   will all have to hold the ill_g_lock as writer for the actual duration
267  *   of the insertion/deletion/change. More details about the <ill-ipsq> mapping
268  *   may be found in the IPMP section.
269  *
270  * - ill_lock:  This is a per ill mutex.
271  *   It protects some members of the ill and is documented below.
272  *   It also protects the <ill-ipsq> mapping
273  *   It also protects the illgroup list threaded by ill_group_next.
274  *   It also protects the <ill-phyint> assoc.
275  *   It also protects the list of ipifs hanging off the ill.
276  *
277  * - ipsq_lock: This is a per ipsq_t mutex lock.
278  *   This protects all the other members of the ipsq struct except
279  *   ipsq_refs and ipsq_phyint_list which are protected by ill_g_lock
280  *
281  * - illgrp_lock: This is a per ill_group mutex lock.
282  *   The only thing it protects is the illgrp_ill_schednext member of ill_group
283  *   which dictates which is the next ill in an ill_group that is to be chosen
284  *   for sending outgoing packets, through creation of an IRE_CACHE that
285  *   references this ill.
286  *
287  * - phyint_lock: This is a per phyint mutex lock. Protects just the
288  *   phyint_flags
289  *
290  * - ip_g_nd_lock: This is a global reader/writer lock.
291  *   Any call to nd_load to load a new parameter to the ND table must hold the
292  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
293  *   as reader.
294  *
295  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
296  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
297  *   uniqueness check also done atomically.
298  *
299  * - ipsec_capab_ills_lock: This readers/writer lock protects the global
300  *   lists of IPsec capable ills (ipsec_capab_ills_{ah,esp}). It is taken
301  *   as a writer when adding or deleting elements from these lists, and
302  *   as a reader when walking these lists to send a SADB update to the
303  *   IPsec capable ills.
304  *
305  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
306  *   group list linked by ill_usesrc_grp_next. It also protects the
307  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
308  *   group is being added or deleted.  This lock is taken as a reader when
309  *   walking the list/group(eg: to get the number of members in a usesrc group).
310  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
311  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
312  *   example, it is not necessary to take this lock in the initial portion
313  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_groupname and
314  *   ip_sioctl_flags since the these operations are executed exclusively and
315  *   that ensures that the "usesrc group state" cannot change. The "usesrc
316  *   group state" change can happen only in the latter part of
317  *   ip_sioctl_slifusesrc and in ill_delete.
318  *
319  * Changing <ill-phyint>, <ill-ipsq>, <ill-illgroup> assocications.
320  *
321  * To change the <ill-phyint> association, the ill_g_lock must be held
322  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
323  * must be held.
324  *
325  * To change the <ill-ipsq> association the ill_g_lock must be held as writer
326  * and the ill_lock of the ill in question must be held.
327  *
328  * To change the <ill-illgroup> association the ill_g_lock must be held as
329  * writer and the ill_lock of the ill in question must be held.
330  *
331  * To add or delete an ipif from the list of ipifs hanging off the ill,
332  * ill_g_lock (writer) and ill_lock must be held and the thread must be
333  * a writer on the associated ipsq,.
334  *
335  * To add or delete an ill to the system, the ill_g_lock must be held as
336  * writer and the thread must be a writer on the associated ipsq.
337  *
338  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
339  * must be a writer on the associated ipsq.
340  *
341  * Lock hierarchy
342  *
343  * Some lock hierarchy scenarios are listed below.
344  *
345  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock
346  * ill_g_lock -> illgrp_lock -> ill_lock
347  * ill_g_lock -> ill_lock(s) -> phyint_lock
348  * ill_g_lock -> ndp_g_lock -> ill_lock -> nce_lock
349  * ill_g_lock -> ip_addr_avail_lock
350  * conn_lock -> irb_lock -> ill_lock -> ire_lock
351  * ill_g_lock -> ip_g_nd_lock
352  *
353  * When more than 1 ill lock is needed to be held, all ill lock addresses
354  * are sorted on address and locked starting from highest addressed lock
355  * downward.
356  *
357  * IPsec scenarios
358  *
359  * ipsa_lock -> ill_g_lock -> ill_lock
360  * ipsec_capab_ills_lock -> ill_g_lock -> ill_lock
361  * ipsec_capab_ills_lock -> ipsa_lock
362  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
363  *
364  * Trusted Solaris scenarios
365  *
366  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
367  * igsa_lock -> gcdb_lock
368  * gcgrp_rwlock -> ire_lock
369  * gcgrp_rwlock -> gcdb_lock
370  *
371  *
372  * Routing/forwarding table locking notes:
373  *
374  * Lock acquisition order: Radix tree lock, irb_lock.
375  * Requirements:
376  * i.  Walker must not hold any locks during the walker callback.
377  * ii  Walker must not see a truncated tree during the walk because of any node
378  *     deletion.
379  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
380  *     in many places in the code to walk the irb list. Thus even if all the
381  *     ires in a bucket have been deleted, we still can't free the radix node
382  *     until the ires have actually been inactive'd (freed).
383  *
384  * Tree traversal - Need to hold the global tree lock in read mode.
385  * Before dropping the global tree lock, need to either increment the ire_refcnt
386  * to ensure that the radix node can't be deleted.
387  *
388  * Tree add - Need to hold the global tree lock in write mode to add a
389  * radix node. To prevent the node from being deleted, increment the
390  * irb_refcnt, after the node is added to the tree. The ire itself is
391  * added later while holding the irb_lock, but not the tree lock.
392  *
393  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
394  * All associated ires must be inactive (i.e. freed), and irb_refcnt
395  * must be zero.
396  *
397  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
398  * global tree lock (read mode) for traversal.
399  *
400  * IPsec notes :
401  *
402  * IP interacts with the IPsec code (AH/ESP) by tagging a M_CTL message
403  * in front of the actual packet. For outbound datagrams, the M_CTL
404  * contains a ipsec_out_t (defined in ipsec_info.h), which has the
405  * information used by the IPsec code for applying the right level of
406  * protection. The information initialized by IP in the ipsec_out_t
407  * is determined by the per-socket policy or global policy in the system.
408  * For inbound datagrams, the M_CTL contains a ipsec_in_t (defined in
409  * ipsec_info.h) which starts out with nothing in it. It gets filled
410  * with the right information if it goes through the AH/ESP code, which
411  * happens if the incoming packet is secure. The information initialized
412  * by AH/ESP, is later used by IP(during fanouts to ULP) to see whether
413  * the policy requirements needed by per-socket policy or global policy
414  * is met or not.
415  *
416  * If there is both per-socket policy (set using setsockopt) and there
417  * is also global policy match for the 5 tuples of the socket,
418  * ipsec_override_policy() makes the decision of which one to use.
419  *
420  * For fully connected sockets i.e dst, src [addr, port] is known,
421  * conn_policy_cached is set indicating that policy has been cached.
422  * conn_in_enforce_policy may or may not be set depending on whether
423  * there is a global policy match or per-socket policy match.
424  * Policy inheriting happpens in ip_bind during the ipa_conn_t bind.
425  * Once the right policy is set on the conn_t, policy cannot change for
426  * this socket. This makes life simpler for TCP (UDP ?) where
427  * re-transmissions go out with the same policy. For symmetry, policy
428  * is cached for fully connected UDP sockets also. Thus if policy is cached,
429  * it also implies that policy is latched i.e policy cannot change
430  * on these sockets. As we have the right policy on the conn, we don't
431  * have to lookup global policy for every outbound and inbound datagram
432  * and thus serving as an optimization. Note that a global policy change
433  * does not affect fully connected sockets if they have policy. If fully
434  * connected sockets did not have any policy associated with it, global
435  * policy change may affect them.
436  *
437  * IP Flow control notes:
438  *
439  * Non-TCP streams are flow controlled by IP. On the send side, if the packet
440  * cannot be sent down to the driver by IP, because of a canput failure, IP
441  * does a putq on the conn_wq. This will cause ip_wsrv to run on the conn_wq.
442  * ip_wsrv in turn, inserts the conn in a list of conn's that need to be drained
443  * when the flowcontrol condition subsides. Ultimately STREAMS backenables the
444  * ip_wsrv on the IP module, which in turn does a qenable of the conn_wq of the
445  * first conn in the list of conn's to be drained. ip_wsrv on this conn drains
446  * the queued messages, and removes the conn from the drain list, if all
447  * messages were drained. It also qenables the next conn in the drain list to
448  * continue the drain process.
449  *
450  * In reality the drain list is not a single list, but a configurable number
451  * of lists. The ip_wsrv on the IP module, qenables the first conn in each
452  * list. If the ip_wsrv of the next qenabled conn does not run, because the
453  * stream closes, ip_close takes responsibility to qenable the next conn in
454  * the drain list. The directly called ip_wput path always does a putq, if
455  * it cannot putnext. Thus synchronization problems are handled between
456  * ip_wsrv and ip_close. conn_drain_insert and conn_drain_tail are the only
457  * functions that manipulate this drain list. Furthermore conn_drain_insert
458  * is called only from ip_wsrv, and there can be only 1 instance of ip_wsrv
459  * running on a queue at any time. conn_drain_tail can be simultaneously called
460  * from both ip_wsrv and ip_close.
461  *
462  * IPQOS notes:
463  *
464  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
465  * and IPQoS modules. IPPF includes hooks in IP at different control points
466  * (callout positions) which direct packets to IPQoS modules for policy
467  * processing. Policies, if present, are global.
468  *
469  * The callout positions are located in the following paths:
470  *		o local_in (packets destined for this host)
471  *		o local_out (packets orginating from this host )
472  *		o fwd_in  (packets forwarded by this m/c - inbound)
473  *		o fwd_out (packets forwarded by this m/c - outbound)
474  * Hooks at these callout points can be enabled/disabled using the ndd variable
475  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
476  * By default all the callout positions are enabled.
477  *
478  * Outbound (local_out)
479  * Hooks are placed in ip_wput_ire and ipsec_out_process.
480  *
481  * Inbound (local_in)
482  * Hooks are placed in ip_proto_input, icmp_inbound, ip_fanout_proto and
483  * TCP and UDP fanout routines.
484  *
485  * Forwarding (in and out)
486  * Hooks are placed in ip_rput_forward.
487  *
488  * IP Policy Framework processing (IPPF processing)
489  * Policy processing for a packet is initiated by ip_process, which ascertains
490  * that the classifier (ipgpc) is loaded and configured, failing which the
491  * packet resumes normal processing in IP. If the clasifier is present, the
492  * packet is acted upon by one or more IPQoS modules (action instances), per
493  * filters configured in ipgpc and resumes normal IP processing thereafter.
494  * An action instance can drop a packet in course of its processing.
495  *
496  * A boolean variable, ip_policy, is used in all the fanout routines that can
497  * invoke ip_process for a packet. This variable indicates if the packet should
498  * to be sent for policy processing. The variable is set to B_TRUE by default,
499  * i.e. when the routines are invoked in the normal ip procesing path for a
500  * packet. The two exceptions being ip_wput_local and icmp_inbound_error_fanout;
501  * ip_policy is set to B_FALSE for all the routines called in these two
502  * functions because, in the former case,  we don't process loopback traffic
503  * currently while in the latter, the packets have already been processed in
504  * icmp_inbound.
505  *
506  * Zones notes:
507  *
508  * The partitioning rules for networking are as follows:
509  * 1) Packets coming from a zone must have a source address belonging to that
510  * zone.
511  * 2) Packets coming from a zone can only be sent on a physical interface on
512  * which the zone has an IP address.
513  * 3) Between two zones on the same machine, packet delivery is only allowed if
514  * there's a matching route for the destination and zone in the forwarding
515  * table.
516  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
517  * different zones can bind to the same port with the wildcard address
518  * (INADDR_ANY).
519  *
520  * The granularity of interface partitioning is at the logical interface level.
521  * Therefore, every zone has its own IP addresses, and incoming packets can be
522  * attributed to a zone unambiguously. A logical interface is placed into a zone
523  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
524  * structure. Rule (1) is implemented by modifying the source address selection
525  * algorithm so that the list of eligible addresses is filtered based on the
526  * sending process zone.
527  *
528  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
529  * across all zones, depending on their type. Here is the break-up:
530  *
531  * IRE type				Shared/exclusive
532  * --------				----------------
533  * IRE_BROADCAST			Exclusive
534  * IRE_DEFAULT (default routes)		Shared (*)
535  * IRE_LOCAL				Exclusive (x)
536  * IRE_LOOPBACK				Exclusive
537  * IRE_PREFIX (net routes)		Shared (*)
538  * IRE_CACHE				Exclusive
539  * IRE_IF_NORESOLVER (interface routes)	Exclusive
540  * IRE_IF_RESOLVER (interface routes)	Exclusive
541  * IRE_HOST (host routes)		Shared (*)
542  *
543  * (*) A zone can only use a default or off-subnet route if the gateway is
544  * directly reachable from the zone, that is, if the gateway's address matches
545  * one of the zone's logical interfaces.
546  *
547  * (x) IRE_LOCAL are handled a bit differently, since for all other entries
548  * in ire_ctable and IRE_INTERFACE, ire_src_addr is what can be used as source
549  * when sending packets using the IRE. For IRE_LOCAL ire_src_addr is the IP
550  * address of the zone itself (the destination). Since IRE_LOCAL is used
551  * for communication between zones, ip_wput_ire has special logic to set
552  * the right source address when sending using an IRE_LOCAL.
553  *
554  * Furthermore, when ip_restrict_interzone_loopback is set (the default),
555  * ire_cache_lookup restricts loopback using an IRE_LOCAL
556  * between zone to the case when L2 would have conceptually looped the packet
557  * back, i.e. the loopback which is required since neither Ethernet drivers
558  * nor Ethernet hardware loops them back. This is the case when the normal
559  * routes (ignoring IREs with different zoneids) would send out the packet on
560  * the same ill (or ill group) as the ill with which is IRE_LOCAL is
561  * associated.
562  *
563  * Multiple zones can share a common broadcast address; typically all zones
564  * share the 255.255.255.255 address. Incoming as well as locally originated
565  * broadcast packets must be dispatched to all the zones on the broadcast
566  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
567  * since some zones may not be on the 10.16.72/24 network. To handle this, each
568  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
569  * sent to every zone that has an IRE_BROADCAST entry for the destination
570  * address on the input ill, see conn_wantpacket().
571  *
572  * Applications in different zones can join the same multicast group address.
573  * For IPv4, group memberships are per-logical interface, so they're already
574  * inherently part of a zone. For IPv6, group memberships are per-physical
575  * interface, so we distinguish IPv6 group memberships based on group address,
576  * interface and zoneid. In both cases, received multicast packets are sent to
577  * every zone for which a group membership entry exists. On IPv6 we need to
578  * check that the target zone still has an address on the receiving physical
579  * interface; it could have been removed since the application issued the
580  * IPV6_JOIN_GROUP.
581  */
582 
583 /*
584  * Squeue Fanout flags:
585  *	0: No fanout.
586  *	1: Fanout across all squeues
587  */
588 boolean_t	ip_squeue_fanout = 0;
589 
590 /*
591  * Maximum dups allowed per packet.
592  */
593 uint_t ip_max_frag_dups = 10;
594 
595 #define	IS_SIMPLE_IPH(ipha)						\
596 	((ipha)->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION)
597 
598 /* RFC1122 Conformance */
599 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
600 
601 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
602 
603 static int	conn_set_held_ipif(conn_t *, ipif_t **, ipif_t *);
604 
605 static int	ip_open(queue_t *q, dev_t *devp, int flag, int sflag,
606 		    cred_t *credp, boolean_t isv6);
607 static mblk_t	*ip_wput_attach_llhdr(mblk_t *, ire_t *, ip_proc_t, uint32_t);
608 
609 static void	icmp_frag_needed(queue_t *, mblk_t *, int, zoneid_t,
610 		    ip_stack_t *);
611 static void	icmp_inbound(queue_t *, mblk_t *, boolean_t, ill_t *, int,
612 		    uint32_t, boolean_t, boolean_t, ill_t *, zoneid_t);
613 static ipaddr_t	icmp_get_nexthop_addr(ipha_t *, ill_t *, zoneid_t, mblk_t *mp);
614 static boolean_t icmp_inbound_too_big(icmph_t *, ipha_t *, ill_t *, zoneid_t,
615 		    mblk_t *, int, ip_stack_t *);
616 static void	icmp_inbound_error_fanout(queue_t *, ill_t *, mblk_t *,
617 		    icmph_t *, ipha_t *, int, int, boolean_t, boolean_t,
618 		    ill_t *, zoneid_t);
619 static void	icmp_options_update(ipha_t *);
620 static void	icmp_param_problem(queue_t *, mblk_t *, uint8_t, zoneid_t,
621 		    ip_stack_t *);
622 static void	icmp_pkt(queue_t *, mblk_t *, void *, size_t, boolean_t,
623 		    zoneid_t zoneid, ip_stack_t *);
624 static mblk_t	*icmp_pkt_err_ok(mblk_t *, ip_stack_t *);
625 static void	icmp_redirect(ill_t *, mblk_t *);
626 static void	icmp_send_redirect(queue_t *, mblk_t *, ipaddr_t,
627 		    ip_stack_t *);
628 
629 static void	ip_arp_news(queue_t *, mblk_t *);
630 static boolean_t ip_bind_insert_ire(mblk_t *, ire_t *, iulp_t *,
631 		    ip_stack_t *);
632 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
633 char		*ip_dot_addr(ipaddr_t, char *);
634 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
635 int		ip_close(queue_t *, int);
636 static char	*ip_dot_saddr(uchar_t *, char *);
637 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
638 		    boolean_t, boolean_t, ill_t *, zoneid_t);
639 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
640 		    boolean_t, boolean_t, zoneid_t);
641 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
642 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
643 static void	ip_lrput(queue_t *, mblk_t *);
644 ipaddr_t	ip_net_mask(ipaddr_t);
645 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, conn_t *, zoneid_t,
646 		    ip_stack_t *);
647 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
648 		    conn_t *, uint32_t, zoneid_t, ip_opt_info_t *);
649 char		*ip_nv_lookup(nv_t *, int);
650 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
651 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
652 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
653 static boolean_t	ip_param_register(IDP *ndp, ipparam_t *, size_t,
654     ipndp_t *, size_t);
655 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
656 void	ip_rput(queue_t *, mblk_t *);
657 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
658 		    void *dummy_arg);
659 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
660 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *,
661     ip_stack_t *);
662 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
663 			    ire_t *, ip_stack_t *);
664 static boolean_t	ip_rput_multimblk_ipoptions(queue_t *, ill_t *,
665 			    mblk_t *, ipha_t **, ipaddr_t *, ip_stack_t *);
666 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *,
667     ip_stack_t *);
668 static boolean_t ip_rput_fragment(queue_t *, mblk_t **, ipha_t *, uint32_t *,
669 		    uint16_t *);
670 int		ip_snmp_get(queue_t *, mblk_t *, int);
671 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *,
672 		    mib2_ipIfStatsEntry_t *, ip_stack_t *);
673 static mblk_t	*ip_snmp_get_mib2_ip_traffic_stats(queue_t *, mblk_t *,
674 		    ip_stack_t *);
675 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *, ip_stack_t *);
676 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *, ip_stack_t *ipst);
677 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *, ip_stack_t *ipst);
678 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *, ip_stack_t *ipst);
679 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *, ip_stack_t *ipst);
680 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *,
681 		    ip_stack_t *ipst);
682 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *,
683 		    ip_stack_t *ipst);
684 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *,
685 		    ip_stack_t *ipst);
686 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *,
687 		    ip_stack_t *ipst);
688 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *,
689 		    ip_stack_t *ipst);
690 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *,
691 		    ip_stack_t *ipst);
692 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *,
693 		    ip_stack_t *ipst);
694 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *,
695 		    ip_stack_t *ipst);
696 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *,
697 		    ip_stack_t *ipst);
698 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *,
699 		    ip_stack_t *ipst);
700 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
701 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
702 static int	ip_snmp_get2_v6_media(nce_t *, iproutedata_t *);
703 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
704 static boolean_t	ip_source_routed(ipha_t *, ip_stack_t *);
705 static boolean_t	ip_source_route_included(ipha_t *);
706 static void	ip_trash_ire_reclaim_stack(ip_stack_t *);
707 
708 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t,
709 		    zoneid_t, ip_stack_t *);
710 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int, ip_stack_t *);
711 static void	ip_wput_local_options(ipha_t *, ip_stack_t *);
712 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
713 		    zoneid_t, ip_stack_t *);
714 
715 static void	conn_drain_init(ip_stack_t *);
716 static void	conn_drain_fini(ip_stack_t *);
717 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
718 
719 static void	conn_walk_drain(ip_stack_t *);
720 static void	conn_walk_fanout_table(connf_t *, uint_t, pfv_t, void *,
721     zoneid_t);
722 
723 static void	*ip_stack_init(netstackid_t stackid, netstack_t *ns);
724 static void	ip_stack_shutdown(netstackid_t stackid, void *arg);
725 static void	ip_stack_fini(netstackid_t stackid, void *arg);
726 
727 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
728     zoneid_t);
729 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
730     void *dummy_arg);
731 
732 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
733 
734 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
735     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
736     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
737 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
738 
739 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
740 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
741     caddr_t, cred_t *);
742 extern int	ip_squeue_bind_set(queue_t *q, mblk_t *mp, char *value,
743     caddr_t cp, cred_t *cr);
744 extern int	ip_squeue_profile_set(queue_t *, mblk_t *, char *, caddr_t,
745     cred_t *);
746 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
747     caddr_t cp, cred_t *cr);
748 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
749     cred_t *);
750 static int	ipmp_hook_emulation_set(queue_t *, mblk_t *, char *, caddr_t,
751     cred_t *);
752 static squeue_func_t ip_squeue_switch(int);
753 
754 static void	*ip_kstat_init(netstackid_t, ip_stack_t *);
755 static void	ip_kstat_fini(netstackid_t, kstat_t *);
756 static int	ip_kstat_update(kstat_t *kp, int rw);
757 static void	*icmp_kstat_init(netstackid_t);
758 static void	icmp_kstat_fini(netstackid_t, kstat_t *);
759 static int	icmp_kstat_update(kstat_t *kp, int rw);
760 static void	*ip_kstat2_init(netstackid_t, ip_stat_t *);
761 static void	ip_kstat2_fini(netstackid_t, kstat_t *);
762 
763 static int	ip_conn_report(queue_t *, mblk_t *, caddr_t, cred_t *);
764 
765 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
766     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
767 
768 static void	ip_rput_process_forward(queue_t *, mblk_t *, ire_t *,
769     ipha_t *, ill_t *, boolean_t);
770 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
771 
772 /* How long, in seconds, we allow frags to hang around. */
773 #define	IP_FRAG_TIMEOUT	60
774 
775 /*
776  * Threshold which determines whether MDT should be used when
777  * generating IP fragments; payload size must be greater than
778  * this threshold for MDT to take place.
779  */
780 #define	IP_WPUT_FRAG_MDT_MIN	32768
781 
782 /* Setable in /etc/system only */
783 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
784 
785 static long ip_rput_pullups;
786 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
787 
788 vmem_t *ip_minor_arena;
789 
790 int	ip_debug;
791 
792 #ifdef DEBUG
793 uint32_t ipsechw_debug = 0;
794 #endif
795 
796 /*
797  * Multirouting/CGTP stuff
798  */
799 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
800 
801 /*
802  * XXX following really should only be in a header. Would need more
803  * header and .c clean up first.
804  */
805 extern optdb_obj_t	ip_opt_obj;
806 
807 ulong_t ip_squeue_enter_unbound = 0;
808 
809 /*
810  * Named Dispatch Parameter Table.
811  * All of these are alterable, within the min/max values given, at run time.
812  */
813 static ipparam_t	lcl_param_arr[] = {
814 	/* min	max	value	name */
815 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
816 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
817 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
818 	{  0,	1,	0,	"ip_respond_to_timestamp"},
819 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
820 	{  0,	1,	1,	"ip_send_redirects"},
821 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
822 	{  0,	10,	0,	"ip_mrtdebug"},
823 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
824 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
825 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
826 	{  1,	255,	255,	"ip_def_ttl" },
827 	{  0,	1,	0,	"ip_forward_src_routed"},
828 	{  0,	256,	32,	"ip_wroff_extra" },
829 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
830 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
831 	{  0,	1,	1,	"ip_path_mtu_discovery" },
832 	{  0,	240,	30,	"ip_ignore_delete_time" },
833 	{  0,	1,	0,	"ip_ignore_redirect" },
834 	{  0,	1,	1,	"ip_output_queue" },
835 	{  1,	254,	1,	"ip_broadcast_ttl" },
836 	{  0,	99999,	100,	"ip_icmp_err_interval" },
837 	{  1,	99999,	10,	"ip_icmp_err_burst" },
838 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
839 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
840 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
841 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
842 	{  0,	1,	1,	"icmp_accept_clear_messages" },
843 	{  0,	1,	1,	"igmp_accept_clear_messages" },
844 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
845 				"ip_ndp_delay_first_probe_time"},
846 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
847 				"ip_ndp_max_unicast_solicit"},
848 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
849 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
850 	{  0,	1,	0,	"ip6_forward_src_routed"},
851 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
852 	{  0,	1,	1,	"ip6_send_redirects"},
853 	{  0,	1,	0,	"ip6_ignore_redirect" },
854 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
855 
856 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
857 
858 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
859 
860 	{  0,	1,	1,	"pim_accept_clear_messages" },
861 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
862 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
863 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
864 	{  0,	15,	0,	"ip_policy_mask" },
865 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
866 	{  0,	255,	1,	"ip_multirt_ttl" },
867 	{  0,	1,	1,	"ip_multidata_outbound" },
868 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
869 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
870 	{  0,	1000,	1,	"ip_max_temp_defend" },
871 	{  0,	1000,	3,	"ip_max_defend" },
872 	{  0,	999999,	30,	"ip_defend_interval" },
873 	{  0,	3600000, 300000, "ip_dup_recovery" },
874 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
875 	{  0,	1,	1,	"ip_lso_outbound" },
876 	{  IGMP_V1_ROUTER, IGMP_V3_ROUTER, IGMP_V3_ROUTER, "igmp_max_version" },
877 	{  MLD_V1_ROUTER, MLD_V2_ROUTER, MLD_V2_ROUTER, "mld_max_version" },
878 #ifdef DEBUG
879 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
880 #else
881 	{  0,	0,	0,	"" },
882 #endif
883 };
884 
885 /*
886  * Extended NDP table
887  * The addresses for the first two are filled in to be ips_ip_g_forward
888  * and ips_ipv6_forward at init time.
889  */
890 static ipndp_t	lcl_ndp_arr[] = {
891 	/* getf			setf		data			name */
892 #define	IPNDP_IP_FORWARDING_OFFSET	0
893 	{  ip_param_generic_get,	ip_forward_set,	NULL,
894 	    "ip_forwarding" },
895 #define	IPNDP_IP6_FORWARDING_OFFSET	1
896 	{  ip_param_generic_get,	ip_forward_set,	NULL,
897 	    "ip6_forwarding" },
898 	{  ip_ill_report,	NULL,		NULL,
899 	    "ip_ill_status" },
900 	{  ip_ipif_report,	NULL,		NULL,
901 	    "ip_ipif_status" },
902 	{  ip_ire_report,	NULL,		NULL,
903 	    "ipv4_ire_status" },
904 	{  ip_ire_report_v6,	NULL,		NULL,
905 	    "ipv6_ire_status" },
906 	{  ip_conn_report,	NULL,		NULL,
907 	    "ip_conn_status" },
908 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
909 	    "ip_rput_pullups" },
910 	{  ndp_report,		NULL,		NULL,
911 	    "ip_ndp_cache_report" },
912 	{  ip_srcid_report,	NULL,		NULL,
913 	    "ip_srcid_status" },
914 	{ ip_param_generic_get, ip_squeue_profile_set,
915 	    (caddr_t)&ip_squeue_profile, "ip_squeue_profile" },
916 	{ ip_param_generic_get, ip_squeue_bind_set,
917 	    (caddr_t)&ip_squeue_bind, "ip_squeue_bind" },
918 	{ ip_param_generic_get, ip_input_proc_set,
919 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
920 	{ ip_param_generic_get, ip_int_set,
921 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
922 #define	IPNDP_CGTP_FILTER_OFFSET	14
923 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, NULL,
924 	    "ip_cgtp_filter" },
925 	{ ip_param_generic_get, ip_int_set,
926 	    (caddr_t)&ip_soft_rings_cnt, "ip_soft_rings_cnt" },
927 #define	IPNDP_IPMP_HOOK_OFFSET	16
928 	{  ip_param_generic_get, ipmp_hook_emulation_set, NULL,
929 	    "ipmp_hook_emulation" },
930 	{  ip_param_generic_get, ip_int_set, (caddr_t)&ip_debug,
931 	    "ip_debug" },
932 };
933 
934 /*
935  * Table of IP ioctls encoding the various properties of the ioctl and
936  * indexed based on the last byte of the ioctl command. Occasionally there
937  * is a clash, and there is more than 1 ioctl with the same last byte.
938  * In such a case 1 ioctl is encoded in the ndx table and the remaining
939  * ioctls are encoded in the misc table. An entry in the ndx table is
940  * retrieved by indexing on the last byte of the ioctl command and comparing
941  * the ioctl command with the value in the ndx table. In the event of a
942  * mismatch the misc table is then searched sequentially for the desired
943  * ioctl command.
944  *
945  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
946  */
947 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
948 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
949 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
950 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
951 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
952 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
953 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
954 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
955 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
956 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
957 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
958 
959 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
960 			MISC_CMD, ip_siocaddrt, NULL },
961 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
962 			MISC_CMD, ip_siocdelrt, NULL },
963 
964 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
965 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
966 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
967 			IF_CMD, ip_sioctl_get_addr, NULL },
968 
969 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
970 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
971 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
972 			IPI_GET_CMD | IPI_REPL,
973 			IF_CMD, ip_sioctl_get_dstaddr, NULL },
974 
975 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
976 			IPI_PRIV | IPI_WR | IPI_REPL,
977 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
978 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
979 			IPI_MODOK | IPI_GET_CMD | IPI_REPL,
980 			IF_CMD, ip_sioctl_get_flags, NULL },
981 
982 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
983 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
984 
985 	/* copyin size cannot be coded for SIOCGIFCONF */
986 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD,
987 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
988 
989 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
990 			IF_CMD, ip_sioctl_mtu, NULL },
991 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
992 			IF_CMD, ip_sioctl_get_mtu, NULL },
993 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
994 			IPI_GET_CMD | IPI_REPL,
995 			IF_CMD, ip_sioctl_get_brdaddr, NULL },
996 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
997 			IF_CMD, ip_sioctl_brdaddr, NULL },
998 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
999 			IPI_GET_CMD | IPI_REPL,
1000 			IF_CMD, ip_sioctl_get_netmask, NULL },
1001 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1002 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1003 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1004 			IPI_GET_CMD | IPI_REPL,
1005 			IF_CMD, ip_sioctl_get_metric, NULL },
1006 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1007 			IF_CMD, ip_sioctl_metric, NULL },
1008 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1009 
1010 	/* See 166-168 below for extended SIOC*XARP ioctls */
1011 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV,
1012 			ARP_CMD, ip_sioctl_arp, NULL },
1013 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD | IPI_REPL,
1014 			ARP_CMD, ip_sioctl_arp, NULL },
1015 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV,
1016 			ARP_CMD, ip_sioctl_arp, NULL },
1017 
1018 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1019 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1020 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1021 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1022 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1023 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1024 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1025 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1026 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1027 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1028 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1029 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1030 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1031 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1032 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1033 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1034 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1035 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1036 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1037 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1038 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1039 
1040 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1041 			MISC_CMD, if_unitsel, if_unitsel_restart },
1042 
1043 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1044 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1045 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1046 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1047 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1048 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1049 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1050 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1051 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1052 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1053 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1054 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1055 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1056 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1057 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1058 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1059 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1060 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1061 
1062 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1063 			IPI_PRIV | IPI_WR | IPI_MODOK,
1064 			IF_CMD, ip_sioctl_sifname, NULL },
1065 
1066 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1067 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1068 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1069 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1070 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1071 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1072 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1073 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1074 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1075 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1076 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1077 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1078 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1079 
1080 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD | IPI_REPL,
1081 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1082 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1083 			IF_CMD, ip_sioctl_get_muxid, NULL },
1084 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1085 			IPI_PRIV | IPI_WR | IPI_REPL,
1086 			IF_CMD, ip_sioctl_muxid, NULL },
1087 
1088 	/* Both if and lif variants share same func */
1089 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1090 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1091 	/* Both if and lif variants share same func */
1092 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1093 			IPI_PRIV | IPI_WR | IPI_REPL,
1094 			IF_CMD, ip_sioctl_slifindex, NULL },
1095 
1096 	/* copyin size cannot be coded for SIOCGIFCONF */
1097 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD,
1098 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1099 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1100 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1101 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1102 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1103 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1104 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1105 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1106 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1107 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1108 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1109 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1110 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1111 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1112 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1113 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1114 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1115 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1116 
1117 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1118 			IPI_PRIV | IPI_WR | IPI_REPL,
1119 			LIF_CMD, ip_sioctl_removeif,
1120 			ip_sioctl_removeif_restart },
1121 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1122 			IPI_GET_CMD | IPI_PRIV | IPI_WR | IPI_REPL,
1123 			LIF_CMD, ip_sioctl_addif, NULL },
1124 #define	SIOCLIFADDR_NDX 112
1125 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1126 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1127 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1128 			IPI_GET_CMD | IPI_REPL,
1129 			LIF_CMD, ip_sioctl_get_addr, NULL },
1130 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1131 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1132 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1133 			IPI_GET_CMD | IPI_REPL,
1134 			LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1135 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1136 			IPI_PRIV | IPI_WR | IPI_REPL,
1137 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1138 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1139 			IPI_GET_CMD | IPI_MODOK | IPI_REPL,
1140 			LIF_CMD, ip_sioctl_get_flags, NULL },
1141 
1142 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1143 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1144 
1145 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1146 			ip_sioctl_get_lifconf, NULL },
1147 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1148 			LIF_CMD, ip_sioctl_mtu, NULL },
1149 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD | IPI_REPL,
1150 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1151 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1152 			IPI_GET_CMD | IPI_REPL,
1153 			LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1154 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1155 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1156 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1157 			IPI_GET_CMD | IPI_REPL,
1158 			LIF_CMD, ip_sioctl_get_netmask, NULL },
1159 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1160 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1161 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1162 			IPI_GET_CMD | IPI_REPL,
1163 			LIF_CMD, ip_sioctl_get_metric, NULL },
1164 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1165 			LIF_CMD, ip_sioctl_metric, NULL },
1166 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1167 			IPI_PRIV | IPI_WR | IPI_MODOK | IPI_REPL,
1168 			LIF_CMD, ip_sioctl_slifname,
1169 			ip_sioctl_slifname_restart },
1170 
1171 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD | IPI_REPL,
1172 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1173 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1174 			IPI_GET_CMD | IPI_REPL,
1175 			LIF_CMD, ip_sioctl_get_muxid, NULL },
1176 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1177 			IPI_PRIV | IPI_WR | IPI_REPL,
1178 			LIF_CMD, ip_sioctl_muxid, NULL },
1179 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1180 			IPI_GET_CMD | IPI_REPL,
1181 			LIF_CMD, ip_sioctl_get_lifindex, 0 },
1182 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1183 			IPI_PRIV | IPI_WR | IPI_REPL,
1184 			LIF_CMD, ip_sioctl_slifindex, 0 },
1185 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1186 			LIF_CMD, ip_sioctl_token, NULL },
1187 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1188 			IPI_GET_CMD | IPI_REPL,
1189 			LIF_CMD, ip_sioctl_get_token, NULL },
1190 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1191 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1192 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1193 			IPI_GET_CMD | IPI_REPL,
1194 			LIF_CMD, ip_sioctl_get_subnet, NULL },
1195 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1196 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1197 
1198 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1199 			IPI_GET_CMD | IPI_REPL,
1200 			LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1201 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1202 			LIF_CMD, ip_siocdelndp_v6, NULL },
1203 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1204 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1205 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1206 			LIF_CMD, ip_siocsetndp_v6, NULL },
1207 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1208 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1209 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1210 			MISC_CMD, ip_sioctl_tonlink, NULL },
1211 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1212 			MISC_CMD, ip_sioctl_tmysite, NULL },
1213 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), IPI_REPL,
1214 			TUN_CMD, ip_sioctl_tunparam, NULL },
1215 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1216 			IPI_PRIV | IPI_WR,
1217 			TUN_CMD, ip_sioctl_tunparam, NULL },
1218 
1219 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1220 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1221 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1222 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1223 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1224 
1225 	/* 153 */ { SIOCLIFFAILOVER, sizeof (struct lifreq),
1226 			IPI_PRIV | IPI_WR | IPI_REPL,
1227 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1228 	/* 154 */ { SIOCLIFFAILBACK, sizeof (struct lifreq),
1229 			IPI_PRIV | IPI_WR | IPI_REPL,
1230 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1231 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1232 			IPI_PRIV | IPI_WR,
1233 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1234 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1235 			IPI_GET_CMD | IPI_REPL,
1236 			LIF_CMD, ip_sioctl_get_groupname, NULL },
1237 	/* 157 */ { SIOCGLIFOINDEX, sizeof (struct lifreq),
1238 			IPI_GET_CMD | IPI_REPL,
1239 			LIF_CMD, ip_sioctl_get_oindex, NULL },
1240 
1241 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1242 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1243 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1244 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1245 
1246 	/* 161 */ { SIOCSLIFOINDEX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1247 		    LIF_CMD, ip_sioctl_slifoindex, NULL },
1248 
1249 	/* These are handled in ip_sioctl_copyin_setup itself */
1250 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1251 			MISC_CMD, NULL, NULL },
1252 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1253 			MISC_CMD, NULL, NULL },
1254 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1255 
1256 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1257 			ip_sioctl_get_lifconf, NULL },
1258 
1259 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV,
1260 			XARP_CMD, ip_sioctl_arp, NULL },
1261 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD | IPI_REPL,
1262 			XARP_CMD, ip_sioctl_arp, NULL },
1263 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV,
1264 			XARP_CMD, ip_sioctl_arp, NULL },
1265 
1266 	/* SIOCPOPSOCKFS is not handled by IP */
1267 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1268 
1269 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1270 			IPI_GET_CMD | IPI_REPL,
1271 			LIF_CMD, ip_sioctl_get_lifzone, NULL },
1272 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1273 			IPI_PRIV | IPI_WR | IPI_REPL,
1274 			LIF_CMD, ip_sioctl_slifzone,
1275 			ip_sioctl_slifzone_restart },
1276 	/* 172-174 are SCTP ioctls and not handled by IP */
1277 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1278 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1279 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1280 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1281 			IPI_GET_CMD, LIF_CMD,
1282 			ip_sioctl_get_lifusesrc, 0 },
1283 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1284 			IPI_PRIV | IPI_WR,
1285 			LIF_CMD, ip_sioctl_slifusesrc,
1286 			NULL },
1287 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1288 			ip_sioctl_get_lifsrcof, NULL },
1289 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1290 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1291 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1292 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1293 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1294 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1295 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1296 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1297 	/* 182 */ { SIOCSIPMPFAILBACK, sizeof (int), IPI_PRIV, MISC_CMD,
1298 			ip_sioctl_set_ipmpfailback, NULL },
1299 	/* SIOCSENABLESDP is handled by SDP */
1300 	/* 183 */ { IPI_DONTCARE /* SIOCSENABLESDP */, 0, 0, 0, NULL, NULL },
1301 };
1302 
1303 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1304 
1305 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1306 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1307 		IPI_GET_CMD | IPI_REPL, TUN_CMD, ip_sioctl_tunparam, NULL },
1308 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1309 		TUN_CMD, ip_sioctl_tunparam, NULL },
1310 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1311 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1312 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1313 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1314 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1315 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1316 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1317 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_REPL | IPI_GET_CMD,
1318 		MISC_CMD, mrt_ioctl},
1319 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_REPL | IPI_GET_CMD,
1320 		MISC_CMD, mrt_ioctl},
1321 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_REPL | IPI_GET_CMD,
1322 		MISC_CMD, mrt_ioctl}
1323 };
1324 
1325 int ip_misc_ioctl_count =
1326     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1327 
1328 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1329 					/* Settable in /etc/system */
1330 /* Defined in ip_ire.c */
1331 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1332 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1333 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1334 
1335 static nv_t	ire_nv_arr[] = {
1336 	{ IRE_BROADCAST, "BROADCAST" },
1337 	{ IRE_LOCAL, "LOCAL" },
1338 	{ IRE_LOOPBACK, "LOOPBACK" },
1339 	{ IRE_CACHE, "CACHE" },
1340 	{ IRE_DEFAULT, "DEFAULT" },
1341 	{ IRE_PREFIX, "PREFIX" },
1342 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1343 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1344 	{ IRE_HOST, "HOST" },
1345 	{ 0 }
1346 };
1347 
1348 nv_t	*ire_nv_tbl = ire_nv_arr;
1349 
1350 /* Defined in ip_netinfo.c */
1351 extern ddi_taskq_t	*eventq_queue_nic;
1352 
1353 /* Simple ICMP IP Header Template */
1354 static ipha_t icmp_ipha = {
1355 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1356 };
1357 
1358 struct module_info ip_mod_info = {
1359 	IP_MOD_ID, IP_MOD_NAME, 1, INFPSZ, 65536, 1024
1360 };
1361 
1362 /*
1363  * Duplicate static symbols within a module confuses mdb; so we avoid the
1364  * problem by making the symbols here distinct from those in udp.c.
1365  */
1366 
1367 /*
1368  * Entry points for IP as a device and as a module.
1369  * FIXME: down the road we might want a separate module and driver qinit.
1370  * We have separate open functions for the /dev/ip and /dev/ip6 devices.
1371  */
1372 static struct qinit iprinitv4 = {
1373 	(pfi_t)ip_rput, NULL, ip_openv4, ip_close, NULL,
1374 	&ip_mod_info
1375 };
1376 
1377 struct qinit iprinitv6 = {
1378 	(pfi_t)ip_rput_v6, NULL, ip_openv6, ip_close, NULL,
1379 	&ip_mod_info
1380 };
1381 
1382 static struct qinit ipwinitv4 = {
1383 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1384 	&ip_mod_info
1385 };
1386 
1387 struct qinit ipwinitv6 = {
1388 	(pfi_t)ip_wput_v6, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1389 	&ip_mod_info
1390 };
1391 
1392 static struct qinit iplrinit = {
1393 	(pfi_t)ip_lrput, NULL, ip_openv4, ip_close, NULL,
1394 	&ip_mod_info
1395 };
1396 
1397 static struct qinit iplwinit = {
1398 	(pfi_t)ip_lwput, NULL, NULL, NULL, NULL,
1399 	&ip_mod_info
1400 };
1401 
1402 /* For AF_INET aka /dev/ip */
1403 struct streamtab ipinfov4 = {
1404 	&iprinitv4, &ipwinitv4, &iplrinit, &iplwinit
1405 };
1406 
1407 /* For AF_INET6 aka /dev/ip6 */
1408 struct streamtab ipinfov6 = {
1409 	&iprinitv6, &ipwinitv6, &iplrinit, &iplwinit
1410 };
1411 
1412 #ifdef	DEBUG
1413 static boolean_t skip_sctp_cksum = B_FALSE;
1414 #endif
1415 
1416 /*
1417  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1418  * ip_rput_v6(), ip_output(), etc.  If the message
1419  * block already has a M_CTL at the front of it, then simply set the zoneid
1420  * appropriately.
1421  */
1422 mblk_t *
1423 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid, ip_stack_t *ipst)
1424 {
1425 	mblk_t		*first_mp;
1426 	ipsec_out_t	*io;
1427 
1428 	ASSERT(zoneid != ALL_ZONES);
1429 	if (mp->b_datap->db_type == M_CTL) {
1430 		io = (ipsec_out_t *)mp->b_rptr;
1431 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1432 		io->ipsec_out_zoneid = zoneid;
1433 		return (mp);
1434 	}
1435 
1436 	first_mp = ipsec_alloc_ipsec_out(ipst->ips_netstack);
1437 	if (first_mp == NULL)
1438 		return (NULL);
1439 	io = (ipsec_out_t *)first_mp->b_rptr;
1440 	/* This is not a secure packet */
1441 	io->ipsec_out_secure = B_FALSE;
1442 	io->ipsec_out_zoneid = zoneid;
1443 	first_mp->b_cont = mp;
1444 	return (first_mp);
1445 }
1446 
1447 /*
1448  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1449  */
1450 mblk_t *
1451 ip_copymsg(mblk_t *mp)
1452 {
1453 	mblk_t *nmp;
1454 	ipsec_info_t *in;
1455 
1456 	if (mp->b_datap->db_type != M_CTL)
1457 		return (copymsg(mp));
1458 
1459 	in = (ipsec_info_t *)mp->b_rptr;
1460 
1461 	/*
1462 	 * Note that M_CTL is also used for delivering ICMP error messages
1463 	 * upstream to transport layers.
1464 	 */
1465 	if (in->ipsec_info_type != IPSEC_OUT &&
1466 	    in->ipsec_info_type != IPSEC_IN)
1467 		return (copymsg(mp));
1468 
1469 	nmp = copymsg(mp->b_cont);
1470 
1471 	if (in->ipsec_info_type == IPSEC_OUT) {
1472 		return (ipsec_out_tag(mp, nmp,
1473 		    ((ipsec_out_t *)in)->ipsec_out_ns));
1474 	} else {
1475 		return (ipsec_in_tag(mp, nmp,
1476 		    ((ipsec_in_t *)in)->ipsec_in_ns));
1477 	}
1478 }
1479 
1480 /* Generate an ICMP fragmentation needed message. */
1481 static void
1482 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid,
1483     ip_stack_t *ipst)
1484 {
1485 	icmph_t	icmph;
1486 	mblk_t *first_mp;
1487 	boolean_t mctl_present;
1488 
1489 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1490 
1491 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
1492 		if (mctl_present)
1493 			freeb(first_mp);
1494 		return;
1495 	}
1496 
1497 	bzero(&icmph, sizeof (icmph_t));
1498 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1499 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1500 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1501 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1502 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1503 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
1504 	    ipst);
1505 }
1506 
1507 /*
1508  * icmp_inbound deals with ICMP messages in the following ways.
1509  *
1510  * 1) It needs to send a reply back and possibly delivering it
1511  *    to the "interested" upper clients.
1512  * 2) It needs to send it to the upper clients only.
1513  * 3) It needs to change some values in IP only.
1514  * 4) It needs to change some values in IP and upper layers e.g TCP.
1515  *
1516  * We need to accomodate icmp messages coming in clear until we get
1517  * everything secure from the wire. If icmp_accept_clear_messages
1518  * is zero we check with the global policy and act accordingly. If
1519  * it is non-zero, we accept the message without any checks. But
1520  * *this does not mean* that this will be delivered to the upper
1521  * clients. By accepting we might send replies back, change our MTU
1522  * value etc. but delivery to the ULP/clients depends on their policy
1523  * dispositions.
1524  *
1525  * We handle the above 4 cases in the context of IPsec in the
1526  * following way :
1527  *
1528  * 1) Send the reply back in the same way as the request came in.
1529  *    If it came in encrypted, it goes out encrypted. If it came in
1530  *    clear, it goes out in clear. Thus, this will prevent chosen
1531  *    plain text attack.
1532  * 2) The client may or may not expect things to come in secure.
1533  *    If it comes in secure, the policy constraints are checked
1534  *    before delivering it to the upper layers. If it comes in
1535  *    clear, ipsec_inbound_accept_clear will decide whether to
1536  *    accept this in clear or not. In both the cases, if the returned
1537  *    message (IP header + 8 bytes) that caused the icmp message has
1538  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1539  *    sending up. If there are only 8 bytes of returned message, then
1540  *    upper client will not be notified.
1541  * 3) Check with global policy to see whether it matches the constaints.
1542  *    But this will be done only if icmp_accept_messages_in_clear is
1543  *    zero.
1544  * 4) If we need to change both in IP and ULP, then the decision taken
1545  *    while affecting the values in IP and while delivering up to TCP
1546  *    should be the same.
1547  *
1548  * 	There are two cases.
1549  *
1550  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1551  *	   failed), we will not deliver it to the ULP, even though they
1552  *	   are *willing* to accept in *clear*. This is fine as our global
1553  *	   disposition to icmp messages asks us reject the datagram.
1554  *
1555  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1556  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1557  *	   to deliver it to ULP (policy failed), it can lead to
1558  *	   consistency problems. The cases known at this time are
1559  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1560  *	   values :
1561  *
1562  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1563  *	     and Upper layer rejects. Then the communication will
1564  *	     come to a stop. This is solved by making similar decisions
1565  *	     at both levels. Currently, when we are unable to deliver
1566  *	     to the Upper Layer (due to policy failures) while IP has
1567  *	     adjusted ire_max_frag, the next outbound datagram would
1568  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1569  *	     will be with the right level of protection. Thus the right
1570  *	     value will be communicated even if we are not able to
1571  *	     communicate when we get from the wire initially. But this
1572  *	     assumes there would be at least one outbound datagram after
1573  *	     IP has adjusted its ire_max_frag value. To make things
1574  *	     simpler, we accept in clear after the validation of
1575  *	     AH/ESP headers.
1576  *
1577  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1578  *	     upper layer depending on the level of protection the upper
1579  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1580  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1581  *	     should be accepted in clear when the Upper layer expects secure.
1582  *	     Thus the communication may get aborted by some bad ICMP
1583  *	     packets.
1584  *
1585  * IPQoS Notes:
1586  * The only instance when a packet is sent for processing is when there
1587  * isn't an ICMP client and if we are interested in it.
1588  * If there is a client, IPPF processing will take place in the
1589  * ip_fanout_proto routine.
1590  *
1591  * Zones notes:
1592  * The packet is only processed in the context of the specified zone: typically
1593  * only this zone will reply to an echo request, and only interested clients in
1594  * this zone will receive a copy of the packet. This means that the caller must
1595  * call icmp_inbound() for each relevant zone.
1596  */
1597 static void
1598 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1599     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1600     ill_t *recv_ill, zoneid_t zoneid)
1601 {
1602 	icmph_t	*icmph;
1603 	ipha_t	*ipha;
1604 	int	iph_hdr_length;
1605 	int	hdr_length;
1606 	boolean_t	interested;
1607 	uint32_t	ts;
1608 	uchar_t	*wptr;
1609 	ipif_t	*ipif;
1610 	mblk_t *first_mp;
1611 	ipsec_in_t *ii;
1612 	ire_t *src_ire;
1613 	boolean_t onlink;
1614 	timestruc_t now;
1615 	uint32_t ill_index;
1616 	ip_stack_t *ipst;
1617 
1618 	ASSERT(ill != NULL);
1619 	ipst = ill->ill_ipst;
1620 
1621 	first_mp = mp;
1622 	if (mctl_present) {
1623 		mp = first_mp->b_cont;
1624 		ASSERT(mp != NULL);
1625 	}
1626 
1627 	ipha = (ipha_t *)mp->b_rptr;
1628 	if (ipst->ips_icmp_accept_clear_messages == 0) {
1629 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1630 		    ipha, NULL, mctl_present, ipst->ips_netstack);
1631 		if (first_mp == NULL)
1632 			return;
1633 	}
1634 
1635 	/*
1636 	 * On a labeled system, we have to check whether the zone itself is
1637 	 * permitted to receive raw traffic.
1638 	 */
1639 	if (is_system_labeled()) {
1640 		if (zoneid == ALL_ZONES)
1641 			zoneid = tsol_packet_to_zoneid(mp);
1642 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1643 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1644 			    zoneid));
1645 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1646 			freemsg(first_mp);
1647 			return;
1648 		}
1649 	}
1650 
1651 	/*
1652 	 * We have accepted the ICMP message. It means that we will
1653 	 * respond to the packet if needed. It may not be delivered
1654 	 * to the upper client depending on the policy constraints
1655 	 * and the disposition in ipsec_inbound_accept_clear.
1656 	 */
1657 
1658 	ASSERT(ill != NULL);
1659 
1660 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1661 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1662 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1663 		/* Last chance to get real. */
1664 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1665 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1666 			freemsg(first_mp);
1667 			return;
1668 		}
1669 		/* Refresh iph following the pullup. */
1670 		ipha = (ipha_t *)mp->b_rptr;
1671 	}
1672 	/* ICMP header checksum, including checksum field, should be zero. */
1673 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1674 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1675 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInCksumErrs);
1676 		freemsg(first_mp);
1677 		return;
1678 	}
1679 	/* The IP header will always be a multiple of four bytes */
1680 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1681 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1682 	    icmph->icmph_code));
1683 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1684 	/* We will set "interested" to "true" if we want a copy */
1685 	interested = B_FALSE;
1686 	switch (icmph->icmph_type) {
1687 	case ICMP_ECHO_REPLY:
1688 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1689 		break;
1690 	case ICMP_DEST_UNREACHABLE:
1691 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1692 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1693 		interested = B_TRUE;	/* Pass up to transport */
1694 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1695 		break;
1696 	case ICMP_SOURCE_QUENCH:
1697 		interested = B_TRUE;	/* Pass up to transport */
1698 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1699 		break;
1700 	case ICMP_REDIRECT:
1701 		if (!ipst->ips_ip_ignore_redirect)
1702 			interested = B_TRUE;
1703 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1704 		break;
1705 	case ICMP_ECHO_REQUEST:
1706 		/*
1707 		 * Whether to respond to echo requests that come in as IP
1708 		 * broadcasts or as IP multicast is subject to debate
1709 		 * (what isn't?).  We aim to please, you pick it.
1710 		 * Default is do it.
1711 		 */
1712 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1713 			/* unicast: always respond */
1714 			interested = B_TRUE;
1715 		} else if (CLASSD(ipha->ipha_dst)) {
1716 			/* multicast: respond based on tunable */
1717 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1718 		} else if (broadcast) {
1719 			/* broadcast: respond based on tunable */
1720 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1721 		}
1722 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1723 		break;
1724 	case ICMP_ROUTER_ADVERTISEMENT:
1725 	case ICMP_ROUTER_SOLICITATION:
1726 		break;
1727 	case ICMP_TIME_EXCEEDED:
1728 		interested = B_TRUE;	/* Pass up to transport */
1729 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1730 		break;
1731 	case ICMP_PARAM_PROBLEM:
1732 		interested = B_TRUE;	/* Pass up to transport */
1733 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1734 		break;
1735 	case ICMP_TIME_STAMP_REQUEST:
1736 		/* Response to Time Stamp Requests is local policy. */
1737 		if (ipst->ips_ip_g_resp_to_timestamp &&
1738 		    /* So is whether to respond if it was an IP broadcast. */
1739 		    (!broadcast || ipst->ips_ip_g_resp_to_timestamp_bcast)) {
1740 			int tstamp_len = 3 * sizeof (uint32_t);
1741 
1742 			if (wptr +  tstamp_len > mp->b_wptr) {
1743 				if (!pullupmsg(mp, wptr + tstamp_len -
1744 				    mp->b_rptr)) {
1745 					BUMP_MIB(ill->ill_ip_mib,
1746 					    ipIfStatsInDiscards);
1747 					freemsg(first_mp);
1748 					return;
1749 				}
1750 				/* Refresh ipha following the pullup. */
1751 				ipha = (ipha_t *)mp->b_rptr;
1752 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1753 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1754 			}
1755 			interested = B_TRUE;
1756 		}
1757 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1758 		break;
1759 	case ICMP_TIME_STAMP_REPLY:
1760 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1761 		break;
1762 	case ICMP_INFO_REQUEST:
1763 		/* Per RFC 1122 3.2.2.7, ignore this. */
1764 	case ICMP_INFO_REPLY:
1765 		break;
1766 	case ICMP_ADDRESS_MASK_REQUEST:
1767 		if ((ipst->ips_ip_respond_to_address_mask_broadcast ||
1768 		    !broadcast) &&
1769 		    /* TODO m_pullup of complete header? */
1770 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN) {
1771 			interested = B_TRUE;
1772 		}
1773 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1774 		break;
1775 	case ICMP_ADDRESS_MASK_REPLY:
1776 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1777 		break;
1778 	default:
1779 		interested = B_TRUE;	/* Pass up to transport */
1780 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1781 		break;
1782 	}
1783 	/* See if there is an ICMP client. */
1784 	if (ipst->ips_ipcl_proto_fanout[IPPROTO_ICMP].connf_head != NULL) {
1785 		/* If there is an ICMP client and we want one too, copy it. */
1786 		mblk_t *first_mp1;
1787 
1788 		if (!interested) {
1789 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1790 			    ip_policy, recv_ill, zoneid);
1791 			return;
1792 		}
1793 		first_mp1 = ip_copymsg(first_mp);
1794 		if (first_mp1 != NULL) {
1795 			ip_fanout_proto(q, first_mp1, ill, ipha,
1796 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1797 		}
1798 	} else if (!interested) {
1799 		freemsg(first_mp);
1800 		return;
1801 	} else {
1802 		/*
1803 		 * Initiate policy processing for this packet if ip_policy
1804 		 * is true.
1805 		 */
1806 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
1807 			ill_index = ill->ill_phyint->phyint_ifindex;
1808 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1809 			if (mp == NULL) {
1810 				if (mctl_present) {
1811 					freeb(first_mp);
1812 				}
1813 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1814 				return;
1815 			}
1816 		}
1817 	}
1818 	/* We want to do something with it. */
1819 	/* Check db_ref to make sure we can modify the packet. */
1820 	if (mp->b_datap->db_ref > 1) {
1821 		mblk_t	*first_mp1;
1822 
1823 		first_mp1 = ip_copymsg(first_mp);
1824 		freemsg(first_mp);
1825 		if (!first_mp1) {
1826 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1827 			return;
1828 		}
1829 		first_mp = first_mp1;
1830 		if (mctl_present) {
1831 			mp = first_mp->b_cont;
1832 			ASSERT(mp != NULL);
1833 		} else {
1834 			mp = first_mp;
1835 		}
1836 		ipha = (ipha_t *)mp->b_rptr;
1837 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1838 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1839 	}
1840 	switch (icmph->icmph_type) {
1841 	case ICMP_ADDRESS_MASK_REQUEST:
1842 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1843 		if (ipif == NULL) {
1844 			freemsg(first_mp);
1845 			return;
1846 		}
1847 		/*
1848 		 * outging interface must be IPv4
1849 		 */
1850 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1851 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1852 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1853 		ipif_refrele(ipif);
1854 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1855 		break;
1856 	case ICMP_ECHO_REQUEST:
1857 		icmph->icmph_type = ICMP_ECHO_REPLY;
1858 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1859 		break;
1860 	case ICMP_TIME_STAMP_REQUEST: {
1861 		uint32_t *tsp;
1862 
1863 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1864 		tsp = (uint32_t *)wptr;
1865 		tsp++;		/* Skip past 'originate time' */
1866 		/* Compute # of milliseconds since midnight */
1867 		gethrestime(&now);
1868 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1869 		    now.tv_nsec / (NANOSEC / MILLISEC);
1870 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1871 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1872 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1873 		break;
1874 	}
1875 	default:
1876 		ipha = (ipha_t *)&icmph[1];
1877 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1878 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1879 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1880 				freemsg(first_mp);
1881 				return;
1882 			}
1883 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1884 			ipha = (ipha_t *)&icmph[1];
1885 		}
1886 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1887 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1888 			freemsg(first_mp);
1889 			return;
1890 		}
1891 		hdr_length = IPH_HDR_LENGTH(ipha);
1892 		if (hdr_length < sizeof (ipha_t)) {
1893 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1894 			freemsg(first_mp);
1895 			return;
1896 		}
1897 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1898 			if (!pullupmsg(mp,
1899 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1900 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1901 				freemsg(first_mp);
1902 				return;
1903 			}
1904 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1905 			ipha = (ipha_t *)&icmph[1];
1906 		}
1907 		switch (icmph->icmph_type) {
1908 		case ICMP_REDIRECT:
1909 			/*
1910 			 * As there is no upper client to deliver, we don't
1911 			 * need the first_mp any more.
1912 			 */
1913 			if (mctl_present) {
1914 				freeb(first_mp);
1915 			}
1916 			icmp_redirect(ill, mp);
1917 			return;
1918 		case ICMP_DEST_UNREACHABLE:
1919 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1920 				if (!icmp_inbound_too_big(icmph, ipha, ill,
1921 				    zoneid, mp, iph_hdr_length, ipst)) {
1922 					freemsg(first_mp);
1923 					return;
1924 				}
1925 				/*
1926 				 * icmp_inbound_too_big() may alter mp.
1927 				 * Resynch ipha and icmph accordingly.
1928 				 */
1929 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1930 				ipha = (ipha_t *)&icmph[1];
1931 			}
1932 			/* FALLTHRU */
1933 		default :
1934 			/*
1935 			 * IPQoS notes: Since we have already done IPQoS
1936 			 * processing we don't want to do it again in
1937 			 * the fanout routines called by
1938 			 * icmp_inbound_error_fanout, hence the last
1939 			 * argument, ip_policy, is B_FALSE.
1940 			 */
1941 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
1942 			    ipha, iph_hdr_length, hdr_length, mctl_present,
1943 			    B_FALSE, recv_ill, zoneid);
1944 		}
1945 		return;
1946 	}
1947 	/* Send out an ICMP packet */
1948 	icmph->icmph_checksum = 0;
1949 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
1950 	if (broadcast || CLASSD(ipha->ipha_dst)) {
1951 		ipif_t	*ipif_chosen;
1952 		/*
1953 		 * Make it look like it was directed to us, so we don't look
1954 		 * like a fool with a broadcast or multicast source address.
1955 		 */
1956 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1957 		/*
1958 		 * Make sure that we haven't grabbed an interface that's DOWN.
1959 		 */
1960 		if (ipif != NULL) {
1961 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
1962 			    ipha->ipha_src, zoneid);
1963 			if (ipif_chosen != NULL) {
1964 				ipif_refrele(ipif);
1965 				ipif = ipif_chosen;
1966 			}
1967 		}
1968 		if (ipif == NULL) {
1969 			ip0dbg(("icmp_inbound: "
1970 			    "No source for broadcast/multicast:\n"
1971 			    "\tsrc 0x%x dst 0x%x ill %p "
1972 			    "ipif_lcl_addr 0x%x\n",
1973 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
1974 			    (void *)ill,
1975 			    ill->ill_ipif->ipif_lcl_addr));
1976 			freemsg(first_mp);
1977 			return;
1978 		}
1979 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1980 		ipha->ipha_dst = ipif->ipif_src_addr;
1981 		ipif_refrele(ipif);
1982 	}
1983 	/* Reset time to live. */
1984 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
1985 	{
1986 		/* Swap source and destination addresses */
1987 		ipaddr_t tmp;
1988 
1989 		tmp = ipha->ipha_src;
1990 		ipha->ipha_src = ipha->ipha_dst;
1991 		ipha->ipha_dst = tmp;
1992 	}
1993 	ipha->ipha_ident = 0;
1994 	if (!IS_SIMPLE_IPH(ipha))
1995 		icmp_options_update(ipha);
1996 
1997 	/*
1998 	 * ICMP echo replies should go out on the same interface
1999 	 * the request came on as probes used by in.mpathd for detecting
2000 	 * NIC failures are ECHO packets. We turn-off load spreading
2001 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
2002 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
2003 	 * function. This is in turn handled by ip_wput and ip_newroute
2004 	 * to make sure that the packet goes out on the interface it came
2005 	 * in on. If we don't turnoff load spreading, the packets might get
2006 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
2007 	 * to go out and in.mpathd would wrongly detect a failure or
2008 	 * mis-detect a NIC failure for link failure. As load spreading
2009 	 * can happen only if ill_group is not NULL, we do only for
2010 	 * that case and this does not affect the normal case.
2011 	 *
2012 	 * We turn off load spreading only on echo packets that came from
2013 	 * on-link hosts. If the interface route has been deleted, this will
2014 	 * not be enforced as we can't do much. For off-link hosts, as the
2015 	 * default routes in IPv4 does not typically have an ire_ipif
2016 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
2017 	 * Moreover, expecting a default route through this interface may
2018 	 * not be correct. We use ipha_dst because of the swap above.
2019 	 */
2020 	onlink = B_FALSE;
2021 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
2022 		/*
2023 		 * First, we need to make sure that it is not one of our
2024 		 * local addresses. If we set onlink when it is one of
2025 		 * our local addresses, we will end up creating IRE_CACHES
2026 		 * for one of our local addresses. Then, we will never
2027 		 * accept packets for them afterwards.
2028 		 */
2029 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2030 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2031 		if (src_ire == NULL) {
2032 			ipif = ipif_get_next_ipif(NULL, ill);
2033 			if (ipif == NULL) {
2034 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2035 				freemsg(mp);
2036 				return;
2037 			}
2038 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2039 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2040 			    NULL, MATCH_IRE_ILL | MATCH_IRE_TYPE, ipst);
2041 			ipif_refrele(ipif);
2042 			if (src_ire != NULL) {
2043 				onlink = B_TRUE;
2044 				ire_refrele(src_ire);
2045 			}
2046 		} else {
2047 			ire_refrele(src_ire);
2048 		}
2049 	}
2050 	if (!mctl_present) {
2051 		/*
2052 		 * This packet should go out the same way as it
2053 		 * came in i.e in clear. To make sure that global
2054 		 * policy will not be applied to this in ip_wput_ire,
2055 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2056 		 */
2057 		ASSERT(first_mp == mp);
2058 		first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2059 		if (first_mp == NULL) {
2060 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2061 			freemsg(mp);
2062 			return;
2063 		}
2064 		ii = (ipsec_in_t *)first_mp->b_rptr;
2065 
2066 		/* This is not a secure packet */
2067 		ii->ipsec_in_secure = B_FALSE;
2068 		if (onlink) {
2069 			ii->ipsec_in_attach_if = B_TRUE;
2070 			ii->ipsec_in_ill_index =
2071 			    ill->ill_phyint->phyint_ifindex;
2072 			ii->ipsec_in_rill_index =
2073 			    recv_ill->ill_phyint->phyint_ifindex;
2074 		}
2075 		first_mp->b_cont = mp;
2076 	} else if (onlink) {
2077 		ii = (ipsec_in_t *)first_mp->b_rptr;
2078 		ii->ipsec_in_attach_if = B_TRUE;
2079 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2080 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2081 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2082 	} else {
2083 		ii = (ipsec_in_t *)first_mp->b_rptr;
2084 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2085 	}
2086 	ii->ipsec_in_zoneid = zoneid;
2087 	ASSERT(zoneid != ALL_ZONES);
2088 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2089 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2090 		return;
2091 	}
2092 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2093 	put(WR(q), first_mp);
2094 }
2095 
2096 static ipaddr_t
2097 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2098 {
2099 	conn_t *connp;
2100 	connf_t *connfp;
2101 	ipaddr_t nexthop_addr = INADDR_ANY;
2102 	int hdr_length = IPH_HDR_LENGTH(ipha);
2103 	uint16_t *up;
2104 	uint32_t ports;
2105 	ip_stack_t *ipst = ill->ill_ipst;
2106 
2107 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2108 	switch (ipha->ipha_protocol) {
2109 		case IPPROTO_TCP:
2110 		{
2111 			tcph_t *tcph;
2112 
2113 			/* do a reverse lookup */
2114 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2115 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2116 			    TCPS_LISTEN, ipst);
2117 			break;
2118 		}
2119 		case IPPROTO_UDP:
2120 		{
2121 			uint32_t dstport, srcport;
2122 
2123 			((uint16_t *)&ports)[0] = up[1];
2124 			((uint16_t *)&ports)[1] = up[0];
2125 
2126 			/* Extract ports in net byte order */
2127 			dstport = htons(ntohl(ports) & 0xFFFF);
2128 			srcport = htons(ntohl(ports) >> 16);
2129 
2130 			connfp = &ipst->ips_ipcl_udp_fanout[
2131 			    IPCL_UDP_HASH(dstport, ipst)];
2132 			mutex_enter(&connfp->connf_lock);
2133 			connp = connfp->connf_head;
2134 
2135 			/* do a reverse lookup */
2136 			while ((connp != NULL) &&
2137 			    (!IPCL_UDP_MATCH(connp, dstport,
2138 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2139 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2140 				connp = connp->conn_next;
2141 			}
2142 			if (connp != NULL)
2143 				CONN_INC_REF(connp);
2144 			mutex_exit(&connfp->connf_lock);
2145 			break;
2146 		}
2147 		case IPPROTO_SCTP:
2148 		{
2149 			in6_addr_t map_src, map_dst;
2150 
2151 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2152 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2153 			((uint16_t *)&ports)[0] = up[1];
2154 			((uint16_t *)&ports)[1] = up[0];
2155 
2156 			connp = sctp_find_conn(&map_src, &map_dst, ports,
2157 			    zoneid, ipst->ips_netstack->netstack_sctp);
2158 			if (connp == NULL) {
2159 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2160 				    zoneid, ports, ipha, ipst);
2161 			} else {
2162 				CONN_INC_REF(connp);
2163 				SCTP_REFRELE(CONN2SCTP(connp));
2164 			}
2165 			break;
2166 		}
2167 		default:
2168 		{
2169 			ipha_t ripha;
2170 
2171 			ripha.ipha_src = ipha->ipha_dst;
2172 			ripha.ipha_dst = ipha->ipha_src;
2173 			ripha.ipha_protocol = ipha->ipha_protocol;
2174 
2175 			connfp = &ipst->ips_ipcl_proto_fanout[
2176 			    ipha->ipha_protocol];
2177 			mutex_enter(&connfp->connf_lock);
2178 			connp = connfp->connf_head;
2179 			for (connp = connfp->connf_head; connp != NULL;
2180 			    connp = connp->conn_next) {
2181 				if (IPCL_PROTO_MATCH(connp,
2182 				    ipha->ipha_protocol, &ripha, ill,
2183 				    0, zoneid)) {
2184 					CONN_INC_REF(connp);
2185 					break;
2186 				}
2187 			}
2188 			mutex_exit(&connfp->connf_lock);
2189 		}
2190 	}
2191 	if (connp != NULL) {
2192 		if (connp->conn_nexthop_set)
2193 			nexthop_addr = connp->conn_nexthop_v4;
2194 		CONN_DEC_REF(connp);
2195 	}
2196 	return (nexthop_addr);
2197 }
2198 
2199 /* Table from RFC 1191 */
2200 static int icmp_frag_size_table[] =
2201 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2202 
2203 /*
2204  * Process received ICMP Packet too big.
2205  * After updating any IRE it does the fanout to any matching transport streams.
2206  * Assumes the message has been pulled up till the IP header that caused
2207  * the error.
2208  *
2209  * Returns B_FALSE on failure and B_TRUE on success.
2210  */
2211 static boolean_t
2212 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2213     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length,
2214     ip_stack_t *ipst)
2215 {
2216 	ire_t	*ire, *first_ire;
2217 	int	mtu;
2218 	int	hdr_length;
2219 	ipaddr_t nexthop_addr;
2220 
2221 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2222 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2223 	ASSERT(ill != NULL);
2224 
2225 	hdr_length = IPH_HDR_LENGTH(ipha);
2226 
2227 	/* Drop if the original packet contained a source route */
2228 	if (ip_source_route_included(ipha)) {
2229 		return (B_FALSE);
2230 	}
2231 	/*
2232 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2233 	 * header.
2234 	 */
2235 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2236 	    mp->b_wptr) {
2237 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2238 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2239 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2240 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2241 			return (B_FALSE);
2242 		}
2243 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2244 		ipha = (ipha_t *)&icmph[1];
2245 	}
2246 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2247 	if (nexthop_addr != INADDR_ANY) {
2248 		/* nexthop set */
2249 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2250 		    nexthop_addr, 0, NULL, ALL_ZONES, MBLK_GETLABEL(mp),
2251 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW, ipst);
2252 	} else {
2253 		/* nexthop not set */
2254 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2255 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2256 	}
2257 
2258 	if (!first_ire) {
2259 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2260 		    ntohl(ipha->ipha_dst)));
2261 		return (B_FALSE);
2262 	}
2263 	/* Check for MTU discovery advice as described in RFC 1191 */
2264 	mtu = ntohs(icmph->icmph_du_mtu);
2265 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2266 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2267 	    ire = ire->ire_next) {
2268 		/*
2269 		 * Look for the connection to which this ICMP message is
2270 		 * directed. If it has the IP_NEXTHOP option set, then the
2271 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2272 		 * option. Else the search is limited to regular IREs.
2273 		 */
2274 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2275 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2276 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2277 		    (nexthop_addr != INADDR_ANY)))
2278 			continue;
2279 
2280 		mutex_enter(&ire->ire_lock);
2281 		if (icmph->icmph_du_zero == 0 && mtu > 68) {
2282 			/* Reduce the IRE max frag value as advised. */
2283 			ip1dbg(("Received mtu from router: %d (was %d)\n",
2284 			    mtu, ire->ire_max_frag));
2285 			ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2286 		} else {
2287 			uint32_t length;
2288 			int	i;
2289 
2290 			/*
2291 			 * Use the table from RFC 1191 to figure out
2292 			 * the next "plateau" based on the length in
2293 			 * the original IP packet.
2294 			 */
2295 			length = ntohs(ipha->ipha_length);
2296 			if (ire->ire_max_frag <= length &&
2297 			    ire->ire_max_frag >= length - hdr_length) {
2298 				/*
2299 				 * Handle broken BSD 4.2 systems that
2300 				 * return the wrong iph_length in ICMP
2301 				 * errors.
2302 				 */
2303 				ip1dbg(("Wrong mtu: sent %d, ire %d\n",
2304 				    length, ire->ire_max_frag));
2305 				length -= hdr_length;
2306 			}
2307 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2308 				if (length > icmp_frag_size_table[i])
2309 					break;
2310 			}
2311 			if (i == A_CNT(icmp_frag_size_table)) {
2312 				/* Smaller than 68! */
2313 				ip1dbg(("Too big for packet size %d\n",
2314 				    length));
2315 				ire->ire_max_frag = MIN(ire->ire_max_frag, 576);
2316 				ire->ire_frag_flag = 0;
2317 			} else {
2318 				mtu = icmp_frag_size_table[i];
2319 				ip1dbg(("Calculated mtu %d, packet size %d, "
2320 				    "before %d", mtu, length,
2321 				    ire->ire_max_frag));
2322 				ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2323 				ip1dbg((", after %d\n", ire->ire_max_frag));
2324 			}
2325 			/* Record the new max frag size for the ULP. */
2326 			icmph->icmph_du_zero = 0;
2327 			icmph->icmph_du_mtu =
2328 			    htons((uint16_t)ire->ire_max_frag);
2329 		}
2330 		mutex_exit(&ire->ire_lock);
2331 	}
2332 	rw_exit(&first_ire->ire_bucket->irb_lock);
2333 	ire_refrele(first_ire);
2334 	return (B_TRUE);
2335 }
2336 
2337 /*
2338  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2339  * calls this function.
2340  */
2341 static mblk_t *
2342 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2343 {
2344 	ipha_t *ipha;
2345 	icmph_t *icmph;
2346 	ipha_t *in_ipha;
2347 	int length;
2348 
2349 	ASSERT(mp->b_datap->db_type == M_DATA);
2350 
2351 	/*
2352 	 * For Self-encapsulated packets, we added an extra IP header
2353 	 * without the options. Inner IP header is the one from which
2354 	 * the outer IP header was formed. Thus, we need to remove the
2355 	 * outer IP header. To do this, we pullup the whole message
2356 	 * and overlay whatever follows the outer IP header over the
2357 	 * outer IP header.
2358 	 */
2359 
2360 	if (!pullupmsg(mp, -1))
2361 		return (NULL);
2362 
2363 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2364 	ipha = (ipha_t *)&icmph[1];
2365 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2366 
2367 	/*
2368 	 * The length that we want to overlay is following the inner
2369 	 * IP header. Subtracting the IP header + icmp header + outer
2370 	 * IP header's length should give us the length that we want to
2371 	 * overlay.
2372 	 */
2373 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2374 	    hdr_length;
2375 	/*
2376 	 * Overlay whatever follows the inner header over the
2377 	 * outer header.
2378 	 */
2379 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2380 
2381 	/* Set the wptr to account for the outer header */
2382 	mp->b_wptr -= hdr_length;
2383 	return (mp);
2384 }
2385 
2386 /*
2387  * Try to pass the ICMP message upstream in case the ULP cares.
2388  *
2389  * If the packet that caused the ICMP error is secure, we send
2390  * it to AH/ESP to make sure that the attached packet has a
2391  * valid association. ipha in the code below points to the
2392  * IP header of the packet that caused the error.
2393  *
2394  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2395  * in the context of IPsec. Normally we tell the upper layer
2396  * whenever we send the ire (including ip_bind), the IPsec header
2397  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2398  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2399  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2400  * same thing. As TCP has the IPsec options size that needs to be
2401  * adjusted, we just pass the MTU unchanged.
2402  *
2403  * IFN could have been generated locally or by some router.
2404  *
2405  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2406  *	    This happens because IP adjusted its value of MTU on an
2407  *	    earlier IFN message and could not tell the upper layer,
2408  *	    the new adjusted value of MTU e.g. Packet was encrypted
2409  *	    or there was not enough information to fanout to upper
2410  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2411  *	    generates the IFN, where IPsec processing has *not* been
2412  *	    done.
2413  *
2414  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2415  *	    could have generated this. This happens because ire_max_frag
2416  *	    value in IP was set to a new value, while the IPsec processing
2417  *	    was being done and after we made the fragmentation check in
2418  *	    ip_wput_ire. Thus on return from IPsec processing,
2419  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2420  *	    and generates the IFN. As IPsec processing is over, we fanout
2421  *	    to AH/ESP to remove the header.
2422  *
2423  *	    In both these cases, ipsec_in_loopback will be set indicating
2424  *	    that IFN was generated locally.
2425  *
2426  * ROUTER : IFN could be secure or non-secure.
2427  *
2428  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2429  *	      packet in error has AH/ESP headers to validate the AH/ESP
2430  *	      headers. AH/ESP will verify whether there is a valid SA or
2431  *	      not and send it back. We will fanout again if we have more
2432  *	      data in the packet.
2433  *
2434  *	      If the packet in error does not have AH/ESP, we handle it
2435  *	      like any other case.
2436  *
2437  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2438  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2439  *	      for validation. AH/ESP will verify whether there is a
2440  *	      valid SA or not and send it back. We will fanout again if
2441  *	      we have more data in the packet.
2442  *
2443  *	      If the packet in error does not have AH/ESP, we handle it
2444  *	      like any other case.
2445  */
2446 static void
2447 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2448     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2449     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2450     zoneid_t zoneid)
2451 {
2452 	uint16_t *up;	/* Pointer to ports in ULP header */
2453 	uint32_t ports;	/* reversed ports for fanout */
2454 	ipha_t ripha;	/* With reversed addresses */
2455 	mblk_t *first_mp;
2456 	ipsec_in_t *ii;
2457 	tcph_t	*tcph;
2458 	conn_t	*connp;
2459 	ip_stack_t *ipst;
2460 
2461 	ASSERT(ill != NULL);
2462 
2463 	ASSERT(recv_ill != NULL);
2464 	ipst = recv_ill->ill_ipst;
2465 
2466 	first_mp = mp;
2467 	if (mctl_present) {
2468 		mp = first_mp->b_cont;
2469 		ASSERT(mp != NULL);
2470 
2471 		ii = (ipsec_in_t *)first_mp->b_rptr;
2472 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2473 	} else {
2474 		ii = NULL;
2475 	}
2476 
2477 	switch (ipha->ipha_protocol) {
2478 	case IPPROTO_UDP:
2479 		/*
2480 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2481 		 * transport header.
2482 		 */
2483 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2484 		    mp->b_wptr) {
2485 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2486 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2487 				goto discard_pkt;
2488 			}
2489 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2490 			ipha = (ipha_t *)&icmph[1];
2491 		}
2492 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2493 
2494 		/*
2495 		 * Attempt to find a client stream based on port.
2496 		 * Note that we do a reverse lookup since the header is
2497 		 * in the form we sent it out.
2498 		 * The ripha header is only used for the IP_UDP_MATCH and we
2499 		 * only set the src and dst addresses and protocol.
2500 		 */
2501 		ripha.ipha_src = ipha->ipha_dst;
2502 		ripha.ipha_dst = ipha->ipha_src;
2503 		ripha.ipha_protocol = ipha->ipha_protocol;
2504 		((uint16_t *)&ports)[0] = up[1];
2505 		((uint16_t *)&ports)[1] = up[0];
2506 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2507 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2508 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2509 		    icmph->icmph_type, icmph->icmph_code));
2510 
2511 		/* Have to change db_type after any pullupmsg */
2512 		DB_TYPE(mp) = M_CTL;
2513 
2514 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2515 		    mctl_present, ip_policy, recv_ill, zoneid);
2516 		return;
2517 
2518 	case IPPROTO_TCP:
2519 		/*
2520 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2521 		 * transport header.
2522 		 */
2523 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2524 		    mp->b_wptr) {
2525 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2526 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2527 				goto discard_pkt;
2528 			}
2529 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2530 			ipha = (ipha_t *)&icmph[1];
2531 		}
2532 		/*
2533 		 * Find a TCP client stream for this packet.
2534 		 * Note that we do a reverse lookup since the header is
2535 		 * in the form we sent it out.
2536 		 */
2537 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2538 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN,
2539 		    ipst);
2540 		if (connp == NULL)
2541 			goto discard_pkt;
2542 
2543 		/* Have to change db_type after any pullupmsg */
2544 		DB_TYPE(mp) = M_CTL;
2545 		squeue_fill(connp->conn_sqp, first_mp, tcp_input,
2546 		    connp, SQTAG_TCP_INPUT_ICMP_ERR);
2547 		return;
2548 
2549 	case IPPROTO_SCTP:
2550 		/*
2551 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2552 		 * transport header.
2553 		 */
2554 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2555 		    mp->b_wptr) {
2556 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2557 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2558 				goto discard_pkt;
2559 			}
2560 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2561 			ipha = (ipha_t *)&icmph[1];
2562 		}
2563 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2564 		/*
2565 		 * Find a SCTP client stream for this packet.
2566 		 * Note that we do a reverse lookup since the header is
2567 		 * in the form we sent it out.
2568 		 * The ripha header is only used for the matching and we
2569 		 * only set the src and dst addresses, protocol, and version.
2570 		 */
2571 		ripha.ipha_src = ipha->ipha_dst;
2572 		ripha.ipha_dst = ipha->ipha_src;
2573 		ripha.ipha_protocol = ipha->ipha_protocol;
2574 		ripha.ipha_version_and_hdr_length =
2575 		    ipha->ipha_version_and_hdr_length;
2576 		((uint16_t *)&ports)[0] = up[1];
2577 		((uint16_t *)&ports)[1] = up[0];
2578 
2579 		/* Have to change db_type after any pullupmsg */
2580 		DB_TYPE(mp) = M_CTL;
2581 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2582 		    mctl_present, ip_policy, zoneid);
2583 		return;
2584 
2585 	case IPPROTO_ESP:
2586 	case IPPROTO_AH: {
2587 		int ipsec_rc;
2588 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
2589 
2590 		/*
2591 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2592 		 * We will re-use the IPSEC_IN if it is already present as
2593 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2594 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2595 		 * one and attach it in the front.
2596 		 */
2597 		if (ii != NULL) {
2598 			/*
2599 			 * ip_fanout_proto_again converts the ICMP errors
2600 			 * that come back from AH/ESP to M_DATA so that
2601 			 * if it is non-AH/ESP and we do a pullupmsg in
2602 			 * this function, it would work. Convert it back
2603 			 * to M_CTL before we send up as this is a ICMP
2604 			 * error. This could have been generated locally or
2605 			 * by some router. Validate the inner IPsec
2606 			 * headers.
2607 			 *
2608 			 * NOTE : ill_index is used by ip_fanout_proto_again
2609 			 * to locate the ill.
2610 			 */
2611 			ASSERT(ill != NULL);
2612 			ii->ipsec_in_ill_index =
2613 			    ill->ill_phyint->phyint_ifindex;
2614 			ii->ipsec_in_rill_index =
2615 			    recv_ill->ill_phyint->phyint_ifindex;
2616 			DB_TYPE(first_mp->b_cont) = M_CTL;
2617 		} else {
2618 			/*
2619 			 * IPSEC_IN is not present. We attach a ipsec_in
2620 			 * message and send up to IPsec for validating
2621 			 * and removing the IPsec headers. Clear
2622 			 * ipsec_in_secure so that when we return
2623 			 * from IPsec, we don't mistakenly think that this
2624 			 * is a secure packet came from the network.
2625 			 *
2626 			 * NOTE : ill_index is used by ip_fanout_proto_again
2627 			 * to locate the ill.
2628 			 */
2629 			ASSERT(first_mp == mp);
2630 			first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2631 			if (first_mp == NULL) {
2632 				freemsg(mp);
2633 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2634 				return;
2635 			}
2636 			ii = (ipsec_in_t *)first_mp->b_rptr;
2637 
2638 			/* This is not a secure packet */
2639 			ii->ipsec_in_secure = B_FALSE;
2640 			first_mp->b_cont = mp;
2641 			DB_TYPE(mp) = M_CTL;
2642 			ASSERT(ill != NULL);
2643 			ii->ipsec_in_ill_index =
2644 			    ill->ill_phyint->phyint_ifindex;
2645 			ii->ipsec_in_rill_index =
2646 			    recv_ill->ill_phyint->phyint_ifindex;
2647 		}
2648 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2649 
2650 		if (!ipsec_loaded(ipss)) {
2651 			ip_proto_not_sup(q, first_mp, 0, zoneid, ipst);
2652 			return;
2653 		}
2654 
2655 		if (ipha->ipha_protocol == IPPROTO_ESP)
2656 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2657 		else
2658 			ipsec_rc = ipsecah_icmp_error(first_mp);
2659 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2660 			return;
2661 
2662 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2663 		return;
2664 	}
2665 	default:
2666 		/*
2667 		 * The ripha header is only used for the lookup and we
2668 		 * only set the src and dst addresses and protocol.
2669 		 */
2670 		ripha.ipha_src = ipha->ipha_dst;
2671 		ripha.ipha_dst = ipha->ipha_src;
2672 		ripha.ipha_protocol = ipha->ipha_protocol;
2673 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2674 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2675 		    ntohl(ipha->ipha_dst),
2676 		    icmph->icmph_type, icmph->icmph_code));
2677 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2678 			ipha_t *in_ipha;
2679 
2680 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2681 			    mp->b_wptr) {
2682 				if (!pullupmsg(mp, (uchar_t *)ipha +
2683 				    hdr_length + sizeof (ipha_t) -
2684 				    mp->b_rptr)) {
2685 					goto discard_pkt;
2686 				}
2687 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2688 				ipha = (ipha_t *)&icmph[1];
2689 			}
2690 			/*
2691 			 * Caller has verified that length has to be
2692 			 * at least the size of IP header.
2693 			 */
2694 			ASSERT(hdr_length >= sizeof (ipha_t));
2695 			/*
2696 			 * Check the sanity of the inner IP header like
2697 			 * we did for the outer header.
2698 			 */
2699 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2700 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2701 				goto discard_pkt;
2702 			}
2703 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2704 				goto discard_pkt;
2705 			}
2706 			/* Check for Self-encapsulated tunnels */
2707 			if (in_ipha->ipha_src == ipha->ipha_src &&
2708 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2709 
2710 				mp = icmp_inbound_self_encap_error(mp,
2711 				    iph_hdr_length, hdr_length);
2712 				if (mp == NULL)
2713 					goto discard_pkt;
2714 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2715 				ipha = (ipha_t *)&icmph[1];
2716 				hdr_length = IPH_HDR_LENGTH(ipha);
2717 				/*
2718 				 * The packet in error is self-encapsualted.
2719 				 * And we are finding it further encapsulated
2720 				 * which we could not have possibly generated.
2721 				 */
2722 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2723 					goto discard_pkt;
2724 				}
2725 				icmp_inbound_error_fanout(q, ill, first_mp,
2726 				    icmph, ipha, iph_hdr_length, hdr_length,
2727 				    mctl_present, ip_policy, recv_ill, zoneid);
2728 				return;
2729 			}
2730 		}
2731 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2732 		    ipha->ipha_protocol == IPPROTO_IPV6) &&
2733 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2734 		    ii != NULL &&
2735 		    ii->ipsec_in_loopback &&
2736 		    ii->ipsec_in_secure) {
2737 			/*
2738 			 * For IP tunnels that get a looped-back
2739 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2740 			 * reported new MTU to take into account the IPsec
2741 			 * headers protecting this configured tunnel.
2742 			 *
2743 			 * This allows the tunnel module (tun.c) to blindly
2744 			 * accept the MTU reported in an ICMP "too big"
2745 			 * message.
2746 			 *
2747 			 * Non-looped back ICMP messages will just be
2748 			 * handled by the security protocols (if needed),
2749 			 * and the first subsequent packet will hit this
2750 			 * path.
2751 			 */
2752 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2753 			    ipsec_in_extra_length(first_mp));
2754 		}
2755 		/* Have to change db_type after any pullupmsg */
2756 		DB_TYPE(mp) = M_CTL;
2757 
2758 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2759 		    ip_policy, recv_ill, zoneid);
2760 		return;
2761 	}
2762 	/* NOTREACHED */
2763 discard_pkt:
2764 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2765 drop_pkt:;
2766 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2767 	freemsg(first_mp);
2768 }
2769 
2770 /*
2771  * Common IP options parser.
2772  *
2773  * Setup routine: fill in *optp with options-parsing state, then
2774  * tail-call ipoptp_next to return the first option.
2775  */
2776 uint8_t
2777 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2778 {
2779 	uint32_t totallen; /* total length of all options */
2780 
2781 	totallen = ipha->ipha_version_and_hdr_length -
2782 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2783 	totallen <<= 2;
2784 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2785 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2786 	optp->ipoptp_flags = 0;
2787 	return (ipoptp_next(optp));
2788 }
2789 
2790 /*
2791  * Common IP options parser: extract next option.
2792  */
2793 uint8_t
2794 ipoptp_next(ipoptp_t *optp)
2795 {
2796 	uint8_t *end = optp->ipoptp_end;
2797 	uint8_t *cur = optp->ipoptp_next;
2798 	uint8_t opt, len, pointer;
2799 
2800 	/*
2801 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2802 	 * has been corrupted.
2803 	 */
2804 	ASSERT(cur <= end);
2805 
2806 	if (cur == end)
2807 		return (IPOPT_EOL);
2808 
2809 	opt = cur[IPOPT_OPTVAL];
2810 
2811 	/*
2812 	 * Skip any NOP options.
2813 	 */
2814 	while (opt == IPOPT_NOP) {
2815 		cur++;
2816 		if (cur == end)
2817 			return (IPOPT_EOL);
2818 		opt = cur[IPOPT_OPTVAL];
2819 	}
2820 
2821 	if (opt == IPOPT_EOL)
2822 		return (IPOPT_EOL);
2823 
2824 	/*
2825 	 * Option requiring a length.
2826 	 */
2827 	if ((cur + 1) >= end) {
2828 		optp->ipoptp_flags |= IPOPTP_ERROR;
2829 		return (IPOPT_EOL);
2830 	}
2831 	len = cur[IPOPT_OLEN];
2832 	if (len < 2) {
2833 		optp->ipoptp_flags |= IPOPTP_ERROR;
2834 		return (IPOPT_EOL);
2835 	}
2836 	optp->ipoptp_cur = cur;
2837 	optp->ipoptp_len = len;
2838 	optp->ipoptp_next = cur + len;
2839 	if (cur + len > end) {
2840 		optp->ipoptp_flags |= IPOPTP_ERROR;
2841 		return (IPOPT_EOL);
2842 	}
2843 
2844 	/*
2845 	 * For the options which require a pointer field, make sure
2846 	 * its there, and make sure it points to either something
2847 	 * inside this option, or the end of the option.
2848 	 */
2849 	switch (opt) {
2850 	case IPOPT_RR:
2851 	case IPOPT_TS:
2852 	case IPOPT_LSRR:
2853 	case IPOPT_SSRR:
2854 		if (len <= IPOPT_OFFSET) {
2855 			optp->ipoptp_flags |= IPOPTP_ERROR;
2856 			return (opt);
2857 		}
2858 		pointer = cur[IPOPT_OFFSET];
2859 		if (pointer - 1 > len) {
2860 			optp->ipoptp_flags |= IPOPTP_ERROR;
2861 			return (opt);
2862 		}
2863 		break;
2864 	}
2865 
2866 	/*
2867 	 * Sanity check the pointer field based on the type of the
2868 	 * option.
2869 	 */
2870 	switch (opt) {
2871 	case IPOPT_RR:
2872 	case IPOPT_SSRR:
2873 	case IPOPT_LSRR:
2874 		if (pointer < IPOPT_MINOFF_SR)
2875 			optp->ipoptp_flags |= IPOPTP_ERROR;
2876 		break;
2877 	case IPOPT_TS:
2878 		if (pointer < IPOPT_MINOFF_IT)
2879 			optp->ipoptp_flags |= IPOPTP_ERROR;
2880 		/*
2881 		 * Note that the Internet Timestamp option also
2882 		 * contains two four bit fields (the Overflow field,
2883 		 * and the Flag field), which follow the pointer
2884 		 * field.  We don't need to check that these fields
2885 		 * fall within the length of the option because this
2886 		 * was implicitely done above.  We've checked that the
2887 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2888 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2889 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2890 		 */
2891 		ASSERT(len > IPOPT_POS_OV_FLG);
2892 		break;
2893 	}
2894 
2895 	return (opt);
2896 }
2897 
2898 /*
2899  * Use the outgoing IP header to create an IP_OPTIONS option the way
2900  * it was passed down from the application.
2901  */
2902 int
2903 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2904 {
2905 	ipoptp_t	opts;
2906 	const uchar_t	*opt;
2907 	uint8_t		optval;
2908 	uint8_t		optlen;
2909 	uint32_t	len = 0;
2910 	uchar_t	*buf1 = buf;
2911 
2912 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2913 	len += IP_ADDR_LEN;
2914 	bzero(buf1, IP_ADDR_LEN);
2915 
2916 	/*
2917 	 * OK to cast away const here, as we don't store through the returned
2918 	 * opts.ipoptp_cur pointer.
2919 	 */
2920 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
2921 	    optval != IPOPT_EOL;
2922 	    optval = ipoptp_next(&opts)) {
2923 		int	off;
2924 
2925 		opt = opts.ipoptp_cur;
2926 		optlen = opts.ipoptp_len;
2927 		switch (optval) {
2928 		case IPOPT_SSRR:
2929 		case IPOPT_LSRR:
2930 
2931 			/*
2932 			 * Insert ipha_dst as the first entry in the source
2933 			 * route and move down the entries on step.
2934 			 * The last entry gets placed at buf1.
2935 			 */
2936 			buf[IPOPT_OPTVAL] = optval;
2937 			buf[IPOPT_OLEN] = optlen;
2938 			buf[IPOPT_OFFSET] = optlen;
2939 
2940 			off = optlen - IP_ADDR_LEN;
2941 			if (off < 0) {
2942 				/* No entries in source route */
2943 				break;
2944 			}
2945 			/* Last entry in source route */
2946 			bcopy(opt + off, buf1, IP_ADDR_LEN);
2947 			off -= IP_ADDR_LEN;
2948 
2949 			while (off > 0) {
2950 				bcopy(opt + off,
2951 				    buf + off + IP_ADDR_LEN,
2952 				    IP_ADDR_LEN);
2953 				off -= IP_ADDR_LEN;
2954 			}
2955 			/* ipha_dst into first slot */
2956 			bcopy(&ipha->ipha_dst,
2957 			    buf + off + IP_ADDR_LEN,
2958 			    IP_ADDR_LEN);
2959 			buf += optlen;
2960 			len += optlen;
2961 			break;
2962 
2963 		case IPOPT_COMSEC:
2964 		case IPOPT_SECURITY:
2965 			/* if passing up a label is not ok, then remove */
2966 			if (is_system_labeled())
2967 				break;
2968 			/* FALLTHROUGH */
2969 		default:
2970 			bcopy(opt, buf, optlen);
2971 			buf += optlen;
2972 			len += optlen;
2973 			break;
2974 		}
2975 	}
2976 done:
2977 	/* Pad the resulting options */
2978 	while (len & 0x3) {
2979 		*buf++ = IPOPT_EOL;
2980 		len++;
2981 	}
2982 	return (len);
2983 }
2984 
2985 /*
2986  * Update any record route or timestamp options to include this host.
2987  * Reverse any source route option.
2988  * This routine assumes that the options are well formed i.e. that they
2989  * have already been checked.
2990  */
2991 static void
2992 icmp_options_update(ipha_t *ipha)
2993 {
2994 	ipoptp_t	opts;
2995 	uchar_t		*opt;
2996 	uint8_t		optval;
2997 	ipaddr_t	src;		/* Our local address */
2998 	ipaddr_t	dst;
2999 
3000 	ip2dbg(("icmp_options_update\n"));
3001 	src = ipha->ipha_src;
3002 	dst = ipha->ipha_dst;
3003 
3004 	for (optval = ipoptp_first(&opts, ipha);
3005 	    optval != IPOPT_EOL;
3006 	    optval = ipoptp_next(&opts)) {
3007 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
3008 		opt = opts.ipoptp_cur;
3009 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
3010 		    optval, opts.ipoptp_len));
3011 		switch (optval) {
3012 			int off1, off2;
3013 		case IPOPT_SSRR:
3014 		case IPOPT_LSRR:
3015 			/*
3016 			 * Reverse the source route.  The first entry
3017 			 * should be the next to last one in the current
3018 			 * source route (the last entry is our address).
3019 			 * The last entry should be the final destination.
3020 			 */
3021 			off1 = IPOPT_MINOFF_SR - 1;
3022 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
3023 			if (off2 < 0) {
3024 				/* No entries in source route */
3025 				ip1dbg((
3026 				    "icmp_options_update: bad src route\n"));
3027 				break;
3028 			}
3029 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3030 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3031 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3032 			off2 -= IP_ADDR_LEN;
3033 
3034 			while (off1 < off2) {
3035 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3036 				bcopy((char *)opt + off2, (char *)opt + off1,
3037 				    IP_ADDR_LEN);
3038 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3039 				off1 += IP_ADDR_LEN;
3040 				off2 -= IP_ADDR_LEN;
3041 			}
3042 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3043 			break;
3044 		}
3045 	}
3046 }
3047 
3048 /*
3049  * Process received ICMP Redirect messages.
3050  */
3051 static void
3052 icmp_redirect(ill_t *ill, mblk_t *mp)
3053 {
3054 	ipha_t	*ipha;
3055 	int	iph_hdr_length;
3056 	icmph_t	*icmph;
3057 	ipha_t	*ipha_err;
3058 	ire_t	*ire;
3059 	ire_t	*prev_ire;
3060 	ire_t	*save_ire;
3061 	ipaddr_t  src, dst, gateway;
3062 	iulp_t	ulp_info = { 0 };
3063 	int	error;
3064 	ip_stack_t *ipst;
3065 
3066 	ASSERT(ill != NULL);
3067 	ipst = ill->ill_ipst;
3068 
3069 	ipha = (ipha_t *)mp->b_rptr;
3070 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3071 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3072 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3073 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3074 		freemsg(mp);
3075 		return;
3076 	}
3077 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3078 	ipha_err = (ipha_t *)&icmph[1];
3079 	src = ipha->ipha_src;
3080 	dst = ipha_err->ipha_dst;
3081 	gateway = icmph->icmph_rd_gateway;
3082 	/* Make sure the new gateway is reachable somehow. */
3083 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3084 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3085 	/*
3086 	 * Make sure we had a route for the dest in question and that
3087 	 * that route was pointing to the old gateway (the source of the
3088 	 * redirect packet.)
3089 	 */
3090 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3091 	    NULL, MATCH_IRE_GW, ipst);
3092 	/*
3093 	 * Check that
3094 	 *	the redirect was not from ourselves
3095 	 *	the new gateway and the old gateway are directly reachable
3096 	 */
3097 	if (!prev_ire ||
3098 	    !ire ||
3099 	    ire->ire_type == IRE_LOCAL) {
3100 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3101 		freemsg(mp);
3102 		if (ire != NULL)
3103 			ire_refrele(ire);
3104 		if (prev_ire != NULL)
3105 			ire_refrele(prev_ire);
3106 		return;
3107 	}
3108 
3109 	/*
3110 	 * Should we use the old ULP info to create the new gateway?  From
3111 	 * a user's perspective, we should inherit the info so that it
3112 	 * is a "smooth" transition.  If we do not do that, then new
3113 	 * connections going thru the new gateway will have no route metrics,
3114 	 * which is counter-intuitive to user.  From a network point of
3115 	 * view, this may or may not make sense even though the new gateway
3116 	 * is still directly connected to us so the route metrics should not
3117 	 * change much.
3118 	 *
3119 	 * But if the old ire_uinfo is not initialized, we do another
3120 	 * recursive lookup on the dest using the new gateway.  There may
3121 	 * be a route to that.  If so, use it to initialize the redirect
3122 	 * route.
3123 	 */
3124 	if (prev_ire->ire_uinfo.iulp_set) {
3125 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3126 	} else {
3127 		ire_t *tmp_ire;
3128 		ire_t *sire;
3129 
3130 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3131 		    ALL_ZONES, 0, NULL,
3132 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT),
3133 		    ipst);
3134 		if (sire != NULL) {
3135 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3136 			/*
3137 			 * If sire != NULL, ire_ftable_lookup() should not
3138 			 * return a NULL value.
3139 			 */
3140 			ASSERT(tmp_ire != NULL);
3141 			ire_refrele(tmp_ire);
3142 			ire_refrele(sire);
3143 		} else if (tmp_ire != NULL) {
3144 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3145 			    sizeof (iulp_t));
3146 			ire_refrele(tmp_ire);
3147 		}
3148 	}
3149 	if (prev_ire->ire_type == IRE_CACHE)
3150 		ire_delete(prev_ire);
3151 	ire_refrele(prev_ire);
3152 	/*
3153 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3154 	 * require TOS routing
3155 	 */
3156 	switch (icmph->icmph_code) {
3157 	case 0:
3158 	case 1:
3159 		/* TODO: TOS specificity for cases 2 and 3 */
3160 	case 2:
3161 	case 3:
3162 		break;
3163 	default:
3164 		freemsg(mp);
3165 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3166 		ire_refrele(ire);
3167 		return;
3168 	}
3169 	/*
3170 	 * Create a Route Association.  This will allow us to remember that
3171 	 * someone we believe told us to use the particular gateway.
3172 	 */
3173 	save_ire = ire;
3174 	ire = ire_create(
3175 	    (uchar_t *)&dst,			/* dest addr */
3176 	    (uchar_t *)&ip_g_all_ones,		/* mask */
3177 	    (uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3178 	    (uchar_t *)&gateway,		/* gateway addr */
3179 	    &save_ire->ire_max_frag,		/* max frag */
3180 	    NULL,				/* no src nce */
3181 	    NULL,				/* no rfq */
3182 	    NULL,				/* no stq */
3183 	    IRE_HOST,
3184 	    NULL,				/* ipif */
3185 	    0,					/* cmask */
3186 	    0,					/* phandle */
3187 	    0,					/* ihandle */
3188 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3189 	    &ulp_info,
3190 	    NULL,				/* tsol_gc_t */
3191 	    NULL,				/* gcgrp */
3192 	    ipst);
3193 
3194 	if (ire == NULL) {
3195 		freemsg(mp);
3196 		ire_refrele(save_ire);
3197 		return;
3198 	}
3199 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3200 	ire_refrele(save_ire);
3201 	atomic_inc_32(&ipst->ips_ip_redirect_cnt);
3202 
3203 	if (error == 0) {
3204 		ire_refrele(ire);		/* Held in ire_add_v4 */
3205 		/* tell routing sockets that we received a redirect */
3206 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3207 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3208 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
3209 	}
3210 
3211 	/*
3212 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3213 	 * This together with the added IRE has the effect of
3214 	 * modifying an existing redirect.
3215 	 */
3216 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3217 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), ipst);
3218 	if (prev_ire != NULL) {
3219 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3220 			ire_delete(prev_ire);
3221 		ire_refrele(prev_ire);
3222 	}
3223 
3224 	freemsg(mp);
3225 }
3226 
3227 /*
3228  * Generate an ICMP parameter problem message.
3229  */
3230 static void
3231 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid,
3232 	ip_stack_t *ipst)
3233 {
3234 	icmph_t	icmph;
3235 	boolean_t mctl_present;
3236 	mblk_t *first_mp;
3237 
3238 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3239 
3240 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3241 		if (mctl_present)
3242 			freeb(first_mp);
3243 		return;
3244 	}
3245 
3246 	bzero(&icmph, sizeof (icmph_t));
3247 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3248 	icmph.icmph_pp_ptr = ptr;
3249 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
3250 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3251 	    ipst);
3252 }
3253 
3254 /*
3255  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3256  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3257  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3258  * an icmp error packet can be sent.
3259  * Assigns an appropriate source address to the packet. If ipha_dst is
3260  * one of our addresses use it for source. Otherwise pick a source based
3261  * on a route lookup back to ipha_src.
3262  * Note that ipha_src must be set here since the
3263  * packet is likely to arrive on an ill queue in ip_wput() which will
3264  * not set a source address.
3265  */
3266 static void
3267 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3268     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
3269 {
3270 	ipaddr_t dst;
3271 	icmph_t	*icmph;
3272 	ipha_t	*ipha;
3273 	uint_t	len_needed;
3274 	size_t	msg_len;
3275 	mblk_t	*mp1;
3276 	ipaddr_t src;
3277 	ire_t	*ire;
3278 	mblk_t *ipsec_mp;
3279 	ipsec_out_t	*io = NULL;
3280 
3281 	if (mctl_present) {
3282 		/*
3283 		 * If it is :
3284 		 *
3285 		 * 1) a IPSEC_OUT, then this is caused by outbound
3286 		 *    datagram originating on this host. IPsec processing
3287 		 *    may or may not have been done. Refer to comments above
3288 		 *    icmp_inbound_error_fanout for details.
3289 		 *
3290 		 * 2) a IPSEC_IN if we are generating a icmp_message
3291 		 *    for an incoming datagram destined for us i.e called
3292 		 *    from ip_fanout_send_icmp.
3293 		 */
3294 		ipsec_info_t *in;
3295 		ipsec_mp = mp;
3296 		mp = ipsec_mp->b_cont;
3297 
3298 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3299 		ipha = (ipha_t *)mp->b_rptr;
3300 
3301 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3302 		    in->ipsec_info_type == IPSEC_IN);
3303 
3304 		if (in->ipsec_info_type == IPSEC_IN) {
3305 			/*
3306 			 * Convert the IPSEC_IN to IPSEC_OUT.
3307 			 */
3308 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3309 				BUMP_MIB(&ipst->ips_ip_mib,
3310 				    ipIfStatsOutDiscards);
3311 				return;
3312 			}
3313 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3314 		} else {
3315 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3316 			io = (ipsec_out_t *)in;
3317 			/*
3318 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3319 			 * ire lookup.
3320 			 */
3321 			io->ipsec_out_proc_begin = B_FALSE;
3322 		}
3323 		ASSERT(zoneid == io->ipsec_out_zoneid);
3324 		ASSERT(zoneid != ALL_ZONES);
3325 	} else {
3326 		/*
3327 		 * This is in clear. The icmp message we are building
3328 		 * here should go out in clear.
3329 		 *
3330 		 * Pardon the convolution of it all, but it's easier to
3331 		 * allocate a "use cleartext" IPSEC_IN message and convert
3332 		 * it than it is to allocate a new one.
3333 		 */
3334 		ipsec_in_t *ii;
3335 		ASSERT(DB_TYPE(mp) == M_DATA);
3336 		ipsec_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
3337 		if (ipsec_mp == NULL) {
3338 			freemsg(mp);
3339 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3340 			return;
3341 		}
3342 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3343 
3344 		/* This is not a secure packet */
3345 		ii->ipsec_in_secure = B_FALSE;
3346 		/*
3347 		 * For trusted extensions using a shared IP address we can
3348 		 * send using any zoneid.
3349 		 */
3350 		if (zoneid == ALL_ZONES)
3351 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3352 		else
3353 			ii->ipsec_in_zoneid = zoneid;
3354 		ipsec_mp->b_cont = mp;
3355 		ipha = (ipha_t *)mp->b_rptr;
3356 		/*
3357 		 * Convert the IPSEC_IN to IPSEC_OUT.
3358 		 */
3359 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3360 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3361 			return;
3362 		}
3363 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3364 	}
3365 
3366 	/* Remember our eventual destination */
3367 	dst = ipha->ipha_src;
3368 
3369 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3370 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE, ipst);
3371 	if (ire != NULL &&
3372 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3373 		src = ipha->ipha_dst;
3374 	} else {
3375 		if (ire != NULL)
3376 			ire_refrele(ire);
3377 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3378 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY),
3379 		    ipst);
3380 		if (ire == NULL) {
3381 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3382 			freemsg(ipsec_mp);
3383 			return;
3384 		}
3385 		src = ire->ire_src_addr;
3386 	}
3387 
3388 	if (ire != NULL)
3389 		ire_refrele(ire);
3390 
3391 	/*
3392 	 * Check if we can send back more then 8 bytes in addition to
3393 	 * the IP header.  We try to send 64 bytes of data and the internal
3394 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
3395 	 */
3396 	len_needed = IPH_HDR_LENGTH(ipha);
3397 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
3398 	    ipha->ipha_protocol == IPPROTO_IPV6) {
3399 
3400 		if (!pullupmsg(mp, -1)) {
3401 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3402 			freemsg(ipsec_mp);
3403 			return;
3404 		}
3405 		ipha = (ipha_t *)mp->b_rptr;
3406 
3407 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
3408 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
3409 			    len_needed));
3410 		} else {
3411 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
3412 
3413 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
3414 			len_needed += ip_hdr_length_v6(mp, ip6h);
3415 		}
3416 	}
3417 	len_needed += ipst->ips_ip_icmp_return;
3418 	msg_len = msgdsize(mp);
3419 	if (msg_len > len_needed) {
3420 		(void) adjmsg(mp, len_needed - msg_len);
3421 		msg_len = len_needed;
3422 	}
3423 	mp1 = allocb_tmpl(sizeof (icmp_ipha) + len, mp);
3424 	if (mp1 == NULL) {
3425 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
3426 		freemsg(ipsec_mp);
3427 		return;
3428 	}
3429 	mp1->b_cont = mp;
3430 	mp = mp1;
3431 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3432 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3433 	    io->ipsec_out_type == IPSEC_OUT);
3434 	ipsec_mp->b_cont = mp;
3435 
3436 	/*
3437 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3438 	 * node generates be accepted in peace by all on-host destinations.
3439 	 * If we do NOT assume that all on-host destinations trust
3440 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3441 	 * (Look for ipsec_out_icmp_loopback).
3442 	 */
3443 	io->ipsec_out_icmp_loopback = B_TRUE;
3444 
3445 	ipha = (ipha_t *)mp->b_rptr;
3446 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3447 	*ipha = icmp_ipha;
3448 	ipha->ipha_src = src;
3449 	ipha->ipha_dst = dst;
3450 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
3451 	msg_len += sizeof (icmp_ipha) + len;
3452 	if (msg_len > IP_MAXPACKET) {
3453 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3454 		msg_len = IP_MAXPACKET;
3455 	}
3456 	ipha->ipha_length = htons((uint16_t)msg_len);
3457 	icmph = (icmph_t *)&ipha[1];
3458 	bcopy(stuff, icmph, len);
3459 	icmph->icmph_checksum = 0;
3460 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3461 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
3462 	put(q, ipsec_mp);
3463 }
3464 
3465 /*
3466  * Determine if an ICMP error packet can be sent given the rate limit.
3467  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3468  * in milliseconds) and a burst size. Burst size number of packets can
3469  * be sent arbitrarely closely spaced.
3470  * The state is tracked using two variables to implement an approximate
3471  * token bucket filter:
3472  *	icmp_pkt_err_last - lbolt value when the last burst started
3473  *	icmp_pkt_err_sent - number of packets sent in current burst
3474  */
3475 boolean_t
3476 icmp_err_rate_limit(ip_stack_t *ipst)
3477 {
3478 	clock_t now = TICK_TO_MSEC(lbolt);
3479 	uint_t refilled; /* Number of packets refilled in tbf since last */
3480 	/* Guard against changes by loading into local variable */
3481 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
3482 
3483 	if (err_interval == 0)
3484 		return (B_FALSE);
3485 
3486 	if (ipst->ips_icmp_pkt_err_last > now) {
3487 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3488 		ipst->ips_icmp_pkt_err_last = 0;
3489 		ipst->ips_icmp_pkt_err_sent = 0;
3490 	}
3491 	/*
3492 	 * If we are in a burst update the token bucket filter.
3493 	 * Update the "last" time to be close to "now" but make sure
3494 	 * we don't loose precision.
3495 	 */
3496 	if (ipst->ips_icmp_pkt_err_sent != 0) {
3497 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
3498 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
3499 			ipst->ips_icmp_pkt_err_sent = 0;
3500 		} else {
3501 			ipst->ips_icmp_pkt_err_sent -= refilled;
3502 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
3503 		}
3504 	}
3505 	if (ipst->ips_icmp_pkt_err_sent == 0) {
3506 		/* Start of new burst */
3507 		ipst->ips_icmp_pkt_err_last = now;
3508 	}
3509 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
3510 		ipst->ips_icmp_pkt_err_sent++;
3511 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3512 		    ipst->ips_icmp_pkt_err_sent));
3513 		return (B_FALSE);
3514 	}
3515 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3516 	return (B_TRUE);
3517 }
3518 
3519 /*
3520  * Check if it is ok to send an IPv4 ICMP error packet in
3521  * response to the IPv4 packet in mp.
3522  * Free the message and return null if no
3523  * ICMP error packet should be sent.
3524  */
3525 static mblk_t *
3526 icmp_pkt_err_ok(mblk_t *mp, ip_stack_t *ipst)
3527 {
3528 	icmph_t	*icmph;
3529 	ipha_t	*ipha;
3530 	uint_t	len_needed;
3531 	ire_t	*src_ire;
3532 	ire_t	*dst_ire;
3533 
3534 	if (!mp)
3535 		return (NULL);
3536 	ipha = (ipha_t *)mp->b_rptr;
3537 	if (ip_csum_hdr(ipha)) {
3538 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
3539 		freemsg(mp);
3540 		return (NULL);
3541 	}
3542 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3543 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3544 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3545 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3546 	if (src_ire != NULL || dst_ire != NULL ||
3547 	    CLASSD(ipha->ipha_dst) ||
3548 	    CLASSD(ipha->ipha_src) ||
3549 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3550 		/* Note: only errors to the fragment with offset 0 */
3551 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3552 		freemsg(mp);
3553 		if (src_ire != NULL)
3554 			ire_refrele(src_ire);
3555 		if (dst_ire != NULL)
3556 			ire_refrele(dst_ire);
3557 		return (NULL);
3558 	}
3559 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3560 		/*
3561 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3562 		 * errors in response to any ICMP errors.
3563 		 */
3564 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3565 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3566 			if (!pullupmsg(mp, len_needed)) {
3567 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3568 				freemsg(mp);
3569 				return (NULL);
3570 			}
3571 			ipha = (ipha_t *)mp->b_rptr;
3572 		}
3573 		icmph = (icmph_t *)
3574 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3575 		switch (icmph->icmph_type) {
3576 		case ICMP_DEST_UNREACHABLE:
3577 		case ICMP_SOURCE_QUENCH:
3578 		case ICMP_TIME_EXCEEDED:
3579 		case ICMP_PARAM_PROBLEM:
3580 		case ICMP_REDIRECT:
3581 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3582 			freemsg(mp);
3583 			return (NULL);
3584 		default:
3585 			break;
3586 		}
3587 	}
3588 	/*
3589 	 * If this is a labeled system, then check to see if we're allowed to
3590 	 * send a response to this particular sender.  If not, then just drop.
3591 	 */
3592 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3593 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3594 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3595 		freemsg(mp);
3596 		return (NULL);
3597 	}
3598 	if (icmp_err_rate_limit(ipst)) {
3599 		/*
3600 		 * Only send ICMP error packets every so often.
3601 		 * This should be done on a per port/source basis,
3602 		 * but for now this will suffice.
3603 		 */
3604 		freemsg(mp);
3605 		return (NULL);
3606 	}
3607 	return (mp);
3608 }
3609 
3610 /*
3611  * Generate an ICMP redirect message.
3612  */
3613 static void
3614 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway, ip_stack_t *ipst)
3615 {
3616 	icmph_t	icmph;
3617 
3618 	/*
3619 	 * We are called from ip_rput where we could
3620 	 * not have attached an IPSEC_IN.
3621 	 */
3622 	ASSERT(mp->b_datap->db_type == M_DATA);
3623 
3624 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3625 		return;
3626 	}
3627 
3628 	bzero(&icmph, sizeof (icmph_t));
3629 	icmph.icmph_type = ICMP_REDIRECT;
3630 	icmph.icmph_code = 1;
3631 	icmph.icmph_rd_gateway = gateway;
3632 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3633 	/* Redirects sent by router, and router is global zone */
3634 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID, ipst);
3635 }
3636 
3637 /*
3638  * Generate an ICMP time exceeded message.
3639  */
3640 void
3641 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3642     ip_stack_t *ipst)
3643 {
3644 	icmph_t	icmph;
3645 	boolean_t mctl_present;
3646 	mblk_t *first_mp;
3647 
3648 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3649 
3650 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3651 		if (mctl_present)
3652 			freeb(first_mp);
3653 		return;
3654 	}
3655 
3656 	bzero(&icmph, sizeof (icmph_t));
3657 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3658 	icmph.icmph_code = code;
3659 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3660 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3661 	    ipst);
3662 }
3663 
3664 /*
3665  * Generate an ICMP unreachable message.
3666  */
3667 void
3668 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3669     ip_stack_t *ipst)
3670 {
3671 	icmph_t	icmph;
3672 	mblk_t *first_mp;
3673 	boolean_t mctl_present;
3674 
3675 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3676 
3677 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3678 		if (mctl_present)
3679 			freeb(first_mp);
3680 		return;
3681 	}
3682 
3683 	bzero(&icmph, sizeof (icmph_t));
3684 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3685 	icmph.icmph_code = code;
3686 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3687 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3688 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3689 	    zoneid, ipst);
3690 }
3691 
3692 /*
3693  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3694  * duplicate.  As long as someone else holds the address, the interface will
3695  * stay down.  When that conflict goes away, the interface is brought back up.
3696  * This is done so that accidental shutdowns of addresses aren't made
3697  * permanent.  Your server will recover from a failure.
3698  *
3699  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3700  * user space process (dhcpagent).
3701  *
3702  * Recovery completes if ARP reports that the address is now ours (via
3703  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3704  *
3705  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3706  */
3707 static void
3708 ipif_dup_recovery(void *arg)
3709 {
3710 	ipif_t *ipif = arg;
3711 	ill_t *ill = ipif->ipif_ill;
3712 	mblk_t *arp_add_mp;
3713 	mblk_t *arp_del_mp;
3714 	area_t *area;
3715 	ip_stack_t *ipst = ill->ill_ipst;
3716 
3717 	ipif->ipif_recovery_id = 0;
3718 
3719 	/*
3720 	 * No lock needed for moving or condemned check, as this is just an
3721 	 * optimization.
3722 	 */
3723 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3724 	    (ipif->ipif_flags & IPIF_POINTOPOINT) ||
3725 	    (ipif->ipif_state_flags & (IPIF_MOVING | IPIF_CONDEMNED))) {
3726 		/* No reason to try to bring this address back. */
3727 		return;
3728 	}
3729 
3730 	if ((arp_add_mp = ipif_area_alloc(ipif)) == NULL)
3731 		goto alloc_fail;
3732 
3733 	if (ipif->ipif_arp_del_mp == NULL) {
3734 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3735 			goto alloc_fail;
3736 		ipif->ipif_arp_del_mp = arp_del_mp;
3737 	}
3738 
3739 	/* Setting the 'unverified' flag restarts DAD */
3740 	area = (area_t *)arp_add_mp->b_rptr;
3741 	area->area_flags = ACE_F_PERMANENT | ACE_F_PUBLISH | ACE_F_MYADDR |
3742 	    ACE_F_UNVERIFIED;
3743 	putnext(ill->ill_rq, arp_add_mp);
3744 	return;
3745 
3746 alloc_fail:
3747 	/*
3748 	 * On allocation failure, just restart the timer.  Note that the ipif
3749 	 * is down here, so no other thread could be trying to start a recovery
3750 	 * timer.  The ill_lock protects the condemned flag and the recovery
3751 	 * timer ID.
3752 	 */
3753 	freemsg(arp_add_mp);
3754 	mutex_enter(&ill->ill_lock);
3755 	if (ipst->ips_ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0 &&
3756 	    !(ipif->ipif_state_flags & IPIF_CONDEMNED)) {
3757 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3758 		    MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3759 	}
3760 	mutex_exit(&ill->ill_lock);
3761 }
3762 
3763 /*
3764  * This is for exclusive changes due to ARP.  Either tear down an interface due
3765  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3766  */
3767 /* ARGSUSED */
3768 static void
3769 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3770 {
3771 	ill_t	*ill = rq->q_ptr;
3772 	arh_t *arh;
3773 	ipaddr_t src;
3774 	ipif_t	*ipif;
3775 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3776 	char hbuf[MAC_STR_LEN];
3777 	char sbuf[INET_ADDRSTRLEN];
3778 	const char *failtype;
3779 	boolean_t bring_up;
3780 	ip_stack_t *ipst = ill->ill_ipst;
3781 
3782 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3783 	case AR_CN_READY:
3784 		failtype = NULL;
3785 		bring_up = B_TRUE;
3786 		break;
3787 	case AR_CN_FAILED:
3788 		failtype = "in use";
3789 		bring_up = B_FALSE;
3790 		break;
3791 	default:
3792 		failtype = "claimed";
3793 		bring_up = B_FALSE;
3794 		break;
3795 	}
3796 
3797 	arh = (arh_t *)mp->b_cont->b_rptr;
3798 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3799 
3800 	/* Handle failures due to probes */
3801 	if (src == 0) {
3802 		bcopy((char *)&arh[1] + 2 * arh->arh_hlen + IP_ADDR_LEN, &src,
3803 		    IP_ADDR_LEN);
3804 	}
3805 
3806 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3807 	    sizeof (hbuf));
3808 	(void) ip_dot_addr(src, sbuf);
3809 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3810 
3811 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3812 		    ipif->ipif_lcl_addr != src) {
3813 			continue;
3814 		}
3815 
3816 		/*
3817 		 * If we failed on a recovery probe, then restart the timer to
3818 		 * try again later.
3819 		 */
3820 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3821 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3822 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3823 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3824 		    ipst->ips_ip_dup_recovery > 0 &&
3825 		    ipif->ipif_recovery_id == 0) {
3826 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3827 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3828 			continue;
3829 		}
3830 
3831 		/*
3832 		 * If what we're trying to do has already been done, then do
3833 		 * nothing.
3834 		 */
3835 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3836 			continue;
3837 
3838 		ipif_get_name(ipif, ibuf, sizeof (ibuf));
3839 
3840 		if (failtype == NULL) {
3841 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3842 			    ibuf);
3843 		} else {
3844 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3845 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3846 		}
3847 
3848 		if (bring_up) {
3849 			ASSERT(ill->ill_dl_up);
3850 			/*
3851 			 * Free up the ARP delete message so we can allocate
3852 			 * a fresh one through the normal path.
3853 			 */
3854 			freemsg(ipif->ipif_arp_del_mp);
3855 			ipif->ipif_arp_del_mp = NULL;
3856 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3857 			    EINPROGRESS) {
3858 				ipif->ipif_addr_ready = 1;
3859 				(void) ipif_up_done(ipif);
3860 			}
3861 			continue;
3862 		}
3863 
3864 		mutex_enter(&ill->ill_lock);
3865 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3866 		ipif->ipif_flags |= IPIF_DUPLICATE;
3867 		ill->ill_ipif_dup_count++;
3868 		mutex_exit(&ill->ill_lock);
3869 		/*
3870 		 * Already exclusive on the ill; no need to handle deferred
3871 		 * processing here.
3872 		 */
3873 		(void) ipif_down(ipif, NULL, NULL);
3874 		ipif_down_tail(ipif);
3875 		mutex_enter(&ill->ill_lock);
3876 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3877 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3878 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3879 		    ipst->ips_ip_dup_recovery > 0) {
3880 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3881 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3882 		}
3883 		mutex_exit(&ill->ill_lock);
3884 	}
3885 	freemsg(mp);
3886 }
3887 
3888 /* ARGSUSED */
3889 static void
3890 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3891 {
3892 	ill_t	*ill = rq->q_ptr;
3893 	arh_t *arh;
3894 	ipaddr_t src;
3895 	ipif_t	*ipif;
3896 
3897 	arh = (arh_t *)mp->b_cont->b_rptr;
3898 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3899 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3900 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3901 			(void) ipif_resolver_up(ipif, Res_act_defend);
3902 	}
3903 	freemsg(mp);
3904 }
3905 
3906 /*
3907  * News from ARP.  ARP sends notification of interesting events down
3908  * to its clients using M_CTL messages with the interesting ARP packet
3909  * attached via b_cont.
3910  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3911  * queue as opposed to ARP sending the message to all the clients, i.e. all
3912  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3913  * table if a cache IRE is found to delete all the entries for the address in
3914  * the packet.
3915  */
3916 static void
3917 ip_arp_news(queue_t *q, mblk_t *mp)
3918 {
3919 	arcn_t		*arcn;
3920 	arh_t		*arh;
3921 	ire_t		*ire = NULL;
3922 	char		hbuf[MAC_STR_LEN];
3923 	char		sbuf[INET_ADDRSTRLEN];
3924 	ipaddr_t	src;
3925 	in6_addr_t	v6src;
3926 	boolean_t	isv6 = B_FALSE;
3927 	ipif_t		*ipif;
3928 	ill_t		*ill;
3929 	ip_stack_t	*ipst;
3930 
3931 	if (CONN_Q(q)) {
3932 		conn_t *connp = Q_TO_CONN(q);
3933 
3934 		ipst = connp->conn_netstack->netstack_ip;
3935 	} else {
3936 		ill_t *ill = (ill_t *)q->q_ptr;
3937 
3938 		ipst = ill->ill_ipst;
3939 	}
3940 
3941 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3942 		if (q->q_next) {
3943 			putnext(q, mp);
3944 		} else
3945 			freemsg(mp);
3946 		return;
3947 	}
3948 	arh = (arh_t *)mp->b_cont->b_rptr;
3949 	/* Is it one we are interested in? */
3950 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3951 		isv6 = B_TRUE;
3952 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3953 		    IPV6_ADDR_LEN);
3954 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3955 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3956 		    IP_ADDR_LEN);
3957 	} else {
3958 		freemsg(mp);
3959 		return;
3960 	}
3961 
3962 	ill = q->q_ptr;
3963 
3964 	arcn = (arcn_t *)mp->b_rptr;
3965 	switch (arcn->arcn_code) {
3966 	case AR_CN_BOGON:
3967 		/*
3968 		 * Someone is sending ARP packets with a source protocol
3969 		 * address that we have published and for which we believe our
3970 		 * entry is authoritative and (when ill_arp_extend is set)
3971 		 * verified to be unique on the network.
3972 		 *
3973 		 * The ARP module internally handles the cases where the sender
3974 		 * is just probing (for DAD) and where the hardware address of
3975 		 * a non-authoritative entry has changed.  Thus, these are the
3976 		 * real conflicts, and we have to do resolution.
3977 		 *
3978 		 * We back away quickly from the address if it's from DHCP or
3979 		 * otherwise temporary and hasn't been used recently (or at
3980 		 * all).  We'd like to include "deprecated" addresses here as
3981 		 * well (as there's no real reason to defend something we're
3982 		 * discarding), but IPMP "reuses" this flag to mean something
3983 		 * other than the standard meaning.
3984 		 *
3985 		 * If the ARP module above is not extended (meaning that it
3986 		 * doesn't know how to defend the address), then we just log
3987 		 * the problem as we always did and continue on.  It's not
3988 		 * right, but there's little else we can do, and those old ATM
3989 		 * users are going away anyway.
3990 		 */
3991 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
3992 		    hbuf, sizeof (hbuf));
3993 		(void) ip_dot_addr(src, sbuf);
3994 		if (isv6) {
3995 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL,
3996 			    ipst);
3997 		} else {
3998 			ire = ire_cache_lookup(src, ALL_ZONES, NULL, ipst);
3999 		}
4000 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
4001 			uint32_t now;
4002 			uint32_t maxage;
4003 			clock_t lused;
4004 			uint_t maxdefense;
4005 			uint_t defs;
4006 
4007 			/*
4008 			 * First, figure out if this address hasn't been used
4009 			 * in a while.  If it hasn't, then it's a better
4010 			 * candidate for abandoning.
4011 			 */
4012 			ipif = ire->ire_ipif;
4013 			ASSERT(ipif != NULL);
4014 			now = gethrestime_sec();
4015 			maxage = now - ire->ire_create_time;
4016 			if (maxage > ipst->ips_ip_max_temp_idle)
4017 				maxage = ipst->ips_ip_max_temp_idle;
4018 			lused = drv_hztousec(ddi_get_lbolt() -
4019 			    ire->ire_last_used_time) / MICROSEC + 1;
4020 			if (lused >= maxage && (ipif->ipif_flags &
4021 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
4022 				maxdefense = ipst->ips_ip_max_temp_defend;
4023 			else
4024 				maxdefense = ipst->ips_ip_max_defend;
4025 
4026 			/*
4027 			 * Now figure out how many times we've defended
4028 			 * ourselves.  Ignore defenses that happened long in
4029 			 * the past.
4030 			 */
4031 			mutex_enter(&ire->ire_lock);
4032 			if ((defs = ire->ire_defense_count) > 0 &&
4033 			    now - ire->ire_defense_time >
4034 			    ipst->ips_ip_defend_interval) {
4035 				ire->ire_defense_count = defs = 0;
4036 			}
4037 			ire->ire_defense_count++;
4038 			ire->ire_defense_time = now;
4039 			mutex_exit(&ire->ire_lock);
4040 			ill_refhold(ill);
4041 			ire_refrele(ire);
4042 
4043 			/*
4044 			 * If we've defended ourselves too many times already,
4045 			 * then give up and tear down the interface(s) using
4046 			 * this address.  Otherwise, defend by sending out a
4047 			 * gratuitous ARP.
4048 			 */
4049 			if (defs >= maxdefense && ill->ill_arp_extend) {
4050 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4051 				    B_FALSE);
4052 			} else {
4053 				cmn_err(CE_WARN,
4054 				    "node %s is using our IP address %s on %s",
4055 				    hbuf, sbuf, ill->ill_name);
4056 				/*
4057 				 * If this is an old (ATM) ARP module, then
4058 				 * don't try to defend the address.  Remain
4059 				 * compatible with the old behavior.  Defend
4060 				 * only with new ARP.
4061 				 */
4062 				if (ill->ill_arp_extend) {
4063 					qwriter_ip(ill, q, mp, ip_arp_defend,
4064 					    NEW_OP, B_FALSE);
4065 				} else {
4066 					ill_refrele(ill);
4067 				}
4068 			}
4069 			return;
4070 		}
4071 		cmn_err(CE_WARN,
4072 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4073 		    hbuf, sbuf, ill->ill_name);
4074 		if (ire != NULL)
4075 			ire_refrele(ire);
4076 		break;
4077 	case AR_CN_ANNOUNCE:
4078 		if (isv6) {
4079 			/*
4080 			 * For XRESOLV interfaces.
4081 			 * Delete the IRE cache entry and NCE for this
4082 			 * v6 address
4083 			 */
4084 			ip_ire_clookup_and_delete_v6(&v6src, ipst);
4085 			/*
4086 			 * If v6src is a non-zero, it's a router address
4087 			 * as below. Do the same sort of thing to clean
4088 			 * out off-net IRE_CACHE entries that go through
4089 			 * the router.
4090 			 */
4091 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4092 				ire_walk_v6(ire_delete_cache_gw_v6,
4093 				    (char *)&v6src, ALL_ZONES, ipst);
4094 			}
4095 		} else {
4096 			nce_hw_map_t hwm;
4097 
4098 			/*
4099 			 * ARP gives us a copy of any packet where it thinks
4100 			 * the address has changed, so that we can update our
4101 			 * caches.  We're responsible for caching known answers
4102 			 * in the current design.  We check whether the
4103 			 * hardware address really has changed in all of our
4104 			 * entries that have cached this mapping, and if so, we
4105 			 * blow them away.  This way we will immediately pick
4106 			 * up the rare case of a host changing hardware
4107 			 * address.
4108 			 */
4109 			if (src == 0)
4110 				break;
4111 			hwm.hwm_addr = src;
4112 			hwm.hwm_hwlen = arh->arh_hlen;
4113 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4114 			NDP_HW_CHANGE_INCR(ipst->ips_ndp4);
4115 			ndp_walk_common(ipst->ips_ndp4, NULL,
4116 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4117 			NDP_HW_CHANGE_DECR(ipst->ips_ndp4);
4118 		}
4119 		break;
4120 	case AR_CN_READY:
4121 		/* No external v6 resolver has a contract to use this */
4122 		if (isv6)
4123 			break;
4124 		/* If the link is down, we'll retry this later */
4125 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4126 			break;
4127 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4128 		    NULL, NULL, ipst);
4129 		if (ipif != NULL) {
4130 			/*
4131 			 * If this is a duplicate recovery, then we now need to
4132 			 * go exclusive to bring this thing back up.
4133 			 */
4134 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4135 			    IPIF_DUPLICATE) {
4136 				ipif_refrele(ipif);
4137 				ill_refhold(ill);
4138 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4139 				    B_FALSE);
4140 				return;
4141 			}
4142 			/*
4143 			 * If this is the first notice that this address is
4144 			 * ready, then let the user know now.
4145 			 */
4146 			if ((ipif->ipif_flags & IPIF_UP) &&
4147 			    !ipif->ipif_addr_ready) {
4148 				ipif_mask_reply(ipif);
4149 				ip_rts_ifmsg(ipif);
4150 				ip_rts_newaddrmsg(RTM_ADD, 0, ipif);
4151 				sctp_update_ipif(ipif, SCTP_IPIF_UP);
4152 			}
4153 			ipif->ipif_addr_ready = 1;
4154 			ipif_refrele(ipif);
4155 		}
4156 		ire = ire_cache_lookup(src, ALL_ZONES, MBLK_GETLABEL(mp), ipst);
4157 		if (ire != NULL) {
4158 			ire->ire_defense_count = 0;
4159 			ire_refrele(ire);
4160 		}
4161 		break;
4162 	case AR_CN_FAILED:
4163 		/* No external v6 resolver has a contract to use this */
4164 		if (isv6)
4165 			break;
4166 		ill_refhold(ill);
4167 		qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP, B_FALSE);
4168 		return;
4169 	}
4170 	freemsg(mp);
4171 }
4172 
4173 /*
4174  * Create a mblk suitable for carrying the interface index and/or source link
4175  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4176  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4177  * application.
4178  */
4179 mblk_t *
4180 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags, zoneid_t zoneid,
4181     ip_stack_t *ipst)
4182 {
4183 	mblk_t		*mp;
4184 	ip_pktinfo_t	*pinfo;
4185 	ipha_t *ipha;
4186 	struct ether_header *pether;
4187 
4188 	mp = allocb(sizeof (ip_pktinfo_t), BPRI_MED);
4189 	if (mp == NULL) {
4190 		ip1dbg(("ip_add_info: allocation failure.\n"));
4191 		return (data_mp);
4192 	}
4193 
4194 	ipha	= (ipha_t *)data_mp->b_rptr;
4195 	pinfo = (ip_pktinfo_t *)mp->b_rptr;
4196 	bzero(pinfo, sizeof (ip_pktinfo_t));
4197 	pinfo->ip_pkt_flags = (uchar_t)flags;
4198 	pinfo->ip_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4199 
4200 	if (flags & (IPF_RECVIF | IPF_RECVADDR))
4201 		pinfo->ip_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4202 	if (flags & IPF_RECVADDR) {
4203 		ipif_t	*ipif;
4204 		ire_t	*ire;
4205 
4206 		/*
4207 		 * Only valid for V4
4208 		 */
4209 		ASSERT((ipha->ipha_version_and_hdr_length & 0xf0) ==
4210 		    (IPV4_VERSION << 4));
4211 
4212 		ipif = ipif_get_next_ipif(NULL, ill);
4213 		if (ipif != NULL) {
4214 			/*
4215 			 * Since a decision has already been made to deliver the
4216 			 * packet, there is no need to test for SECATTR and
4217 			 * ZONEONLY.
4218 			 * When a multicast packet is transmitted
4219 			 * a cache entry is created for the multicast address.
4220 			 * When delivering a copy of the packet or when new
4221 			 * packets are received we do not want to match on the
4222 			 * cached entry so explicitly match on
4223 			 * IRE_LOCAL and IRE_LOOPBACK
4224 			 */
4225 			ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4226 			    IRE_LOCAL | IRE_LOOPBACK,
4227 			    ipif, zoneid, NULL,
4228 			    MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP, ipst);
4229 			if (ire == NULL) {
4230 				/*
4231 				 * packet must have come on a different
4232 				 * interface.
4233 				 * Since a decision has already been made to
4234 				 * deliver the packet, there is no need to test
4235 				 * for SECATTR and ZONEONLY.
4236 				 * Only match on local and broadcast ire's.
4237 				 * See detailed comment above.
4238 				 */
4239 				ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4240 				    IRE_LOCAL | IRE_LOOPBACK, ipif, zoneid,
4241 				    NULL, MATCH_IRE_TYPE, ipst);
4242 			}
4243 
4244 			if (ire == NULL) {
4245 				/*
4246 				 * This is either a multicast packet or
4247 				 * the address has been removed since
4248 				 * the packet was received.
4249 				 * Return INADDR_ANY so that normal source
4250 				 * selection occurs for the response.
4251 				 */
4252 
4253 				pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4254 			} else {
4255 				pinfo->ip_pkt_match_addr.s_addr =
4256 				    ire->ire_src_addr;
4257 				ire_refrele(ire);
4258 			}
4259 			ipif_refrele(ipif);
4260 		} else {
4261 			pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4262 		}
4263 	}
4264 
4265 	pether = (struct ether_header *)((char *)ipha
4266 	    - sizeof (struct ether_header));
4267 	/*
4268 	 * Make sure the interface is an ethernet type, since this option
4269 	 * is currently supported only on this type of interface. Also make
4270 	 * sure we are pointing correctly above db_base.
4271 	 */
4272 
4273 	if ((flags & IPF_RECVSLLA) &&
4274 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4275 	    (ill->ill_type == IFT_ETHER) &&
4276 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4277 
4278 		pinfo->ip_pkt_slla.sdl_type = IFT_ETHER;
4279 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
4280 		    (uchar_t *)pinfo->ip_pkt_slla.sdl_data, ETHERADDRL);
4281 	} else {
4282 		/*
4283 		 * Clear the bit. Indicate to upper layer that IP is not
4284 		 * sending this ancillary info.
4285 		 */
4286 		pinfo->ip_pkt_flags = pinfo->ip_pkt_flags & ~IPF_RECVSLLA;
4287 	}
4288 
4289 	mp->b_datap->db_type = M_CTL;
4290 	mp->b_wptr += sizeof (ip_pktinfo_t);
4291 	mp->b_cont = data_mp;
4292 
4293 	return (mp);
4294 }
4295 
4296 /*
4297  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4298  * part of the bind request.
4299  */
4300 
4301 boolean_t
4302 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4303 {
4304 	ipsec_in_t *ii;
4305 
4306 	ASSERT(policy_mp != NULL);
4307 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4308 
4309 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4310 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4311 
4312 	connp->conn_policy = ii->ipsec_in_policy;
4313 	ii->ipsec_in_policy = NULL;
4314 
4315 	if (ii->ipsec_in_action != NULL) {
4316 		if (connp->conn_latch == NULL) {
4317 			connp->conn_latch = iplatch_create();
4318 			if (connp->conn_latch == NULL)
4319 				return (B_FALSE);
4320 		}
4321 		ipsec_latch_inbound(connp->conn_latch, ii);
4322 	}
4323 	return (B_TRUE);
4324 }
4325 
4326 /*
4327  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4328  * and to arrange for power-fanout assist.  The ULP is identified by
4329  * adding a single byte at the end of the original bind message.
4330  * A ULP other than UDP or TCP that wishes to be recognized passes
4331  * down a bind with a zero length address.
4332  *
4333  * The binding works as follows:
4334  * - A zero byte address means just bind to the protocol.
4335  * - A four byte address is treated as a request to validate
4336  *   that the address is a valid local address, appropriate for
4337  *   an application to bind to. This does not affect any fanout
4338  *   information in IP.
4339  * - A sizeof sin_t byte address is used to bind to only the local address
4340  *   and port.
4341  * - A sizeof ipa_conn_t byte address contains complete fanout information
4342  *   consisting of local and remote addresses and ports.  In
4343  *   this case, the addresses are both validated as appropriate
4344  *   for this operation, and, if so, the information is retained
4345  *   for use in the inbound fanout.
4346  *
4347  * The ULP (except in the zero-length bind) can append an
4348  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4349  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4350  * a copy of the source or destination IRE (source for local bind;
4351  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4352  * policy information contained should be copied on to the conn.
4353  *
4354  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4355  */
4356 mblk_t *
4357 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4358 {
4359 	ssize_t		len;
4360 	struct T_bind_req	*tbr;
4361 	sin_t		*sin;
4362 	ipa_conn_t	*ac;
4363 	uchar_t		*ucp;
4364 	mblk_t		*mp1;
4365 	boolean_t	ire_requested;
4366 	boolean_t	ipsec_policy_set = B_FALSE;
4367 	int		error = 0;
4368 	int		protocol;
4369 	ipa_conn_x_t	*acx;
4370 
4371 	ASSERT(!connp->conn_af_isv6);
4372 	connp->conn_pkt_isv6 = B_FALSE;
4373 
4374 	len = MBLKL(mp);
4375 	if (len < (sizeof (*tbr) + 1)) {
4376 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4377 		    "ip_bind: bogus msg, len %ld", len);
4378 		/* XXX: Need to return something better */
4379 		goto bad_addr;
4380 	}
4381 	/* Back up and extract the protocol identifier. */
4382 	mp->b_wptr--;
4383 	protocol = *mp->b_wptr & 0xFF;
4384 	tbr = (struct T_bind_req *)mp->b_rptr;
4385 	/* Reset the message type in preparation for shipping it back. */
4386 	DB_TYPE(mp) = M_PCPROTO;
4387 
4388 	connp->conn_ulp = (uint8_t)protocol;
4389 
4390 	/*
4391 	 * Check for a zero length address.  This is from a protocol that
4392 	 * wants to register to receive all packets of its type.
4393 	 */
4394 	if (tbr->ADDR_length == 0) {
4395 		/*
4396 		 * These protocols are now intercepted in ip_bind_v6().
4397 		 * Reject protocol-level binds here for now.
4398 		 *
4399 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4400 		 * so that the protocol type cannot be SCTP.
4401 		 */
4402 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4403 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4404 			goto bad_addr;
4405 		}
4406 
4407 		/*
4408 		 *
4409 		 * The udp module never sends down a zero-length address,
4410 		 * and allowing this on a labeled system will break MLP
4411 		 * functionality.
4412 		 */
4413 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4414 			goto bad_addr;
4415 
4416 		if (connp->conn_mac_exempt)
4417 			goto bad_addr;
4418 
4419 		/* No hash here really.  The table is big enough. */
4420 		connp->conn_srcv6 = ipv6_all_zeros;
4421 
4422 		ipcl_proto_insert(connp, protocol);
4423 
4424 		tbr->PRIM_type = T_BIND_ACK;
4425 		return (mp);
4426 	}
4427 
4428 	/* Extract the address pointer from the message. */
4429 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4430 	    tbr->ADDR_length);
4431 	if (ucp == NULL) {
4432 		ip1dbg(("ip_bind: no address\n"));
4433 		goto bad_addr;
4434 	}
4435 	if (!OK_32PTR(ucp)) {
4436 		ip1dbg(("ip_bind: unaligned address\n"));
4437 		goto bad_addr;
4438 	}
4439 	/*
4440 	 * Check for trailing mps.
4441 	 */
4442 
4443 	mp1 = mp->b_cont;
4444 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4445 	ipsec_policy_set = (mp1 != NULL && DB_TYPE(mp1) == IPSEC_POLICY_SET);
4446 
4447 	switch (tbr->ADDR_length) {
4448 	default:
4449 		ip1dbg(("ip_bind: bad address length %d\n",
4450 		    (int)tbr->ADDR_length));
4451 		goto bad_addr;
4452 
4453 	case IP_ADDR_LEN:
4454 		/* Verification of local address only */
4455 		error = ip_bind_laddr(connp, mp, *(ipaddr_t *)ucp, 0,
4456 		    ire_requested, ipsec_policy_set, B_FALSE);
4457 		break;
4458 
4459 	case sizeof (sin_t):
4460 		sin = (sin_t *)ucp;
4461 		error = ip_bind_laddr(connp, mp, sin->sin_addr.s_addr,
4462 		    sin->sin_port, ire_requested, ipsec_policy_set, B_TRUE);
4463 		break;
4464 
4465 	case sizeof (ipa_conn_t):
4466 		ac = (ipa_conn_t *)ucp;
4467 		/* For raw socket, the local port is not set. */
4468 		if (ac->ac_lport == 0)
4469 			ac->ac_lport = connp->conn_lport;
4470 		/* Always verify destination reachability. */
4471 		error = ip_bind_connected(connp, mp, &ac->ac_laddr,
4472 		    ac->ac_lport, ac->ac_faddr, ac->ac_fport, ire_requested,
4473 		    ipsec_policy_set, B_TRUE, B_TRUE);
4474 		break;
4475 
4476 	case sizeof (ipa_conn_x_t):
4477 		acx = (ipa_conn_x_t *)ucp;
4478 		/*
4479 		 * Whether or not to verify destination reachability depends
4480 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4481 		 */
4482 		error = ip_bind_connected(connp, mp, &acx->acx_conn.ac_laddr,
4483 		    acx->acx_conn.ac_lport, acx->acx_conn.ac_faddr,
4484 		    acx->acx_conn.ac_fport, ire_requested, ipsec_policy_set,
4485 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
4486 		break;
4487 	}
4488 	if (error == EINPROGRESS)
4489 		return (NULL);
4490 	else if (error != 0)
4491 		goto bad_addr;
4492 	/*
4493 	 * Pass the IPsec headers size in ire_ipsec_overhead.
4494 	 * We can't do this in ip_bind_insert_ire because the policy
4495 	 * may not have been inherited at that point in time and hence
4496 	 * conn_out_enforce_policy may not be set.
4497 	 */
4498 	mp1 = mp->b_cont;
4499 	if (ire_requested && connp->conn_out_enforce_policy &&
4500 	    mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE) {
4501 		ire_t *ire = (ire_t *)mp1->b_rptr;
4502 		ASSERT(MBLKL(mp1) >= sizeof (ire_t));
4503 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4504 	}
4505 
4506 	/* Send it home. */
4507 	mp->b_datap->db_type = M_PCPROTO;
4508 	tbr->PRIM_type = T_BIND_ACK;
4509 	return (mp);
4510 
4511 bad_addr:
4512 	/*
4513 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4514 	 * a unix errno.
4515 	 */
4516 	if (error > 0)
4517 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4518 	else
4519 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4520 	return (mp);
4521 }
4522 
4523 /*
4524  * Here address is verified to be a valid local address.
4525  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4526  * address is also considered a valid local address.
4527  * In the case of a broadcast/multicast address, however, the
4528  * upper protocol is expected to reset the src address
4529  * to 0 if it sees a IRE_BROADCAST type returned so that
4530  * no packets are emitted with broadcast/multicast address as
4531  * source address (that violates hosts requirements RFC1122)
4532  * The addresses valid for bind are:
4533  *	(1) - INADDR_ANY (0)
4534  *	(2) - IP address of an UP interface
4535  *	(3) - IP address of a DOWN interface
4536  *	(4) - valid local IP broadcast addresses. In this case
4537  *	the conn will only receive packets destined to
4538  *	the specified broadcast address.
4539  *	(5) - a multicast address. In this case
4540  *	the conn will only receive packets destined to
4541  *	the specified multicast address. Note: the
4542  *	application still has to issue an
4543  *	IP_ADD_MEMBERSHIP socket option.
4544  *
4545  * On error, return -1 for TBADADDR otherwise pass the
4546  * errno with TSYSERR reply.
4547  *
4548  * In all the above cases, the bound address must be valid in the current zone.
4549  * When the address is loopback, multicast or broadcast, there might be many
4550  * matching IREs so bind has to look up based on the zone.
4551  *
4552  * Note: lport is in network byte order.
4553  */
4554 int
4555 ip_bind_laddr(conn_t *connp, mblk_t *mp, ipaddr_t src_addr, uint16_t lport,
4556     boolean_t ire_requested, boolean_t ipsec_policy_set,
4557     boolean_t fanout_insert)
4558 {
4559 	int		error = 0;
4560 	ire_t		*src_ire;
4561 	mblk_t		*policy_mp;
4562 	ipif_t		*ipif;
4563 	zoneid_t	zoneid;
4564 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4565 
4566 	if (ipsec_policy_set) {
4567 		policy_mp = mp->b_cont;
4568 	}
4569 
4570 	/*
4571 	 * If it was previously connected, conn_fully_bound would have
4572 	 * been set.
4573 	 */
4574 	connp->conn_fully_bound = B_FALSE;
4575 
4576 	src_ire = NULL;
4577 	ipif = NULL;
4578 
4579 	zoneid = IPCL_ZONEID(connp);
4580 
4581 	if (src_addr) {
4582 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4583 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
4584 		/*
4585 		 * If an address other than 0.0.0.0 is requested,
4586 		 * we verify that it is a valid address for bind
4587 		 * Note: Following code is in if-else-if form for
4588 		 * readability compared to a condition check.
4589 		 */
4590 		/* LINTED - statement has no consequent */
4591 		if (IRE_IS_LOCAL(src_ire)) {
4592 			/*
4593 			 * (2) Bind to address of local UP interface
4594 			 */
4595 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4596 			/*
4597 			 * (4) Bind to broadcast address
4598 			 * Note: permitted only from transports that
4599 			 * request IRE
4600 			 */
4601 			if (!ire_requested)
4602 				error = EADDRNOTAVAIL;
4603 		} else {
4604 			/*
4605 			 * (3) Bind to address of local DOWN interface
4606 			 * (ipif_lookup_addr() looks up all interfaces
4607 			 * but we do not get here for UP interfaces
4608 			 * - case (2) above)
4609 			 * We put the protocol byte back into the mblk
4610 			 * since we may come back via ip_wput_nondata()
4611 			 * later with this mblk if ipif_lookup_addr chooses
4612 			 * to defer processing.
4613 			 */
4614 			*mp->b_wptr++ = (char)connp->conn_ulp;
4615 			if ((ipif = ipif_lookup_addr(src_addr, NULL, zoneid,
4616 			    CONNP_TO_WQ(connp), mp, ip_wput_nondata,
4617 			    &error, ipst)) != NULL) {
4618 				ipif_refrele(ipif);
4619 			} else if (error == EINPROGRESS) {
4620 				if (src_ire != NULL)
4621 					ire_refrele(src_ire);
4622 				return (EINPROGRESS);
4623 			} else if (CLASSD(src_addr)) {
4624 				error = 0;
4625 				if (src_ire != NULL)
4626 					ire_refrele(src_ire);
4627 				/*
4628 				 * (5) bind to multicast address.
4629 				 * Fake out the IRE returned to upper
4630 				 * layer to be a broadcast IRE.
4631 				 */
4632 				src_ire = ire_ctable_lookup(
4633 				    INADDR_BROADCAST, INADDR_ANY,
4634 				    IRE_BROADCAST, NULL, zoneid, NULL,
4635 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY),
4636 				    ipst);
4637 				if (src_ire == NULL || !ire_requested)
4638 					error = EADDRNOTAVAIL;
4639 			} else {
4640 				/*
4641 				 * Not a valid address for bind
4642 				 */
4643 				error = EADDRNOTAVAIL;
4644 			}
4645 			/*
4646 			 * Just to keep it consistent with the processing in
4647 			 * ip_bind_v4()
4648 			 */
4649 			mp->b_wptr--;
4650 		}
4651 		if (error) {
4652 			/* Red Alert!  Attempting to be a bogon! */
4653 			ip1dbg(("ip_bind: bad src address 0x%x\n",
4654 			    ntohl(src_addr)));
4655 			goto bad_addr;
4656 		}
4657 	}
4658 
4659 	/*
4660 	 * Allow setting new policies. For example, disconnects come
4661 	 * down as ipa_t bind. As we would have set conn_policy_cached
4662 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4663 	 * can change after the disconnect.
4664 	 */
4665 	connp->conn_policy_cached = B_FALSE;
4666 
4667 	/*
4668 	 * If not fanout_insert this was just an address verification
4669 	 */
4670 	if (fanout_insert) {
4671 		/*
4672 		 * The addresses have been verified. Time to insert in
4673 		 * the correct fanout list.
4674 		 */
4675 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4676 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4677 		connp->conn_lport = lport;
4678 		connp->conn_fport = 0;
4679 		/*
4680 		 * Do we need to add a check to reject Multicast packets
4681 		 */
4682 		error = ipcl_bind_insert(connp, *mp->b_wptr, src_addr, lport);
4683 	}
4684 
4685 	if (error == 0) {
4686 		if (ire_requested) {
4687 			if (!ip_bind_insert_ire(mp, src_ire, NULL, ipst)) {
4688 				error = -1;
4689 				/* Falls through to bad_addr */
4690 			}
4691 		} else if (ipsec_policy_set) {
4692 			if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4693 				error = -1;
4694 				/* Falls through to bad_addr */
4695 			}
4696 		}
4697 	}
4698 bad_addr:
4699 	if (error != 0) {
4700 		if (connp->conn_anon_port) {
4701 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4702 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4703 			    B_FALSE);
4704 		}
4705 		connp->conn_mlp_type = mlptSingle;
4706 	}
4707 	if (src_ire != NULL)
4708 		IRE_REFRELE(src_ire);
4709 	if (ipsec_policy_set) {
4710 		ASSERT(policy_mp == mp->b_cont);
4711 		ASSERT(policy_mp != NULL);
4712 		freeb(policy_mp);
4713 		/*
4714 		 * As of now assume that nothing else accompanies
4715 		 * IPSEC_POLICY_SET.
4716 		 */
4717 		mp->b_cont = NULL;
4718 	}
4719 	return (error);
4720 }
4721 
4722 /*
4723  * Verify that both the source and destination addresses
4724  * are valid.  If verify_dst is false, then the destination address may be
4725  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4726  * destination reachability, while tunnels do not.
4727  * Note that we allow connect to broadcast and multicast
4728  * addresses when ire_requested is set. Thus the ULP
4729  * has to check for IRE_BROADCAST and multicast.
4730  *
4731  * Returns zero if ok.
4732  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4733  * (for use with TSYSERR reply).
4734  *
4735  * Note: lport and fport are in network byte order.
4736  */
4737 int
4738 ip_bind_connected(conn_t *connp, mblk_t *mp, ipaddr_t *src_addrp,
4739     uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4740     boolean_t ire_requested, boolean_t ipsec_policy_set,
4741     boolean_t fanout_insert, boolean_t verify_dst)
4742 {
4743 	ire_t		*src_ire;
4744 	ire_t		*dst_ire;
4745 	int		error = 0;
4746 	int 		protocol;
4747 	mblk_t		*policy_mp;
4748 	ire_t		*sire = NULL;
4749 	ire_t		*md_dst_ire = NULL;
4750 	ire_t		*lso_dst_ire = NULL;
4751 	ill_t		*ill = NULL;
4752 	zoneid_t	zoneid;
4753 	ipaddr_t	src_addr = *src_addrp;
4754 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4755 
4756 	src_ire = dst_ire = NULL;
4757 	protocol = *mp->b_wptr & 0xFF;
4758 
4759 	/*
4760 	 * If we never got a disconnect before, clear it now.
4761 	 */
4762 	connp->conn_fully_bound = B_FALSE;
4763 
4764 	if (ipsec_policy_set) {
4765 		policy_mp = mp->b_cont;
4766 	}
4767 
4768 	zoneid = IPCL_ZONEID(connp);
4769 
4770 	if (CLASSD(dst_addr)) {
4771 		/* Pick up an IRE_BROADCAST */
4772 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4773 		    NULL, zoneid, MBLK_GETLABEL(mp),
4774 		    (MATCH_IRE_RECURSIVE |
4775 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4776 		    MATCH_IRE_SECATTR), ipst);
4777 	} else {
4778 		/*
4779 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4780 		 * and onlink ipif is not found set ENETUNREACH error.
4781 		 */
4782 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4783 			ipif_t *ipif;
4784 
4785 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4786 			    dst_addr : connp->conn_nexthop_v4, zoneid, ipst);
4787 			if (ipif == NULL) {
4788 				error = ENETUNREACH;
4789 				goto bad_addr;
4790 			}
4791 			ipif_refrele(ipif);
4792 		}
4793 
4794 		if (connp->conn_nexthop_set) {
4795 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4796 			    0, 0, NULL, NULL, zoneid, MBLK_GETLABEL(mp),
4797 			    MATCH_IRE_SECATTR, ipst);
4798 		} else {
4799 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4800 			    &sire, zoneid, MBLK_GETLABEL(mp),
4801 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4802 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4803 			    MATCH_IRE_SECATTR), ipst);
4804 		}
4805 	}
4806 	/*
4807 	 * dst_ire can't be a broadcast when not ire_requested.
4808 	 * We also prevent ire's with src address INADDR_ANY to
4809 	 * be used, which are created temporarily for
4810 	 * sending out packets from endpoints that have
4811 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4812 	 * reachable.  If verify_dst is false, the destination needn't be
4813 	 * reachable.
4814 	 *
4815 	 * If we match on a reject or black hole, then we've got a
4816 	 * local failure.  May as well fail out the connect() attempt,
4817 	 * since it's never going to succeed.
4818 	 */
4819 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4820 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4821 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4822 		/*
4823 		 * If we're verifying destination reachability, we always want
4824 		 * to complain here.
4825 		 *
4826 		 * If we're not verifying destination reachability but the
4827 		 * destination has a route, we still want to fail on the
4828 		 * temporary address and broadcast address tests.
4829 		 */
4830 		if (verify_dst || (dst_ire != NULL)) {
4831 			if (ip_debug > 2) {
4832 				pr_addr_dbg("ip_bind_connected: bad connected "
4833 				    "dst %s\n", AF_INET, &dst_addr);
4834 			}
4835 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4836 				error = ENETUNREACH;
4837 			else
4838 				error = EHOSTUNREACH;
4839 			goto bad_addr;
4840 		}
4841 	}
4842 
4843 	/*
4844 	 * We now know that routing will allow us to reach the destination.
4845 	 * Check whether Trusted Solaris policy allows communication with this
4846 	 * host, and pretend that the destination is unreachable if not.
4847 	 *
4848 	 * This is never a problem for TCP, since that transport is known to
4849 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4850 	 * handling.  If the remote is unreachable, it will be detected at that
4851 	 * point, so there's no reason to check it here.
4852 	 *
4853 	 * Note that for sendto (and other datagram-oriented friends), this
4854 	 * check is done as part of the data path label computation instead.
4855 	 * The check here is just to make non-TCP connect() report the right
4856 	 * error.
4857 	 */
4858 	if (dst_ire != NULL && is_system_labeled() &&
4859 	    !IPCL_IS_TCP(connp) &&
4860 	    tsol_compute_label(DB_CREDDEF(mp, connp->conn_cred), dst_addr, NULL,
4861 	    connp->conn_mac_exempt, ipst) != 0) {
4862 		error = EHOSTUNREACH;
4863 		if (ip_debug > 2) {
4864 			pr_addr_dbg("ip_bind_connected: no label for dst %s\n",
4865 			    AF_INET, &dst_addr);
4866 		}
4867 		goto bad_addr;
4868 	}
4869 
4870 	/*
4871 	 * If the app does a connect(), it means that it will most likely
4872 	 * send more than 1 packet to the destination.  It makes sense
4873 	 * to clear the temporary flag.
4874 	 */
4875 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4876 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4877 		irb_t *irb = dst_ire->ire_bucket;
4878 
4879 		rw_enter(&irb->irb_lock, RW_WRITER);
4880 		/*
4881 		 * We need to recheck for IRE_MARK_TEMPORARY after acquiring
4882 		 * the lock to guarantee irb_tmp_ire_cnt.
4883 		 */
4884 		if (dst_ire->ire_marks & IRE_MARK_TEMPORARY) {
4885 			dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4886 			irb->irb_tmp_ire_cnt--;
4887 		}
4888 		rw_exit(&irb->irb_lock);
4889 	}
4890 
4891 	/*
4892 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4893 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4894 	 * eligibility tests for passive connects are handled separately
4895 	 * through tcp_adapt_ire().  We do this before the source address
4896 	 * selection, because dst_ire may change after a call to
4897 	 * ipif_select_source().  This is a best-effort check, as the
4898 	 * packet for this connection may not actually go through
4899 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4900 	 * calling ip_newroute().  This is why we further check on the
4901 	 * IRE during LSO/Multidata packet transmission in
4902 	 * tcp_lsosend()/tcp_multisend().
4903 	 */
4904 	if (!ipsec_policy_set && dst_ire != NULL &&
4905 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4906 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4907 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4908 			lso_dst_ire = dst_ire;
4909 			IRE_REFHOLD(lso_dst_ire);
4910 		} else if (ipst->ips_ip_multidata_outbound &&
4911 		    ILL_MDT_CAPABLE(ill)) {
4912 			md_dst_ire = dst_ire;
4913 			IRE_REFHOLD(md_dst_ire);
4914 		}
4915 	}
4916 
4917 	if (dst_ire != NULL &&
4918 	    dst_ire->ire_type == IRE_LOCAL &&
4919 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4920 		/*
4921 		 * If the IRE belongs to a different zone, look for a matching
4922 		 * route in the forwarding table and use the source address from
4923 		 * that route.
4924 		 */
4925 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4926 		    zoneid, 0, NULL,
4927 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4928 		    MATCH_IRE_RJ_BHOLE, ipst);
4929 		if (src_ire == NULL) {
4930 			error = EHOSTUNREACH;
4931 			goto bad_addr;
4932 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4933 			if (!(src_ire->ire_type & IRE_HOST))
4934 				error = ENETUNREACH;
4935 			else
4936 				error = EHOSTUNREACH;
4937 			goto bad_addr;
4938 		}
4939 		if (src_addr == INADDR_ANY)
4940 			src_addr = src_ire->ire_src_addr;
4941 		ire_refrele(src_ire);
4942 		src_ire = NULL;
4943 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4944 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4945 			src_addr = sire->ire_src_addr;
4946 			ire_refrele(dst_ire);
4947 			dst_ire = sire;
4948 			sire = NULL;
4949 		} else {
4950 			/*
4951 			 * Pick a source address so that a proper inbound
4952 			 * load spreading would happen.
4953 			 */
4954 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4955 			ipif_t *src_ipif = NULL;
4956 			ire_t *ipif_ire;
4957 
4958 			/*
4959 			 * Supply a local source address such that inbound
4960 			 * load spreading happens.
4961 			 *
4962 			 * Determine the best source address on this ill for
4963 			 * the destination.
4964 			 *
4965 			 * 1) For broadcast, we should return a broadcast ire
4966 			 *    found above so that upper layers know that the
4967 			 *    destination address is a broadcast address.
4968 			 *
4969 			 * 2) If this is part of a group, select a better
4970 			 *    source address so that better inbound load
4971 			 *    balancing happens. Do the same if the ipif
4972 			 *    is DEPRECATED.
4973 			 *
4974 			 * 3) If the outgoing interface is part of a usesrc
4975 			 *    group, then try selecting a source address from
4976 			 *    the usesrc ILL.
4977 			 */
4978 			if ((dst_ire->ire_zoneid != zoneid &&
4979 			    dst_ire->ire_zoneid != ALL_ZONES) ||
4980 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
4981 			    ((dst_ill->ill_group != NULL) ||
4982 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
4983 			    (dst_ill->ill_usesrc_ifindex != 0)))) {
4984 				/*
4985 				 * If the destination is reachable via a
4986 				 * given gateway, the selected source address
4987 				 * should be in the same subnet as the gateway.
4988 				 * Otherwise, the destination is not reachable.
4989 				 *
4990 				 * If there are no interfaces on the same subnet
4991 				 * as the destination, ipif_select_source gives
4992 				 * first non-deprecated interface which might be
4993 				 * on a different subnet than the gateway.
4994 				 * This is not desirable. Hence pass the dst_ire
4995 				 * source address to ipif_select_source.
4996 				 * It is sure that the destination is reachable
4997 				 * with the dst_ire source address subnet.
4998 				 * So passing dst_ire source address to
4999 				 * ipif_select_source will make sure that the
5000 				 * selected source will be on the same subnet
5001 				 * as dst_ire source address.
5002 				 */
5003 				ipaddr_t saddr =
5004 				    dst_ire->ire_ipif->ipif_src_addr;
5005 				src_ipif = ipif_select_source(dst_ill,
5006 				    saddr, zoneid);
5007 				if (src_ipif != NULL) {
5008 					if (IS_VNI(src_ipif->ipif_ill)) {
5009 						/*
5010 						 * For VNI there is no
5011 						 * interface route
5012 						 */
5013 						src_addr =
5014 						    src_ipif->ipif_src_addr;
5015 					} else {
5016 						ipif_ire =
5017 						    ipif_to_ire(src_ipif);
5018 						if (ipif_ire != NULL) {
5019 							IRE_REFRELE(dst_ire);
5020 							dst_ire = ipif_ire;
5021 						}
5022 						src_addr =
5023 						    dst_ire->ire_src_addr;
5024 					}
5025 					ipif_refrele(src_ipif);
5026 				} else {
5027 					src_addr = dst_ire->ire_src_addr;
5028 				}
5029 			} else {
5030 				src_addr = dst_ire->ire_src_addr;
5031 			}
5032 		}
5033 	}
5034 
5035 	/*
5036 	 * We do ire_route_lookup() here (and not
5037 	 * interface lookup as we assert that
5038 	 * src_addr should only come from an
5039 	 * UP interface for hard binding.
5040 	 */
5041 	ASSERT(src_ire == NULL);
5042 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5043 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
5044 	/* src_ire must be a local|loopback */
5045 	if (!IRE_IS_LOCAL(src_ire)) {
5046 		if (ip_debug > 2) {
5047 			pr_addr_dbg("ip_bind_connected: bad connected "
5048 			    "src %s\n", AF_INET, &src_addr);
5049 		}
5050 		error = EADDRNOTAVAIL;
5051 		goto bad_addr;
5052 	}
5053 
5054 	/*
5055 	 * If the source address is a loopback address, the
5056 	 * destination had best be local or multicast.
5057 	 * The transports that can't handle multicast will reject
5058 	 * those addresses.
5059 	 */
5060 	if (src_ire->ire_type == IRE_LOOPBACK &&
5061 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5062 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
5063 		error = -1;
5064 		goto bad_addr;
5065 	}
5066 
5067 	/*
5068 	 * Allow setting new policies. For example, disconnects come
5069 	 * down as ipa_t bind. As we would have set conn_policy_cached
5070 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5071 	 * can change after the disconnect.
5072 	 */
5073 	connp->conn_policy_cached = B_FALSE;
5074 
5075 	/*
5076 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5077 	 * can handle their passed-in conn's.
5078 	 */
5079 
5080 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5081 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5082 	connp->conn_lport = lport;
5083 	connp->conn_fport = fport;
5084 	*src_addrp = src_addr;
5085 
5086 	ASSERT(!(ipsec_policy_set && ire_requested));
5087 	if (ire_requested) {
5088 		iulp_t *ulp_info = NULL;
5089 
5090 		/*
5091 		 * Note that sire will not be NULL if this is an off-link
5092 		 * connection and there is not cache for that dest yet.
5093 		 *
5094 		 * XXX Because of an existing bug, if there are multiple
5095 		 * default routes, the IRE returned now may not be the actual
5096 		 * default route used (default routes are chosen in a
5097 		 * round robin fashion).  So if the metrics for different
5098 		 * default routes are different, we may return the wrong
5099 		 * metrics.  This will not be a problem if the existing
5100 		 * bug is fixed.
5101 		 */
5102 		if (sire != NULL) {
5103 			ulp_info = &(sire->ire_uinfo);
5104 		}
5105 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info, ipst)) {
5106 			error = -1;
5107 			goto bad_addr;
5108 		}
5109 	} else if (ipsec_policy_set) {
5110 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
5111 			error = -1;
5112 			goto bad_addr;
5113 		}
5114 	}
5115 
5116 	/*
5117 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5118 	 * we'll cache that.  If we don't, we'll inherit global policy.
5119 	 *
5120 	 * We can't insert until the conn reflects the policy. Note that
5121 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5122 	 * connections where we don't have a policy. This is to prevent
5123 	 * global policy lookups in the inbound path.
5124 	 *
5125 	 * If we insert before we set conn_policy_cached,
5126 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5127 	 * because global policy cound be non-empty. We normally call
5128 	 * ipsec_check_policy() for conn_policy_cached connections only if
5129 	 * ipc_in_enforce_policy is set. But in this case,
5130 	 * conn_policy_cached can get set anytime since we made the
5131 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5132 	 * called, which will make the above assumption false.  Thus, we
5133 	 * need to insert after we set conn_policy_cached.
5134 	 */
5135 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5136 		goto bad_addr;
5137 
5138 	if (fanout_insert) {
5139 		/*
5140 		 * The addresses have been verified. Time to insert in
5141 		 * the correct fanout list.
5142 		 */
5143 		error = ipcl_conn_insert(connp, protocol, src_addr,
5144 		    dst_addr, connp->conn_ports);
5145 	}
5146 
5147 	if (error == 0) {
5148 		connp->conn_fully_bound = B_TRUE;
5149 		/*
5150 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5151 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5152 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5153 		 * ip_xxinfo_return(), which performs further checks
5154 		 * against them and upon success, returns the LSO/MDT info
5155 		 * mblk which we will attach to the bind acknowledgment.
5156 		 */
5157 		if (lso_dst_ire != NULL) {
5158 			mblk_t *lsoinfo_mp;
5159 
5160 			ASSERT(ill->ill_lso_capab != NULL);
5161 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5162 			    ill->ill_name, ill->ill_lso_capab)) != NULL)
5163 				linkb(mp, lsoinfo_mp);
5164 		} else if (md_dst_ire != NULL) {
5165 			mblk_t *mdinfo_mp;
5166 
5167 			ASSERT(ill->ill_mdt_capab != NULL);
5168 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5169 			    ill->ill_name, ill->ill_mdt_capab)) != NULL)
5170 				linkb(mp, mdinfo_mp);
5171 		}
5172 	}
5173 bad_addr:
5174 	if (ipsec_policy_set) {
5175 		ASSERT(policy_mp == mp->b_cont);
5176 		ASSERT(policy_mp != NULL);
5177 		freeb(policy_mp);
5178 		/*
5179 		 * As of now assume that nothing else accompanies
5180 		 * IPSEC_POLICY_SET.
5181 		 */
5182 		mp->b_cont = NULL;
5183 	}
5184 	if (src_ire != NULL)
5185 		IRE_REFRELE(src_ire);
5186 	if (dst_ire != NULL)
5187 		IRE_REFRELE(dst_ire);
5188 	if (sire != NULL)
5189 		IRE_REFRELE(sire);
5190 	if (md_dst_ire != NULL)
5191 		IRE_REFRELE(md_dst_ire);
5192 	if (lso_dst_ire != NULL)
5193 		IRE_REFRELE(lso_dst_ire);
5194 	return (error);
5195 }
5196 
5197 /*
5198  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
5199  * Prefers dst_ire over src_ire.
5200  */
5201 static boolean_t
5202 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info, ip_stack_t *ipst)
5203 {
5204 	mblk_t	*mp1;
5205 	ire_t *ret_ire = NULL;
5206 
5207 	mp1 = mp->b_cont;
5208 	ASSERT(mp1 != NULL);
5209 
5210 	if (ire != NULL) {
5211 		/*
5212 		 * mp1 initialized above to IRE_DB_REQ_TYPE
5213 		 * appended mblk. Its <upper protocol>'s
5214 		 * job to make sure there is room.
5215 		 */
5216 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
5217 			return (0);
5218 
5219 		mp1->b_datap->db_type = IRE_DB_TYPE;
5220 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
5221 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
5222 		ret_ire = (ire_t *)mp1->b_rptr;
5223 		/*
5224 		 * Pass the latest setting of the ip_path_mtu_discovery and
5225 		 * copy the ulp info if any.
5226 		 */
5227 		ret_ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ?
5228 		    IPH_DF : 0;
5229 		if (ulp_info != NULL) {
5230 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5231 			    sizeof (iulp_t));
5232 		}
5233 		ret_ire->ire_mp = mp1;
5234 	} else {
5235 		/*
5236 		 * No IRE was found. Remove IRE mblk.
5237 		 */
5238 		mp->b_cont = mp1->b_cont;
5239 		freeb(mp1);
5240 	}
5241 
5242 	return (1);
5243 }
5244 
5245 /*
5246  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5247  * the final piece where we don't.  Return a pointer to the first mblk in the
5248  * result, and update the pointer to the next mblk to chew on.  If anything
5249  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5250  * NULL pointer.
5251  */
5252 mblk_t *
5253 ip_carve_mp(mblk_t **mpp, ssize_t len)
5254 {
5255 	mblk_t	*mp0;
5256 	mblk_t	*mp1;
5257 	mblk_t	*mp2;
5258 
5259 	if (!len || !mpp || !(mp0 = *mpp))
5260 		return (NULL);
5261 	/* If we aren't going to consume the first mblk, we need a dup. */
5262 	if (mp0->b_wptr - mp0->b_rptr > len) {
5263 		mp1 = dupb(mp0);
5264 		if (mp1) {
5265 			/* Partition the data between the two mblks. */
5266 			mp1->b_wptr = mp1->b_rptr + len;
5267 			mp0->b_rptr = mp1->b_wptr;
5268 			/*
5269 			 * after adjustments if mblk not consumed is now
5270 			 * unaligned, try to align it. If this fails free
5271 			 * all messages and let upper layer recover.
5272 			 */
5273 			if (!OK_32PTR(mp0->b_rptr)) {
5274 				if (!pullupmsg(mp0, -1)) {
5275 					freemsg(mp0);
5276 					freemsg(mp1);
5277 					*mpp = NULL;
5278 					return (NULL);
5279 				}
5280 			}
5281 		}
5282 		return (mp1);
5283 	}
5284 	/* Eat through as many mblks as we need to get len bytes. */
5285 	len -= mp0->b_wptr - mp0->b_rptr;
5286 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5287 		if (mp2->b_wptr - mp2->b_rptr > len) {
5288 			/*
5289 			 * We won't consume the entire last mblk.  Like
5290 			 * above, dup and partition it.
5291 			 */
5292 			mp1->b_cont = dupb(mp2);
5293 			mp1 = mp1->b_cont;
5294 			if (!mp1) {
5295 				/*
5296 				 * Trouble.  Rather than go to a lot of
5297 				 * trouble to clean up, we free the messages.
5298 				 * This won't be any worse than losing it on
5299 				 * the wire.
5300 				 */
5301 				freemsg(mp0);
5302 				freemsg(mp2);
5303 				*mpp = NULL;
5304 				return (NULL);
5305 			}
5306 			mp1->b_wptr = mp1->b_rptr + len;
5307 			mp2->b_rptr = mp1->b_wptr;
5308 			/*
5309 			 * after adjustments if mblk not consumed is now
5310 			 * unaligned, try to align it. If this fails free
5311 			 * all messages and let upper layer recover.
5312 			 */
5313 			if (!OK_32PTR(mp2->b_rptr)) {
5314 				if (!pullupmsg(mp2, -1)) {
5315 					freemsg(mp0);
5316 					freemsg(mp2);
5317 					*mpp = NULL;
5318 					return (NULL);
5319 				}
5320 			}
5321 			*mpp = mp2;
5322 			return (mp0);
5323 		}
5324 		/* Decrement len by the amount we just got. */
5325 		len -= mp2->b_wptr - mp2->b_rptr;
5326 	}
5327 	/*
5328 	 * len should be reduced to zero now.  If not our caller has
5329 	 * screwed up.
5330 	 */
5331 	if (len) {
5332 		/* Shouldn't happen! */
5333 		freemsg(mp0);
5334 		*mpp = NULL;
5335 		return (NULL);
5336 	}
5337 	/*
5338 	 * We consumed up to exactly the end of an mblk.  Detach the part
5339 	 * we are returning from the rest of the chain.
5340 	 */
5341 	mp1->b_cont = NULL;
5342 	*mpp = mp2;
5343 	return (mp0);
5344 }
5345 
5346 /* The ill stream is being unplumbed. Called from ip_close */
5347 int
5348 ip_modclose(ill_t *ill)
5349 {
5350 	boolean_t success;
5351 	ipsq_t	*ipsq;
5352 	ipif_t	*ipif;
5353 	queue_t	*q = ill->ill_rq;
5354 	ip_stack_t	*ipst = ill->ill_ipst;
5355 	clock_t timeout;
5356 
5357 	/*
5358 	 * Wait for the ACKs of all deferred control messages to be processed.
5359 	 * In particular, we wait for a potential capability reset initiated
5360 	 * in ip_sioctl_plink() to complete before proceeding.
5361 	 *
5362 	 * Note: we wait for at most ip_modclose_ackwait_ms (by default 3000 ms)
5363 	 * in case the driver never replies.
5364 	 */
5365 	timeout = lbolt + MSEC_TO_TICK(ip_modclose_ackwait_ms);
5366 	mutex_enter(&ill->ill_lock);
5367 	while (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
5368 		if (cv_timedwait(&ill->ill_cv, &ill->ill_lock, timeout) < 0) {
5369 			/* Timeout */
5370 			break;
5371 		}
5372 	}
5373 	mutex_exit(&ill->ill_lock);
5374 
5375 	/*
5376 	 * Forcibly enter the ipsq after some delay. This is to take
5377 	 * care of the case when some ioctl does not complete because
5378 	 * we sent a control message to the driver and it did not
5379 	 * send us a reply. We want to be able to at least unplumb
5380 	 * and replumb rather than force the user to reboot the system.
5381 	 */
5382 	success = ipsq_enter(ill, B_FALSE);
5383 
5384 	/*
5385 	 * Open/close/push/pop is guaranteed to be single threaded
5386 	 * per stream by STREAMS. FS guarantees that all references
5387 	 * from top are gone before close is called. So there can't
5388 	 * be another close thread that has set CONDEMNED on this ill.
5389 	 * and cause ipsq_enter to return failure.
5390 	 */
5391 	ASSERT(success);
5392 	ipsq = ill->ill_phyint->phyint_ipsq;
5393 
5394 	/*
5395 	 * Mark it condemned. No new reference will be made to this ill.
5396 	 * Lookup functions will return an error. Threads that try to
5397 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5398 	 * that the refcnt will drop down to zero.
5399 	 */
5400 	mutex_enter(&ill->ill_lock);
5401 	ill->ill_state_flags |= ILL_CONDEMNED;
5402 	for (ipif = ill->ill_ipif; ipif != NULL;
5403 	    ipif = ipif->ipif_next) {
5404 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5405 	}
5406 	/*
5407 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5408 	 * returns  error if ILL_CONDEMNED is set
5409 	 */
5410 	cv_broadcast(&ill->ill_cv);
5411 	mutex_exit(&ill->ill_lock);
5412 
5413 	/*
5414 	 * Send all the deferred DLPI messages downstream which came in
5415 	 * during the small window right before ipsq_enter(). We do this
5416 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5417 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5418 	 */
5419 	ill_dlpi_send_deferred(ill);
5420 
5421 	/*
5422 	 * Shut down fragmentation reassembly.
5423 	 * ill_frag_timer won't start a timer again.
5424 	 * Now cancel any existing timer
5425 	 */
5426 	(void) untimeout(ill->ill_frag_timer_id);
5427 	(void) ill_frag_timeout(ill, 0);
5428 
5429 	/*
5430 	 * If MOVE was in progress, clear the
5431 	 * move_in_progress fields also.
5432 	 */
5433 	if (ill->ill_move_in_progress) {
5434 		ILL_CLEAR_MOVE(ill);
5435 	}
5436 
5437 	/*
5438 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5439 	 * this ill. Then wait for the refcnts to drop to zero.
5440 	 * ill_is_quiescent checks whether the ill is really quiescent.
5441 	 * Then make sure that threads that are waiting to enter the
5442 	 * ipsq have seen the error returned by ipsq_enter and have
5443 	 * gone away. Then we call ill_delete_tail which does the
5444 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
5445 	 */
5446 	ill_delete(ill);
5447 	mutex_enter(&ill->ill_lock);
5448 	while (!ill_is_quiescent(ill))
5449 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5450 	while (ill->ill_waiters)
5451 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5452 
5453 	mutex_exit(&ill->ill_lock);
5454 
5455 	/*
5456 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
5457 	 * it held until the end of the function since the cleanup
5458 	 * below needs to be able to use the ip_stack_t.
5459 	 */
5460 	netstack_hold(ipst->ips_netstack);
5461 
5462 	/* qprocsoff is called in ill_delete_tail */
5463 	ill_delete_tail(ill);
5464 	ASSERT(ill->ill_ipst == NULL);
5465 
5466 	/*
5467 	 * Walk through all upper (conn) streams and qenable
5468 	 * those that have queued data.
5469 	 * close synchronization needs this to
5470 	 * be done to ensure that all upper layers blocked
5471 	 * due to flow control to the closing device
5472 	 * get unblocked.
5473 	 */
5474 	ip1dbg(("ip_wsrv: walking\n"));
5475 	conn_walk_drain(ipst);
5476 
5477 	mutex_enter(&ipst->ips_ip_mi_lock);
5478 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
5479 	mutex_exit(&ipst->ips_ip_mi_lock);
5480 
5481 	/*
5482 	 * credp could be null if the open didn't succeed and ip_modopen
5483 	 * itself calls ip_close.
5484 	 */
5485 	if (ill->ill_credp != NULL)
5486 		crfree(ill->ill_credp);
5487 
5488 	mutex_enter(&ill->ill_lock);
5489 	ill_nic_info_dispatch(ill);
5490 	mutex_exit(&ill->ill_lock);
5491 
5492 	/*
5493 	 * Now we are done with the module close pieces that
5494 	 * need the netstack_t.
5495 	 */
5496 	netstack_rele(ipst->ips_netstack);
5497 
5498 	mi_close_free((IDP)ill);
5499 	q->q_ptr = WR(q)->q_ptr = NULL;
5500 
5501 	ipsq_exit(ipsq, B_TRUE, B_TRUE);
5502 
5503 	return (0);
5504 }
5505 
5506 /*
5507  * This is called as part of close() for IP, UDP, ICMP, and RTS
5508  * in order to quiesce the conn.
5509  */
5510 void
5511 ip_quiesce_conn(conn_t *connp)
5512 {
5513 	boolean_t	drain_cleanup_reqd = B_FALSE;
5514 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5515 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5516 	ip_stack_t	*ipst;
5517 
5518 	ASSERT(!IPCL_IS_TCP(connp));
5519 	ipst = connp->conn_netstack->netstack_ip;
5520 
5521 	/*
5522 	 * Mark the conn as closing, and this conn must not be
5523 	 * inserted in future into any list. Eg. conn_drain_insert(),
5524 	 * won't insert this conn into the conn_drain_list.
5525 	 * Similarly ill_pending_mp_add() will not add any mp to
5526 	 * the pending mp list, after this conn has started closing.
5527 	 *
5528 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5529 	 * cannot get set henceforth.
5530 	 */
5531 	mutex_enter(&connp->conn_lock);
5532 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5533 	connp->conn_state_flags |= CONN_CLOSING;
5534 	if (connp->conn_idl != NULL)
5535 		drain_cleanup_reqd = B_TRUE;
5536 	if (connp->conn_oper_pending_ill != NULL)
5537 		conn_ioctl_cleanup_reqd = B_TRUE;
5538 	if (connp->conn_dhcpinit_ill != NULL) {
5539 		ASSERT(connp->conn_dhcpinit_ill->ill_dhcpinit != 0);
5540 		atomic_dec_32(&connp->conn_dhcpinit_ill->ill_dhcpinit);
5541 		connp->conn_dhcpinit_ill = NULL;
5542 	}
5543 	if (connp->conn_ilg_inuse != 0)
5544 		ilg_cleanup_reqd = B_TRUE;
5545 	mutex_exit(&connp->conn_lock);
5546 
5547 	if (conn_ioctl_cleanup_reqd)
5548 		conn_ioctl_cleanup(connp);
5549 
5550 	if (is_system_labeled() && connp->conn_anon_port) {
5551 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5552 		    connp->conn_mlp_type, connp->conn_ulp,
5553 		    ntohs(connp->conn_lport), B_FALSE);
5554 		connp->conn_anon_port = 0;
5555 	}
5556 	connp->conn_mlp_type = mlptSingle;
5557 
5558 	/*
5559 	 * Remove this conn from any fanout list it is on.
5560 	 * and then wait for any threads currently operating
5561 	 * on this endpoint to finish
5562 	 */
5563 	ipcl_hash_remove(connp);
5564 
5565 	/*
5566 	 * Remove this conn from the drain list, and do
5567 	 * any other cleanup that may be required.
5568 	 * (Only non-tcp streams may have a non-null conn_idl.
5569 	 * TCP streams are never flow controlled, and
5570 	 * conn_idl will be null)
5571 	 */
5572 	if (drain_cleanup_reqd)
5573 		conn_drain_tail(connp, B_TRUE);
5574 
5575 	if (connp == ipst->ips_ip_g_mrouter)
5576 		(void) ip_mrouter_done(NULL, ipst);
5577 
5578 	if (ilg_cleanup_reqd)
5579 		ilg_delete_all(connp);
5580 
5581 	conn_delete_ire(connp, NULL);
5582 
5583 	/*
5584 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5585 	 * callers from write side can't be there now because close
5586 	 * is in progress. The only other caller is ipcl_walk
5587 	 * which checks for the condemned flag.
5588 	 */
5589 	mutex_enter(&connp->conn_lock);
5590 	connp->conn_state_flags |= CONN_CONDEMNED;
5591 	while (connp->conn_ref != 1)
5592 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5593 	connp->conn_state_flags |= CONN_QUIESCED;
5594 	mutex_exit(&connp->conn_lock);
5595 }
5596 
5597 /* ARGSUSED */
5598 int
5599 ip_close(queue_t *q, int flags)
5600 {
5601 	conn_t		*connp;
5602 
5603 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5604 
5605 	/*
5606 	 * Call the appropriate delete routine depending on whether this is
5607 	 * a module or device.
5608 	 */
5609 	if (WR(q)->q_next != NULL) {
5610 		/* This is a module close */
5611 		return (ip_modclose((ill_t *)q->q_ptr));
5612 	}
5613 
5614 	connp = q->q_ptr;
5615 	ip_quiesce_conn(connp);
5616 
5617 	qprocsoff(q);
5618 
5619 	/*
5620 	 * Now we are truly single threaded on this stream, and can
5621 	 * delete the things hanging off the connp, and finally the connp.
5622 	 * We removed this connp from the fanout list, it cannot be
5623 	 * accessed thru the fanouts, and we already waited for the
5624 	 * conn_ref to drop to 0. We are already in close, so
5625 	 * there cannot be any other thread from the top. qprocsoff
5626 	 * has completed, and service has completed or won't run in
5627 	 * future.
5628 	 */
5629 	ASSERT(connp->conn_ref == 1);
5630 
5631 	inet_minor_free(ip_minor_arena, connp->conn_dev);
5632 
5633 	connp->conn_ref--;
5634 	ipcl_conn_destroy(connp);
5635 
5636 	q->q_ptr = WR(q)->q_ptr = NULL;
5637 	return (0);
5638 }
5639 
5640 /*
5641  * Wapper around putnext() so that ip_rts_request can merely use
5642  * conn_recv.
5643  */
5644 /*ARGSUSED2*/
5645 static void
5646 ip_conn_input(void *arg1, mblk_t *mp, void *arg2)
5647 {
5648 	conn_t *connp = (conn_t *)arg1;
5649 
5650 	putnext(connp->conn_rq, mp);
5651 }
5652 
5653 /* Return the IP checksum for the IP header at "iph". */
5654 uint16_t
5655 ip_csum_hdr(ipha_t *ipha)
5656 {
5657 	uint16_t	*uph;
5658 	uint32_t	sum;
5659 	int		opt_len;
5660 
5661 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
5662 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
5663 	uph = (uint16_t *)ipha;
5664 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
5665 	    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
5666 	if (opt_len > 0) {
5667 		do {
5668 			sum += uph[10];
5669 			sum += uph[11];
5670 			uph += 2;
5671 		} while (--opt_len);
5672 	}
5673 	sum = (sum & 0xFFFF) + (sum >> 16);
5674 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
5675 	if (sum == 0xffff)
5676 		sum = 0;
5677 	return ((uint16_t)sum);
5678 }
5679 
5680 /*
5681  * Called when the module is about to be unloaded
5682  */
5683 void
5684 ip_ddi_destroy(void)
5685 {
5686 	tnet_fini();
5687 
5688 	icmp_ddi_destroy();
5689 	rts_ddi_destroy();
5690 	udp_ddi_destroy();
5691 	sctp_ddi_g_destroy();
5692 	tcp_ddi_g_destroy();
5693 	ipsec_policy_g_destroy();
5694 	ipcl_g_destroy();
5695 	ip_net_g_destroy();
5696 	ip_ire_g_fini();
5697 	inet_minor_destroy(ip_minor_arena);
5698 
5699 #ifdef DEBUG
5700 	list_destroy(&ip_thread_list);
5701 	rw_destroy(&ip_thread_rwlock);
5702 	tsd_destroy(&ip_thread_data);
5703 #endif
5704 
5705 	netstack_unregister(NS_IP);
5706 }
5707 
5708 /*
5709  * First step in cleanup.
5710  */
5711 /* ARGSUSED */
5712 static void
5713 ip_stack_shutdown(netstackid_t stackid, void *arg)
5714 {
5715 	ip_stack_t *ipst = (ip_stack_t *)arg;
5716 
5717 #ifdef NS_DEBUG
5718 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
5719 #endif
5720 
5721 	/* Get rid of loopback interfaces and their IREs */
5722 	ip_loopback_cleanup(ipst);
5723 }
5724 
5725 /*
5726  * Free the IP stack instance.
5727  */
5728 static void
5729 ip_stack_fini(netstackid_t stackid, void *arg)
5730 {
5731 	ip_stack_t *ipst = (ip_stack_t *)arg;
5732 	int ret;
5733 
5734 #ifdef NS_DEBUG
5735 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5736 #endif
5737 	ipv4_hook_destroy(ipst);
5738 	ipv6_hook_destroy(ipst);
5739 	ip_net_destroy(ipst);
5740 
5741 	rw_destroy(&ipst->ips_srcid_lock);
5742 
5743 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5744 	ipst->ips_ip_mibkp = NULL;
5745 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5746 	ipst->ips_icmp_mibkp = NULL;
5747 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5748 	ipst->ips_ip_kstat = NULL;
5749 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5750 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5751 	ipst->ips_ip6_kstat = NULL;
5752 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5753 
5754 	nd_free(&ipst->ips_ip_g_nd);
5755 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5756 	ipst->ips_param_arr = NULL;
5757 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5758 	ipst->ips_ndp_arr = NULL;
5759 
5760 	ip_mrouter_stack_destroy(ipst);
5761 
5762 	mutex_destroy(&ipst->ips_ip_mi_lock);
5763 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5764 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5765 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5766 
5767 	ret = untimeout(ipst->ips_igmp_timeout_id);
5768 	if (ret == -1) {
5769 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5770 	} else {
5771 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5772 		ipst->ips_igmp_timeout_id = 0;
5773 	}
5774 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5775 	if (ret == -1) {
5776 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5777 	} else {
5778 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5779 		ipst->ips_igmp_slowtimeout_id = 0;
5780 	}
5781 	ret = untimeout(ipst->ips_mld_timeout_id);
5782 	if (ret == -1) {
5783 		ASSERT(ipst->ips_mld_timeout_id == 0);
5784 	} else {
5785 		ASSERT(ipst->ips_mld_timeout_id != 0);
5786 		ipst->ips_mld_timeout_id = 0;
5787 	}
5788 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5789 	if (ret == -1) {
5790 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5791 	} else {
5792 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5793 		ipst->ips_mld_slowtimeout_id = 0;
5794 	}
5795 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5796 	if (ret == -1) {
5797 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5798 	} else {
5799 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5800 		ipst->ips_ip_ire_expire_id = 0;
5801 	}
5802 
5803 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5804 	mutex_destroy(&ipst->ips_mld_timer_lock);
5805 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5806 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5807 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5808 	rw_destroy(&ipst->ips_ill_g_lock);
5809 
5810 	ip_ire_fini(ipst);
5811 	ip6_asp_free(ipst);
5812 	conn_drain_fini(ipst);
5813 	ipcl_destroy(ipst);
5814 
5815 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5816 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5817 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5818 	ipst->ips_ndp4 = NULL;
5819 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5820 	ipst->ips_ndp6 = NULL;
5821 
5822 	if (ipst->ips_loopback_ksp != NULL) {
5823 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5824 		ipst->ips_loopback_ksp = NULL;
5825 	}
5826 
5827 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5828 	ipst->ips_phyint_g_list = NULL;
5829 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5830 	ipst->ips_ill_g_heads = NULL;
5831 
5832 	kmem_free(ipst, sizeof (*ipst));
5833 }
5834 
5835 /*
5836  * This function is called from the TSD destructor, and is used to debug
5837  * reference count issues in IP. See block comment in <inet/ip_if.h> for
5838  * details.
5839  */
5840 static void
5841 ip_thread_exit(void *phash)
5842 {
5843 	th_hash_t *thh = phash;
5844 
5845 	rw_enter(&ip_thread_rwlock, RW_WRITER);
5846 	list_remove(&ip_thread_list, thh);
5847 	rw_exit(&ip_thread_rwlock);
5848 	mod_hash_destroy_hash(thh->thh_hash);
5849 	kmem_free(thh, sizeof (*thh));
5850 }
5851 
5852 /*
5853  * Called when the IP kernel module is loaded into the kernel
5854  */
5855 void
5856 ip_ddi_init(void)
5857 {
5858 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
5859 
5860 	/*
5861 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5862 	 * initial devices: ip, ip6, tcp, tcp6.
5863 	 */
5864 	if ((ip_minor_arena = inet_minor_create("ip_minor_arena",
5865 	    INET_MIN_DEV + 2, KM_SLEEP)) == NULL) {
5866 		cmn_err(CE_PANIC,
5867 		    "ip_ddi_init: ip_minor_arena creation failed\n");
5868 	}
5869 
5870 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5871 
5872 	ipcl_g_init();
5873 	ip_ire_g_init();
5874 	ip_net_g_init();
5875 
5876 #ifdef DEBUG
5877 	tsd_create(&ip_thread_data, ip_thread_exit);
5878 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
5879 	list_create(&ip_thread_list, sizeof (th_hash_t),
5880 	    offsetof(th_hash_t, thh_link));
5881 #endif
5882 
5883 	/*
5884 	 * We want to be informed each time a stack is created or
5885 	 * destroyed in the kernel, so we can maintain the
5886 	 * set of udp_stack_t's.
5887 	 */
5888 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
5889 	    ip_stack_fini);
5890 
5891 	ipsec_policy_g_init();
5892 	tcp_ddi_g_init();
5893 	sctp_ddi_g_init();
5894 
5895 	tnet_init();
5896 
5897 	udp_ddi_init();
5898 	rts_ddi_init();
5899 	icmp_ddi_init();
5900 }
5901 
5902 /*
5903  * Initialize the IP stack instance.
5904  */
5905 static void *
5906 ip_stack_init(netstackid_t stackid, netstack_t *ns)
5907 {
5908 	ip_stack_t	*ipst;
5909 	ipparam_t	*pa;
5910 	ipndp_t		*na;
5911 
5912 #ifdef NS_DEBUG
5913 	printf("ip_stack_init(stack %d)\n", stackid);
5914 #endif
5915 
5916 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
5917 	ipst->ips_netstack = ns;
5918 
5919 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
5920 	    KM_SLEEP);
5921 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
5922 	    KM_SLEEP);
5923 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5924 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5925 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5926 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5927 
5928 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5929 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5930 	ipst->ips_igmp_deferred_next = INFINITY;
5931 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5932 	ipst->ips_mld_deferred_next = INFINITY;
5933 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5934 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5935 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
5936 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
5937 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
5938 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
5939 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
5940 
5941 	ipcl_init(ipst);
5942 	ip_ire_init(ipst);
5943 	ip6_asp_init(ipst);
5944 	ipif_init(ipst);
5945 	conn_drain_init(ipst);
5946 	ip_mrouter_stack_init(ipst);
5947 
5948 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
5949 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
5950 
5951 	ipst->ips_ip_multirt_log_interval = 1000;
5952 
5953 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
5954 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
5955 	ipst->ips_ill_index = 1;
5956 
5957 	ipst->ips_saved_ip_g_forward = -1;
5958 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
5959 
5960 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
5961 	ipst->ips_param_arr = pa;
5962 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
5963 
5964 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
5965 	ipst->ips_ndp_arr = na;
5966 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5967 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
5968 	    (caddr_t)&ipst->ips_ip_g_forward;
5969 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
5970 	    (caddr_t)&ipst->ips_ipv6_forward;
5971 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
5972 	    "ip_cgtp_filter") == 0);
5973 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
5974 	    (caddr_t)&ipst->ips_ip_cgtp_filter;
5975 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_name,
5976 	    "ipmp_hook_emulation") == 0);
5977 	ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_data =
5978 	    (caddr_t)&ipst->ips_ipmp_hook_emulation;
5979 
5980 	(void) ip_param_register(&ipst->ips_ip_g_nd,
5981 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
5982 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
5983 
5984 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
5985 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
5986 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
5987 	ipst->ips_ip6_kstat =
5988 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
5989 
5990 	ipst->ips_ipmp_enable_failback = B_TRUE;
5991 
5992 	ipst->ips_ip_src_id = 1;
5993 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
5994 
5995 	ip_net_init(ipst, ns);
5996 	ipv4_hook_init(ipst);
5997 	ipv6_hook_init(ipst);
5998 
5999 	return (ipst);
6000 }
6001 
6002 /*
6003  * Allocate and initialize a DLPI template of the specified length.  (May be
6004  * called as writer.)
6005  */
6006 mblk_t *
6007 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
6008 {
6009 	mblk_t	*mp;
6010 
6011 	mp = allocb(len, BPRI_MED);
6012 	if (!mp)
6013 		return (NULL);
6014 
6015 	/*
6016 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
6017 	 * of which we don't seem to use) are sent with M_PCPROTO, and
6018 	 * that other DLPI are M_PROTO.
6019 	 */
6020 	if (prim == DL_INFO_REQ) {
6021 		mp->b_datap->db_type = M_PCPROTO;
6022 	} else {
6023 		mp->b_datap->db_type = M_PROTO;
6024 	}
6025 
6026 	mp->b_wptr = mp->b_rptr + len;
6027 	bzero(mp->b_rptr, len);
6028 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6029 	return (mp);
6030 }
6031 
6032 const char *
6033 dlpi_prim_str(int prim)
6034 {
6035 	switch (prim) {
6036 	case DL_INFO_REQ:	return ("DL_INFO_REQ");
6037 	case DL_INFO_ACK:	return ("DL_INFO_ACK");
6038 	case DL_ATTACH_REQ:	return ("DL_ATTACH_REQ");
6039 	case DL_DETACH_REQ:	return ("DL_DETACH_REQ");
6040 	case DL_BIND_REQ:	return ("DL_BIND_REQ");
6041 	case DL_BIND_ACK:	return ("DL_BIND_ACK");
6042 	case DL_UNBIND_REQ:	return ("DL_UNBIND_REQ");
6043 	case DL_OK_ACK:		return ("DL_OK_ACK");
6044 	case DL_ERROR_ACK:	return ("DL_ERROR_ACK");
6045 	case DL_ENABMULTI_REQ:	return ("DL_ENABMULTI_REQ");
6046 	case DL_DISABMULTI_REQ:	return ("DL_DISABMULTI_REQ");
6047 	case DL_PROMISCON_REQ:	return ("DL_PROMISCON_REQ");
6048 	case DL_PROMISCOFF_REQ:	return ("DL_PROMISCOFF_REQ");
6049 	case DL_UNITDATA_REQ:	return ("DL_UNITDATA_REQ");
6050 	case DL_UNITDATA_IND:	return ("DL_UNITDATA_IND");
6051 	case DL_UDERROR_IND:	return ("DL_UDERROR_IND");
6052 	case DL_PHYS_ADDR_REQ:	return ("DL_PHYS_ADDR_REQ");
6053 	case DL_PHYS_ADDR_ACK:	return ("DL_PHYS_ADDR_ACK");
6054 	case DL_SET_PHYS_ADDR_REQ:	return ("DL_SET_PHYS_ADDR_REQ");
6055 	case DL_NOTIFY_REQ:	return ("DL_NOTIFY_REQ");
6056 	case DL_NOTIFY_ACK:	return ("DL_NOTIFY_ACK");
6057 	case DL_NOTIFY_IND:	return ("DL_NOTIFY_IND");
6058 	case DL_CAPABILITY_REQ:	return ("DL_CAPABILITY_REQ");
6059 	case DL_CAPABILITY_ACK:	return ("DL_CAPABILITY_ACK");
6060 	case DL_CONTROL_REQ:	return ("DL_CONTROL_REQ");
6061 	case DL_CONTROL_ACK:	return ("DL_CONTROL_ACK");
6062 	default:		return ("<unknown primitive>");
6063 	}
6064 }
6065 
6066 const char *
6067 dlpi_err_str(int err)
6068 {
6069 	switch (err) {
6070 	case DL_ACCESS:		return ("DL_ACCESS");
6071 	case DL_BADADDR:	return ("DL_BADADDR");
6072 	case DL_BADCORR:	return ("DL_BADCORR");
6073 	case DL_BADDATA:	return ("DL_BADDATA");
6074 	case DL_BADPPA:		return ("DL_BADPPA");
6075 	case DL_BADPRIM:	return ("DL_BADPRIM");
6076 	case DL_BADQOSPARAM:	return ("DL_BADQOSPARAM");
6077 	case DL_BADQOSTYPE:	return ("DL_BADQOSTYPE");
6078 	case DL_BADSAP:		return ("DL_BADSAP");
6079 	case DL_BADTOKEN:	return ("DL_BADTOKEN");
6080 	case DL_BOUND:		return ("DL_BOUND");
6081 	case DL_INITFAILED:	return ("DL_INITFAILED");
6082 	case DL_NOADDR:		return ("DL_NOADDR");
6083 	case DL_NOTINIT:	return ("DL_NOTINIT");
6084 	case DL_OUTSTATE:	return ("DL_OUTSTATE");
6085 	case DL_SYSERR:		return ("DL_SYSERR");
6086 	case DL_UNSUPPORTED:	return ("DL_UNSUPPORTED");
6087 	case DL_UNDELIVERABLE:	return ("DL_UNDELIVERABLE");
6088 	case DL_NOTSUPPORTED :	return ("DL_NOTSUPPORTED ");
6089 	case DL_TOOMANY:	return ("DL_TOOMANY");
6090 	case DL_NOTENAB:	return ("DL_NOTENAB");
6091 	case DL_BUSY:		return ("DL_BUSY");
6092 	case DL_NOAUTO:		return ("DL_NOAUTO");
6093 	case DL_NOXIDAUTO:	return ("DL_NOXIDAUTO");
6094 	case DL_NOTESTAUTO:	return ("DL_NOTESTAUTO");
6095 	case DL_XIDAUTO:	return ("DL_XIDAUTO");
6096 	case DL_TESTAUTO:	return ("DL_TESTAUTO");
6097 	case DL_PENDING:	return ("DL_PENDING");
6098 	default:		return ("<unknown error>");
6099 	}
6100 }
6101 
6102 /*
6103  * Debug formatting routine.  Returns a character string representation of the
6104  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6105  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6106  *
6107  * Once the ndd table-printing interfaces are removed, this can be changed to
6108  * standard dotted-decimal form.
6109  */
6110 char *
6111 ip_dot_addr(ipaddr_t addr, char *buf)
6112 {
6113 	uint8_t *ap = (uint8_t *)&addr;
6114 
6115 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6116 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6117 	return (buf);
6118 }
6119 
6120 /*
6121  * Write the given MAC address as a printable string in the usual colon-
6122  * separated format.
6123  */
6124 const char *
6125 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6126 {
6127 	char *bp;
6128 
6129 	if (alen == 0 || buflen < 4)
6130 		return ("?");
6131 	bp = buf;
6132 	for (;;) {
6133 		/*
6134 		 * If there are more MAC address bytes available, but we won't
6135 		 * have any room to print them, then add "..." to the string
6136 		 * instead.  See below for the 'magic number' explanation.
6137 		 */
6138 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6139 			(void) strcpy(bp, "...");
6140 			break;
6141 		}
6142 		(void) sprintf(bp, "%02x", *addr++);
6143 		bp += 2;
6144 		if (--alen == 0)
6145 			break;
6146 		*bp++ = ':';
6147 		buflen -= 3;
6148 		/*
6149 		 * At this point, based on the first 'if' statement above,
6150 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6151 		 * buflen >= 4.  The first case leaves room for the final "xx"
6152 		 * number and trailing NUL byte.  The second leaves room for at
6153 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6154 		 * that statement.
6155 		 */
6156 	}
6157 	return (buf);
6158 }
6159 
6160 /*
6161  * Send an ICMP error after patching up the packet appropriately.  Returns
6162  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6163  */
6164 static boolean_t
6165 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6166     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6167     zoneid_t zoneid, ip_stack_t *ipst)
6168 {
6169 	ipha_t *ipha;
6170 	mblk_t *first_mp;
6171 	boolean_t secure;
6172 	unsigned char db_type;
6173 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6174 
6175 	first_mp = mp;
6176 	if (mctl_present) {
6177 		mp = mp->b_cont;
6178 		secure = ipsec_in_is_secure(first_mp);
6179 		ASSERT(mp != NULL);
6180 	} else {
6181 		/*
6182 		 * If this is an ICMP error being reported - which goes
6183 		 * up as M_CTLs, we need to convert them to M_DATA till
6184 		 * we finish checking with global policy because
6185 		 * ipsec_check_global_policy() assumes M_DATA as clear
6186 		 * and M_CTL as secure.
6187 		 */
6188 		db_type = DB_TYPE(mp);
6189 		DB_TYPE(mp) = M_DATA;
6190 		secure = B_FALSE;
6191 	}
6192 	/*
6193 	 * We are generating an icmp error for some inbound packet.
6194 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6195 	 * Before we generate an error, check with global policy
6196 	 * to see whether this is allowed to enter the system. As
6197 	 * there is no "conn", we are checking with global policy.
6198 	 */
6199 	ipha = (ipha_t *)mp->b_rptr;
6200 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6201 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6202 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6203 		if (first_mp == NULL)
6204 			return (B_FALSE);
6205 	}
6206 
6207 	if (!mctl_present)
6208 		DB_TYPE(mp) = db_type;
6209 
6210 	if (flags & IP_FF_SEND_ICMP) {
6211 		if (flags & IP_FF_HDR_COMPLETE) {
6212 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6213 				freemsg(first_mp);
6214 				return (B_TRUE);
6215 			}
6216 		}
6217 		if (flags & IP_FF_CKSUM) {
6218 			/*
6219 			 * Have to correct checksum since
6220 			 * the packet might have been
6221 			 * fragmented and the reassembly code in ip_rput
6222 			 * does not restore the IP checksum.
6223 			 */
6224 			ipha->ipha_hdr_checksum = 0;
6225 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6226 		}
6227 		switch (icmp_type) {
6228 		case ICMP_DEST_UNREACHABLE:
6229 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6230 			    ipst);
6231 			break;
6232 		default:
6233 			freemsg(first_mp);
6234 			break;
6235 		}
6236 	} else {
6237 		freemsg(first_mp);
6238 		return (B_FALSE);
6239 	}
6240 
6241 	return (B_TRUE);
6242 }
6243 
6244 /*
6245  * Used to send an ICMP error message when a packet is received for
6246  * a protocol that is not supported. The mblk passed as argument
6247  * is consumed by this function.
6248  */
6249 void
6250 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6251     ip_stack_t *ipst)
6252 {
6253 	mblk_t *mp;
6254 	ipha_t *ipha;
6255 	ill_t *ill;
6256 	ipsec_in_t *ii;
6257 
6258 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6259 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6260 
6261 	mp = ipsec_mp->b_cont;
6262 	ipsec_mp->b_cont = NULL;
6263 	ipha = (ipha_t *)mp->b_rptr;
6264 	/* Get ill from index in ipsec_in_t. */
6265 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6266 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6267 	    ipst);
6268 	if (ill != NULL) {
6269 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6270 			if (ip_fanout_send_icmp(q, mp, flags,
6271 			    ICMP_DEST_UNREACHABLE,
6272 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6273 				BUMP_MIB(ill->ill_ip_mib,
6274 				    ipIfStatsInUnknownProtos);
6275 			}
6276 		} else {
6277 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6278 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6279 			    0, B_FALSE, zoneid, ipst)) {
6280 				BUMP_MIB(ill->ill_ip_mib,
6281 				    ipIfStatsInUnknownProtos);
6282 			}
6283 		}
6284 		ill_refrele(ill);
6285 	} else { /* re-link for the freemsg() below. */
6286 		ipsec_mp->b_cont = mp;
6287 	}
6288 
6289 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6290 	freemsg(ipsec_mp);
6291 }
6292 
6293 /*
6294  * See if the inbound datagram has had IPsec processing applied to it.
6295  */
6296 boolean_t
6297 ipsec_in_is_secure(mblk_t *ipsec_mp)
6298 {
6299 	ipsec_in_t *ii;
6300 
6301 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6302 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6303 
6304 	if (ii->ipsec_in_loopback) {
6305 		return (ii->ipsec_in_secure);
6306 	} else {
6307 		return (ii->ipsec_in_ah_sa != NULL ||
6308 		    ii->ipsec_in_esp_sa != NULL ||
6309 		    ii->ipsec_in_decaps);
6310 	}
6311 }
6312 
6313 /*
6314  * Handle protocols with which IP is less intimate.  There
6315  * can be more than one stream bound to a particular
6316  * protocol.  When this is the case, normally each one gets a copy
6317  * of any incoming packets.
6318  *
6319  * IPsec NOTE :
6320  *
6321  * Don't allow a secure packet going up a non-secure connection.
6322  * We don't allow this because
6323  *
6324  * 1) Reply might go out in clear which will be dropped at
6325  *    the sending side.
6326  * 2) If the reply goes out in clear it will give the
6327  *    adversary enough information for getting the key in
6328  *    most of the cases.
6329  *
6330  * Moreover getting a secure packet when we expect clear
6331  * implies that SA's were added without checking for
6332  * policy on both ends. This should not happen once ISAKMP
6333  * is used to negotiate SAs as SAs will be added only after
6334  * verifying the policy.
6335  *
6336  * NOTE : If the packet was tunneled and not multicast we only send
6337  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6338  * back to delivering packets to AF_INET6 raw sockets.
6339  *
6340  * IPQoS Notes:
6341  * Once we have determined the client, invoke IPPF processing.
6342  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6343  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6344  * ip_policy will be false.
6345  *
6346  * Zones notes:
6347  * Currently only applications in the global zone can create raw sockets for
6348  * protocols other than ICMP. So unlike the broadcast / multicast case of
6349  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6350  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6351  */
6352 static void
6353 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6354     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6355     zoneid_t zoneid)
6356 {
6357 	queue_t	*rq;
6358 	mblk_t	*mp1, *first_mp1;
6359 	uint_t	protocol = ipha->ipha_protocol;
6360 	ipaddr_t dst;
6361 	boolean_t one_only;
6362 	mblk_t *first_mp = mp;
6363 	boolean_t secure;
6364 	uint32_t ill_index;
6365 	conn_t	*connp, *first_connp, *next_connp;
6366 	connf_t	*connfp;
6367 	boolean_t shared_addr;
6368 	mib2_ipIfStatsEntry_t *mibptr;
6369 	ip_stack_t *ipst = recv_ill->ill_ipst;
6370 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6371 
6372 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6373 	if (mctl_present) {
6374 		mp = first_mp->b_cont;
6375 		secure = ipsec_in_is_secure(first_mp);
6376 		ASSERT(mp != NULL);
6377 	} else {
6378 		secure = B_FALSE;
6379 	}
6380 	dst = ipha->ipha_dst;
6381 	/*
6382 	 * If the packet was tunneled and not multicast we only send to it
6383 	 * the first match.
6384 	 */
6385 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6386 	    !CLASSD(dst));
6387 
6388 	shared_addr = (zoneid == ALL_ZONES);
6389 	if (shared_addr) {
6390 		/*
6391 		 * We don't allow multilevel ports for raw IP, so no need to
6392 		 * check for that here.
6393 		 */
6394 		zoneid = tsol_packet_to_zoneid(mp);
6395 	}
6396 
6397 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6398 	mutex_enter(&connfp->connf_lock);
6399 	connp = connfp->connf_head;
6400 	for (connp = connfp->connf_head; connp != NULL;
6401 	    connp = connp->conn_next) {
6402 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6403 		    zoneid) &&
6404 		    (!is_system_labeled() ||
6405 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6406 		    connp))) {
6407 			break;
6408 		}
6409 	}
6410 
6411 	if (connp == NULL || connp->conn_upq == NULL) {
6412 		/*
6413 		 * No one bound to these addresses.  Is
6414 		 * there a client that wants all
6415 		 * unclaimed datagrams?
6416 		 */
6417 		mutex_exit(&connfp->connf_lock);
6418 		/*
6419 		 * Check for IPPROTO_ENCAP...
6420 		 */
6421 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6422 			/*
6423 			 * If an IPsec mblk is here on a multicast
6424 			 * tunnel (using ip_mroute stuff), check policy here,
6425 			 * THEN ship off to ip_mroute_decap().
6426 			 *
6427 			 * BTW,  If I match a configured IP-in-IP
6428 			 * tunnel, this path will not be reached, and
6429 			 * ip_mroute_decap will never be called.
6430 			 */
6431 			first_mp = ipsec_check_global_policy(first_mp, connp,
6432 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6433 			if (first_mp != NULL) {
6434 				if (mctl_present)
6435 					freeb(first_mp);
6436 				ip_mroute_decap(q, mp, ill);
6437 			} /* Else we already freed everything! */
6438 		} else {
6439 			/*
6440 			 * Otherwise send an ICMP protocol unreachable.
6441 			 */
6442 			if (ip_fanout_send_icmp(q, first_mp, flags,
6443 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6444 			    mctl_present, zoneid, ipst)) {
6445 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6446 			}
6447 		}
6448 		return;
6449 	}
6450 	CONN_INC_REF(connp);
6451 	first_connp = connp;
6452 
6453 	/*
6454 	 * Only send message to one tunnel driver by immediately
6455 	 * terminating the loop.
6456 	 */
6457 	connp = one_only ? NULL : connp->conn_next;
6458 
6459 	for (;;) {
6460 		while (connp != NULL) {
6461 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6462 			    flags, zoneid) &&
6463 			    (!is_system_labeled() ||
6464 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6465 			    shared_addr, connp)))
6466 				break;
6467 			connp = connp->conn_next;
6468 		}
6469 
6470 		/*
6471 		 * Copy the packet.
6472 		 */
6473 		if (connp == NULL || connp->conn_upq == NULL ||
6474 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6475 		    ((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6476 			/*
6477 			 * No more interested clients or memory
6478 			 * allocation failed
6479 			 */
6480 			connp = first_connp;
6481 			break;
6482 		}
6483 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6484 		CONN_INC_REF(connp);
6485 		mutex_exit(&connfp->connf_lock);
6486 		rq = connp->conn_rq;
6487 		if (!canputnext(rq)) {
6488 			if (flags & IP_FF_RAWIP) {
6489 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6490 			} else {
6491 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6492 			}
6493 
6494 			freemsg(first_mp1);
6495 		} else {
6496 			/*
6497 			 * Don't enforce here if we're an actual tunnel -
6498 			 * let "tun" do it instead.
6499 			 */
6500 			if (!IPCL_IS_IPTUN(connp) &&
6501 			    (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6502 			    secure)) {
6503 				first_mp1 = ipsec_check_inbound_policy
6504 				    (first_mp1, connp, ipha, NULL,
6505 				    mctl_present);
6506 			}
6507 			if (first_mp1 != NULL) {
6508 				int in_flags = 0;
6509 				/*
6510 				 * ip_fanout_proto also gets called from
6511 				 * icmp_inbound_error_fanout, in which case
6512 				 * the msg type is M_CTL.  Don't add info
6513 				 * in this case for the time being. In future
6514 				 * when there is a need for knowing the
6515 				 * inbound iface index for ICMP error msgs,
6516 				 * then this can be changed.
6517 				 */
6518 				if (connp->conn_recvif)
6519 					in_flags = IPF_RECVIF;
6520 				/*
6521 				 * The ULP may support IP_RECVPKTINFO for both
6522 				 * IP v4 and v6 so pass the appropriate argument
6523 				 * based on conn IP version.
6524 				 */
6525 				if (connp->conn_ip_recvpktinfo) {
6526 					if (connp->conn_af_isv6) {
6527 						/*
6528 						 * V6 only needs index
6529 						 */
6530 						in_flags |= IPF_RECVIF;
6531 					} else {
6532 						/*
6533 						 * V4 needs index +
6534 						 * matching address.
6535 						 */
6536 						in_flags |= IPF_RECVADDR;
6537 					}
6538 				}
6539 				if ((in_flags != 0) &&
6540 				    (mp->b_datap->db_type != M_CTL)) {
6541 					/*
6542 					 * the actual data will be
6543 					 * contained in b_cont upon
6544 					 * successful return of the
6545 					 * following call else
6546 					 * original mblk is returned
6547 					 */
6548 					ASSERT(recv_ill != NULL);
6549 					mp1 = ip_add_info(mp1, recv_ill,
6550 					    in_flags, IPCL_ZONEID(connp), ipst);
6551 				}
6552 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6553 				if (mctl_present)
6554 					freeb(first_mp1);
6555 				(connp->conn_recv)(connp, mp1, NULL);
6556 			}
6557 		}
6558 		mutex_enter(&connfp->connf_lock);
6559 		/* Follow the next pointer before releasing the conn. */
6560 		next_connp = connp->conn_next;
6561 		CONN_DEC_REF(connp);
6562 		connp = next_connp;
6563 	}
6564 
6565 	/* Last one.  Send it upstream. */
6566 	mutex_exit(&connfp->connf_lock);
6567 
6568 	/*
6569 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6570 	 * will be set to false.
6571 	 */
6572 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6573 		ill_index = ill->ill_phyint->phyint_ifindex;
6574 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6575 		if (mp == NULL) {
6576 			CONN_DEC_REF(connp);
6577 			if (mctl_present) {
6578 				freeb(first_mp);
6579 			}
6580 			return;
6581 		}
6582 	}
6583 
6584 	rq = connp->conn_rq;
6585 	if (!canputnext(rq)) {
6586 		if (flags & IP_FF_RAWIP) {
6587 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6588 		} else {
6589 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6590 		}
6591 
6592 		freemsg(first_mp);
6593 	} else {
6594 		if (IPCL_IS_IPTUN(connp)) {
6595 			/*
6596 			 * Tunneled packet.  We enforce policy in the tunnel
6597 			 * module itself.
6598 			 *
6599 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6600 			 * a policy check.
6601 			 * FIXME to use conn_recv for tun later.
6602 			 */
6603 			putnext(rq, first_mp);
6604 			CONN_DEC_REF(connp);
6605 			return;
6606 		}
6607 
6608 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6609 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6610 			    ipha, NULL, mctl_present);
6611 		}
6612 
6613 		if (first_mp != NULL) {
6614 			int in_flags = 0;
6615 
6616 			/*
6617 			 * ip_fanout_proto also gets called
6618 			 * from icmp_inbound_error_fanout, in
6619 			 * which case the msg type is M_CTL.
6620 			 * Don't add info in this case for time
6621 			 * being. In future when there is a
6622 			 * need for knowing the inbound iface
6623 			 * index for ICMP error msgs, then this
6624 			 * can be changed
6625 			 */
6626 			if (connp->conn_recvif)
6627 				in_flags = IPF_RECVIF;
6628 			if (connp->conn_ip_recvpktinfo) {
6629 				if (connp->conn_af_isv6) {
6630 					/*
6631 					 * V6 only needs index
6632 					 */
6633 					in_flags |= IPF_RECVIF;
6634 				} else {
6635 					/*
6636 					 * V4 needs index +
6637 					 * matching address.
6638 					 */
6639 					in_flags |= IPF_RECVADDR;
6640 				}
6641 			}
6642 			if ((in_flags != 0) &&
6643 			    (mp->b_datap->db_type != M_CTL)) {
6644 
6645 				/*
6646 				 * the actual data will be contained in
6647 				 * b_cont upon successful return
6648 				 * of the following call else original
6649 				 * mblk is returned
6650 				 */
6651 				ASSERT(recv_ill != NULL);
6652 				mp = ip_add_info(mp, recv_ill,
6653 				    in_flags, IPCL_ZONEID(connp), ipst);
6654 			}
6655 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6656 			(connp->conn_recv)(connp, mp, NULL);
6657 			if (mctl_present)
6658 				freeb(first_mp);
6659 		}
6660 	}
6661 	CONN_DEC_REF(connp);
6662 }
6663 
6664 /*
6665  * Fanout for TCP packets
6666  * The caller puts <fport, lport> in the ports parameter.
6667  *
6668  * IPQoS Notes
6669  * Before sending it to the client, invoke IPPF processing.
6670  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6671  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6672  * ip_policy is false.
6673  */
6674 static void
6675 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6676     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6677 {
6678 	mblk_t  *first_mp;
6679 	boolean_t secure;
6680 	uint32_t ill_index;
6681 	int	ip_hdr_len;
6682 	tcph_t	*tcph;
6683 	boolean_t syn_present = B_FALSE;
6684 	conn_t	*connp;
6685 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6686 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6687 
6688 	ASSERT(recv_ill != NULL);
6689 
6690 	first_mp = mp;
6691 	if (mctl_present) {
6692 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6693 		mp = first_mp->b_cont;
6694 		secure = ipsec_in_is_secure(first_mp);
6695 		ASSERT(mp != NULL);
6696 	} else {
6697 		secure = B_FALSE;
6698 	}
6699 
6700 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6701 
6702 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6703 	    zoneid, ipst)) == NULL) {
6704 		/*
6705 		 * No connected connection or listener. Send a
6706 		 * TH_RST via tcp_xmit_listeners_reset.
6707 		 */
6708 
6709 		/* Initiate IPPf processing, if needed. */
6710 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6711 			uint32_t ill_index;
6712 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6713 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6714 			if (first_mp == NULL)
6715 				return;
6716 		}
6717 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6718 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6719 		    zoneid));
6720 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6721 		    ipst->ips_netstack->netstack_tcp, NULL);
6722 		return;
6723 	}
6724 
6725 	/*
6726 	 * Allocate the SYN for the TCP connection here itself
6727 	 */
6728 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6729 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6730 		if (IPCL_IS_TCP(connp)) {
6731 			squeue_t *sqp;
6732 
6733 			/*
6734 			 * For fused tcp loopback, assign the eager's
6735 			 * squeue to be that of the active connect's.
6736 			 * Note that we don't check for IP_FF_LOOPBACK
6737 			 * here since this routine gets called only
6738 			 * for loopback (unlike the IPv6 counterpart).
6739 			 */
6740 			ASSERT(Q_TO_CONN(q) != NULL);
6741 			if (do_tcp_fusion &&
6742 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6743 			    !secure &&
6744 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy &&
6745 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6746 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6747 				sqp = Q_TO_CONN(q)->conn_sqp;
6748 			} else {
6749 				sqp = IP_SQUEUE_GET(lbolt);
6750 			}
6751 
6752 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6753 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6754 			syn_present = B_TRUE;
6755 		}
6756 	}
6757 
6758 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6759 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6760 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6761 		if ((flags & TH_RST) || (flags & TH_URG)) {
6762 			CONN_DEC_REF(connp);
6763 			freemsg(first_mp);
6764 			return;
6765 		}
6766 		if (flags & TH_ACK) {
6767 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6768 			    ipst->ips_netstack->netstack_tcp, connp);
6769 			CONN_DEC_REF(connp);
6770 			return;
6771 		}
6772 
6773 		CONN_DEC_REF(connp);
6774 		freemsg(first_mp);
6775 		return;
6776 	}
6777 
6778 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6779 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6780 		    NULL, mctl_present);
6781 		if (first_mp == NULL) {
6782 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6783 			CONN_DEC_REF(connp);
6784 			return;
6785 		}
6786 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6787 			ASSERT(syn_present);
6788 			if (mctl_present) {
6789 				ASSERT(first_mp != mp);
6790 				first_mp->b_datap->db_struioflag |=
6791 				    STRUIO_POLICY;
6792 			} else {
6793 				ASSERT(first_mp == mp);
6794 				mp->b_datap->db_struioflag &=
6795 				    ~STRUIO_EAGER;
6796 				mp->b_datap->db_struioflag |=
6797 				    STRUIO_POLICY;
6798 			}
6799 		} else {
6800 			/*
6801 			 * Discard first_mp early since we're dealing with a
6802 			 * fully-connected conn_t and tcp doesn't do policy in
6803 			 * this case.
6804 			 */
6805 			if (mctl_present) {
6806 				freeb(first_mp);
6807 				mctl_present = B_FALSE;
6808 			}
6809 			first_mp = mp;
6810 		}
6811 	}
6812 
6813 	/*
6814 	 * Initiate policy processing here if needed. If we get here from
6815 	 * icmp_inbound_error_fanout, ip_policy is false.
6816 	 */
6817 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6818 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6819 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6820 		if (mp == NULL) {
6821 			CONN_DEC_REF(connp);
6822 			if (mctl_present)
6823 				freeb(first_mp);
6824 			return;
6825 		} else if (mctl_present) {
6826 			ASSERT(first_mp != mp);
6827 			first_mp->b_cont = mp;
6828 		} else {
6829 			first_mp = mp;
6830 		}
6831 	}
6832 
6833 
6834 
6835 	/* Handle socket options. */
6836 	if (!syn_present &&
6837 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6838 		/* Add header */
6839 		ASSERT(recv_ill != NULL);
6840 		/*
6841 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6842 		 * IPF_RECVIF.
6843 		 */
6844 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6845 		    ipst);
6846 		if (mp == NULL) {
6847 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6848 			CONN_DEC_REF(connp);
6849 			if (mctl_present)
6850 				freeb(first_mp);
6851 			return;
6852 		} else if (mctl_present) {
6853 			/*
6854 			 * ip_add_info might return a new mp.
6855 			 */
6856 			ASSERT(first_mp != mp);
6857 			first_mp->b_cont = mp;
6858 		} else {
6859 			first_mp = mp;
6860 		}
6861 	}
6862 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6863 	if (IPCL_IS_TCP(connp)) {
6864 		/* do not drain, certain use cases can blow the stack */
6865 		squeue_enter_nodrain(connp->conn_sqp, first_mp,
6866 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
6867 	} else {
6868 		/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
6869 		(connp->conn_recv)(connp, first_mp, NULL);
6870 		CONN_DEC_REF(connp);
6871 	}
6872 }
6873 
6874 /*
6875  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
6876  * pass it along to ESP if the SPI is non-zero.  Returns TRUE if the mblk
6877  * is not consumed.
6878  *
6879  * One of four things can happen, all of which affect the passed-in mblk:
6880  *
6881  * 1.) ICMP messages that go through here just get returned TRUE.
6882  *
6883  * 2.) The packet is stock UDP and gets its zero-SPI stripped.  Return TRUE.
6884  *
6885  * 3.) The packet is ESP-in-UDP, gets transformed into an equivalent
6886  *     ESP packet, and is passed along to ESP for consumption.  Return FALSE.
6887  *
6888  * 4.) The packet is an ESP-in-UDP Keepalive.  Drop it and return FALSE.
6889  */
6890 static boolean_t
6891 zero_spi_check(queue_t *q, mblk_t *mp, ire_t *ire, ill_t *recv_ill,
6892     ipsec_stack_t *ipss)
6893 {
6894 	int shift, plen, iph_len;
6895 	ipha_t *ipha;
6896 	udpha_t *udpha;
6897 	uint32_t *spi;
6898 	uint8_t *orptr;
6899 	boolean_t udp_pkt, free_ire;
6900 
6901 	if (DB_TYPE(mp) == M_CTL) {
6902 		/*
6903 		 * ICMP message with UDP inside.  Don't bother stripping, just
6904 		 * send it up.
6905 		 *
6906 		 * NOTE: Any app with UDP_NAT_T_ENDPOINT set is probably going
6907 		 * to ignore errors set by ICMP anyway ('cause they might be
6908 		 * forged), but that's the app's decision, not ours.
6909 		 */
6910 
6911 		/* Bunch of reality checks for DEBUG kernels... */
6912 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION);
6913 		ASSERT(((ipha_t *)mp->b_rptr)->ipha_protocol == IPPROTO_ICMP);
6914 
6915 		return (B_TRUE);
6916 	}
6917 
6918 	ipha = (ipha_t *)mp->b_rptr;
6919 	iph_len = IPH_HDR_LENGTH(ipha);
6920 	plen = ntohs(ipha->ipha_length);
6921 
6922 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
6923 		/*
6924 		 * Most likely a keepalive for the benefit of an intervening
6925 		 * NAT.  These aren't for us, per se, so drop it.
6926 		 *
6927 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
6928 		 * byte packets (keepalives are 1-byte), but we'll drop them
6929 		 * also.
6930 		 */
6931 		ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6932 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
6933 		return (B_FALSE);
6934 	}
6935 
6936 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
6937 		/* might as well pull it all up - it might be ESP. */
6938 		if (!pullupmsg(mp, -1)) {
6939 			ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6940 			    DROPPER(ipss, ipds_esp_nomem),
6941 			    &ipss->ipsec_dropper);
6942 			return (B_FALSE);
6943 		}
6944 
6945 		ipha = (ipha_t *)mp->b_rptr;
6946 	}
6947 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
6948 	if (*spi == 0) {
6949 		/* UDP packet - remove 0-spi. */
6950 		shift = sizeof (uint32_t);
6951 	} else {
6952 		/* ESP-in-UDP packet - reduce to ESP. */
6953 		ipha->ipha_protocol = IPPROTO_ESP;
6954 		shift = sizeof (udpha_t);
6955 	}
6956 
6957 	/* Fix IP header */
6958 	ipha->ipha_length = htons(plen - shift);
6959 	ipha->ipha_hdr_checksum = 0;
6960 
6961 	orptr = mp->b_rptr;
6962 	mp->b_rptr += shift;
6963 
6964 	if (*spi == 0) {
6965 		ASSERT((uint8_t *)ipha == orptr);
6966 		udpha = (udpha_t *)(orptr + iph_len);
6967 		udpha->uha_length = htons(plen - shift - iph_len);
6968 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
6969 		udp_pkt = B_TRUE;
6970 	} else {
6971 		udp_pkt = B_FALSE;
6972 	}
6973 	ovbcopy(orptr, orptr + shift, iph_len);
6974 	if (!udp_pkt) /* Punt up for ESP processing. */ {
6975 		ipha = (ipha_t *)(orptr + shift);
6976 
6977 		free_ire = (ire == NULL);
6978 		if (free_ire) {
6979 			/* Re-acquire ire. */
6980 			ire = ire_cache_lookup(ipha->ipha_dst, ALL_ZONES, NULL,
6981 			    ipss->ipsec_netstack->netstack_ip);
6982 			if (ire == NULL || !(ire->ire_type & IRE_LOCAL)) {
6983 				if (ire != NULL)
6984 					ire_refrele(ire);
6985 				/*
6986 				 * Do a regular freemsg(), as this is an IP
6987 				 * error (no local route) not an IPsec one.
6988 				 */
6989 				freemsg(mp);
6990 			}
6991 		}
6992 
6993 		ip_proto_input(q, mp, ipha, ire, recv_ill, B_TRUE);
6994 		if (free_ire)
6995 			ire_refrele(ire);
6996 	}
6997 
6998 	return (udp_pkt);
6999 }
7000 
7001 /*
7002  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
7003  * We are responsible for disposing of mp, such as by freemsg() or putnext()
7004  * Caller is responsible for dropping references to the conn, and freeing
7005  * first_mp.
7006  *
7007  * IPQoS Notes
7008  * Before sending it to the client, invoke IPPF processing. Policy processing
7009  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
7010  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
7011  * ip_wput_local, ip_policy is false.
7012  */
7013 static void
7014 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
7015     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
7016     boolean_t ip_policy)
7017 {
7018 	boolean_t	mctl_present = (first_mp != NULL);
7019 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
7020 	uint32_t	ill_index;
7021 	ip_stack_t	*ipst = recv_ill->ill_ipst;
7022 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
7023 
7024 	ASSERT(ill != NULL);
7025 
7026 	if (mctl_present)
7027 		first_mp->b_cont = mp;
7028 	else
7029 		first_mp = mp;
7030 
7031 	if (CONN_UDP_FLOWCTLD(connp)) {
7032 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
7033 		freemsg(first_mp);
7034 		return;
7035 	}
7036 
7037 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
7038 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
7039 		    NULL, mctl_present);
7040 		if (first_mp == NULL) {
7041 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7042 			return;	/* Freed by ipsec_check_inbound_policy(). */
7043 		}
7044 	}
7045 	if (mctl_present)
7046 		freeb(first_mp);
7047 
7048 	/* Let's hope the compilers utter "branch, predict-not-taken..." ;) */
7049 	if (connp->conn_udp->udp_nat_t_endpoint) {
7050 		if (mctl_present) {
7051 			/* mctl_present *shouldn't* happen. */
7052 			ip_drop_packet(mp, B_TRUE, NULL, NULL,
7053 			    DROPPER(ipss, ipds_esp_nat_t_ipsec),
7054 			    &ipss->ipsec_dropper);
7055 			return;
7056 		}
7057 
7058 		if (!zero_spi_check(ill->ill_rq, mp, NULL, recv_ill, ipss))
7059 			return;
7060 	}
7061 
7062 	/* Handle options. */
7063 	if (connp->conn_recvif)
7064 		in_flags = IPF_RECVIF;
7065 	/*
7066 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
7067 	 * passed to ip_add_info is based on IP version of connp.
7068 	 */
7069 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
7070 		if (connp->conn_af_isv6) {
7071 			/*
7072 			 * V6 only needs index
7073 			 */
7074 			in_flags |= IPF_RECVIF;
7075 		} else {
7076 			/*
7077 			 * V4 needs index + matching address.
7078 			 */
7079 			in_flags |= IPF_RECVADDR;
7080 		}
7081 	}
7082 
7083 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
7084 		in_flags |= IPF_RECVSLLA;
7085 
7086 	/*
7087 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7088 	 * freed if the packet is dropped. The caller will do so.
7089 	 */
7090 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7091 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7092 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7093 		if (mp == NULL) {
7094 			return;
7095 		}
7096 	}
7097 	if ((in_flags != 0) &&
7098 	    (mp->b_datap->db_type != M_CTL)) {
7099 		/*
7100 		 * The actual data will be contained in b_cont
7101 		 * upon successful return of the following call
7102 		 * else original mblk is returned
7103 		 */
7104 		ASSERT(recv_ill != NULL);
7105 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7106 		    ipst);
7107 	}
7108 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7109 	/* Send it upstream */
7110 	(connp->conn_recv)(connp, mp, NULL);
7111 }
7112 
7113 /*
7114  * Fanout for UDP packets.
7115  * The caller puts <fport, lport> in the ports parameter.
7116  *
7117  * If SO_REUSEADDR is set all multicast and broadcast packets
7118  * will be delivered to all streams bound to the same port.
7119  *
7120  * Zones notes:
7121  * Multicast and broadcast packets will be distributed to streams in all zones.
7122  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7123  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7124  * packets. To maintain this behavior with multiple zones, the conns are grouped
7125  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7126  * each zone. If unset, all the following conns in the same zone are skipped.
7127  */
7128 static void
7129 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7130     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7131     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7132 {
7133 	uint32_t	dstport, srcport;
7134 	ipaddr_t	dst;
7135 	mblk_t		*first_mp;
7136 	boolean_t	secure;
7137 	in6_addr_t	v6src;
7138 	conn_t		*connp;
7139 	connf_t		*connfp;
7140 	conn_t		*first_connp;
7141 	conn_t		*next_connp;
7142 	mblk_t		*mp1, *first_mp1;
7143 	ipaddr_t	src;
7144 	zoneid_t	last_zoneid;
7145 	boolean_t	reuseaddr;
7146 	boolean_t	shared_addr;
7147 	ip_stack_t	*ipst;
7148 
7149 	ASSERT(recv_ill != NULL);
7150 	ipst = recv_ill->ill_ipst;
7151 
7152 	first_mp = mp;
7153 	if (mctl_present) {
7154 		mp = first_mp->b_cont;
7155 		first_mp->b_cont = NULL;
7156 		secure = ipsec_in_is_secure(first_mp);
7157 		ASSERT(mp != NULL);
7158 	} else {
7159 		first_mp = NULL;
7160 		secure = B_FALSE;
7161 	}
7162 
7163 	/* Extract ports in net byte order */
7164 	dstport = htons(ntohl(ports) & 0xFFFF);
7165 	srcport = htons(ntohl(ports) >> 16);
7166 	dst = ipha->ipha_dst;
7167 	src = ipha->ipha_src;
7168 
7169 	shared_addr = (zoneid == ALL_ZONES);
7170 	if (shared_addr) {
7171 		/*
7172 		 * No need to handle exclusive-stack zones since ALL_ZONES
7173 		 * only applies to the shared stack.
7174 		 */
7175 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7176 		if (zoneid == ALL_ZONES)
7177 			zoneid = tsol_packet_to_zoneid(mp);
7178 	}
7179 
7180 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7181 	mutex_enter(&connfp->connf_lock);
7182 	connp = connfp->connf_head;
7183 	if (!broadcast && !CLASSD(dst)) {
7184 		/*
7185 		 * Not broadcast or multicast. Send to the one (first)
7186 		 * client we find. No need to check conn_wantpacket()
7187 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7188 		 * IPv4 unicast packets.
7189 		 */
7190 		while ((connp != NULL) &&
7191 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7192 		    !IPCL_ZONE_MATCH(connp, zoneid))) {
7193 			connp = connp->conn_next;
7194 		}
7195 
7196 		if (connp == NULL || connp->conn_upq == NULL)
7197 			goto notfound;
7198 
7199 		if (is_system_labeled() &&
7200 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7201 		    connp))
7202 			goto notfound;
7203 
7204 		CONN_INC_REF(connp);
7205 		mutex_exit(&connfp->connf_lock);
7206 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7207 		    flags, recv_ill, ip_policy);
7208 		IP_STAT(ipst, ip_udp_fannorm);
7209 		CONN_DEC_REF(connp);
7210 		return;
7211 	}
7212 
7213 	/*
7214 	 * Broadcast and multicast case
7215 	 *
7216 	 * Need to check conn_wantpacket().
7217 	 * If SO_REUSEADDR has been set on the first we send the
7218 	 * packet to all clients that have joined the group and
7219 	 * match the port.
7220 	 */
7221 
7222 	while (connp != NULL) {
7223 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7224 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7225 		    (!is_system_labeled() ||
7226 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7227 		    connp)))
7228 			break;
7229 		connp = connp->conn_next;
7230 	}
7231 
7232 	if (connp == NULL || connp->conn_upq == NULL)
7233 		goto notfound;
7234 
7235 	first_connp = connp;
7236 	/*
7237 	 * When SO_REUSEADDR is not set, send the packet only to the first
7238 	 * matching connection in its zone by keeping track of the zoneid.
7239 	 */
7240 	reuseaddr = first_connp->conn_reuseaddr;
7241 	last_zoneid = first_connp->conn_zoneid;
7242 
7243 	CONN_INC_REF(connp);
7244 	connp = connp->conn_next;
7245 	for (;;) {
7246 		while (connp != NULL) {
7247 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7248 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7249 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7250 			    (!is_system_labeled() ||
7251 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7252 			    shared_addr, connp)))
7253 				break;
7254 			connp = connp->conn_next;
7255 		}
7256 		/*
7257 		 * Just copy the data part alone. The mctl part is
7258 		 * needed just for verifying policy and it is never
7259 		 * sent up.
7260 		 */
7261 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7262 		    ((mp1 = copymsg(mp)) == NULL))) {
7263 			/*
7264 			 * No more interested clients or memory
7265 			 * allocation failed
7266 			 */
7267 			connp = first_connp;
7268 			break;
7269 		}
7270 		if (connp->conn_zoneid != last_zoneid) {
7271 			/*
7272 			 * Update the zoneid so that the packet isn't sent to
7273 			 * any more conns in the same zone unless SO_REUSEADDR
7274 			 * is set.
7275 			 */
7276 			reuseaddr = connp->conn_reuseaddr;
7277 			last_zoneid = connp->conn_zoneid;
7278 		}
7279 		if (first_mp != NULL) {
7280 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7281 			    ipsec_info_type == IPSEC_IN);
7282 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7283 			    ipst->ips_netstack);
7284 			if (first_mp1 == NULL) {
7285 				freemsg(mp1);
7286 				connp = first_connp;
7287 				break;
7288 			}
7289 		} else {
7290 			first_mp1 = NULL;
7291 		}
7292 		CONN_INC_REF(connp);
7293 		mutex_exit(&connfp->connf_lock);
7294 		/*
7295 		 * IPQoS notes: We don't send the packet for policy
7296 		 * processing here, will do it for the last one (below).
7297 		 * i.e. we do it per-packet now, but if we do policy
7298 		 * processing per-conn, then we would need to do it
7299 		 * here too.
7300 		 */
7301 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7302 		    ipha, flags, recv_ill, B_FALSE);
7303 		mutex_enter(&connfp->connf_lock);
7304 		/* Follow the next pointer before releasing the conn. */
7305 		next_connp = connp->conn_next;
7306 		IP_STAT(ipst, ip_udp_fanmb);
7307 		CONN_DEC_REF(connp);
7308 		connp = next_connp;
7309 	}
7310 
7311 	/* Last one.  Send it upstream. */
7312 	mutex_exit(&connfp->connf_lock);
7313 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7314 	    recv_ill, ip_policy);
7315 	IP_STAT(ipst, ip_udp_fanmb);
7316 	CONN_DEC_REF(connp);
7317 	return;
7318 
7319 notfound:
7320 
7321 	mutex_exit(&connfp->connf_lock);
7322 	IP_STAT(ipst, ip_udp_fanothers);
7323 	/*
7324 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7325 	 * have already been matched above, since they live in the IPv4
7326 	 * fanout tables. This implies we only need to
7327 	 * check for IPv6 in6addr_any endpoints here.
7328 	 * Thus we compare using ipv6_all_zeros instead of the destination
7329 	 * address, except for the multicast group membership lookup which
7330 	 * uses the IPv4 destination.
7331 	 */
7332 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7333 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7334 	mutex_enter(&connfp->connf_lock);
7335 	connp = connfp->connf_head;
7336 	if (!broadcast && !CLASSD(dst)) {
7337 		while (connp != NULL) {
7338 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7339 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7340 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7341 			    !connp->conn_ipv6_v6only)
7342 				break;
7343 			connp = connp->conn_next;
7344 		}
7345 
7346 		if (connp != NULL && is_system_labeled() &&
7347 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7348 		    connp))
7349 			connp = NULL;
7350 
7351 		if (connp == NULL || connp->conn_upq == NULL) {
7352 			/*
7353 			 * No one bound to this port.  Is
7354 			 * there a client that wants all
7355 			 * unclaimed datagrams?
7356 			 */
7357 			mutex_exit(&connfp->connf_lock);
7358 
7359 			if (mctl_present)
7360 				first_mp->b_cont = mp;
7361 			else
7362 				first_mp = mp;
7363 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7364 			    connf_head != NULL) {
7365 				ip_fanout_proto(q, first_mp, ill, ipha,
7366 				    flags | IP_FF_RAWIP, mctl_present,
7367 				    ip_policy, recv_ill, zoneid);
7368 			} else {
7369 				if (ip_fanout_send_icmp(q, first_mp, flags,
7370 				    ICMP_DEST_UNREACHABLE,
7371 				    ICMP_PORT_UNREACHABLE,
7372 				    mctl_present, zoneid, ipst)) {
7373 					BUMP_MIB(ill->ill_ip_mib,
7374 					    udpIfStatsNoPorts);
7375 				}
7376 			}
7377 			return;
7378 		}
7379 
7380 		CONN_INC_REF(connp);
7381 		mutex_exit(&connfp->connf_lock);
7382 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7383 		    flags, recv_ill, ip_policy);
7384 		CONN_DEC_REF(connp);
7385 		return;
7386 	}
7387 	/*
7388 	 * IPv4 multicast packet being delivered to an AF_INET6
7389 	 * in6addr_any endpoint.
7390 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7391 	 * and not conn_wantpacket_v6() since any multicast membership is
7392 	 * for an IPv4-mapped multicast address.
7393 	 * The packet is sent to all clients in all zones that have joined the
7394 	 * group and match the port.
7395 	 */
7396 	while (connp != NULL) {
7397 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7398 		    srcport, v6src) &&
7399 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7400 		    (!is_system_labeled() ||
7401 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7402 		    connp)))
7403 			break;
7404 		connp = connp->conn_next;
7405 	}
7406 
7407 	if (connp == NULL || connp->conn_upq == NULL) {
7408 		/*
7409 		 * No one bound to this port.  Is
7410 		 * there a client that wants all
7411 		 * unclaimed datagrams?
7412 		 */
7413 		mutex_exit(&connfp->connf_lock);
7414 
7415 		if (mctl_present)
7416 			first_mp->b_cont = mp;
7417 		else
7418 			first_mp = mp;
7419 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7420 		    NULL) {
7421 			ip_fanout_proto(q, first_mp, ill, ipha,
7422 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7423 			    recv_ill, zoneid);
7424 		} else {
7425 			/*
7426 			 * We used to attempt to send an icmp error here, but
7427 			 * since this is known to be a multicast packet
7428 			 * and we don't send icmp errors in response to
7429 			 * multicast, just drop the packet and give up sooner.
7430 			 */
7431 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7432 			freemsg(first_mp);
7433 		}
7434 		return;
7435 	}
7436 
7437 	first_connp = connp;
7438 
7439 	CONN_INC_REF(connp);
7440 	connp = connp->conn_next;
7441 	for (;;) {
7442 		while (connp != NULL) {
7443 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7444 			    ipv6_all_zeros, srcport, v6src) &&
7445 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7446 			    (!is_system_labeled() ||
7447 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7448 			    shared_addr, connp)))
7449 				break;
7450 			connp = connp->conn_next;
7451 		}
7452 		/*
7453 		 * Just copy the data part alone. The mctl part is
7454 		 * needed just for verifying policy and it is never
7455 		 * sent up.
7456 		 */
7457 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7458 		    ((mp1 = copymsg(mp)) == NULL))) {
7459 			/*
7460 			 * No more intested clients or memory
7461 			 * allocation failed
7462 			 */
7463 			connp = first_connp;
7464 			break;
7465 		}
7466 		if (first_mp != NULL) {
7467 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7468 			    ipsec_info_type == IPSEC_IN);
7469 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7470 			    ipst->ips_netstack);
7471 			if (first_mp1 == NULL) {
7472 				freemsg(mp1);
7473 				connp = first_connp;
7474 				break;
7475 			}
7476 		} else {
7477 			first_mp1 = NULL;
7478 		}
7479 		CONN_INC_REF(connp);
7480 		mutex_exit(&connfp->connf_lock);
7481 		/*
7482 		 * IPQoS notes: We don't send the packet for policy
7483 		 * processing here, will do it for the last one (below).
7484 		 * i.e. we do it per-packet now, but if we do policy
7485 		 * processing per-conn, then we would need to do it
7486 		 * here too.
7487 		 */
7488 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7489 		    ipha, flags, recv_ill, B_FALSE);
7490 		mutex_enter(&connfp->connf_lock);
7491 		/* Follow the next pointer before releasing the conn. */
7492 		next_connp = connp->conn_next;
7493 		CONN_DEC_REF(connp);
7494 		connp = next_connp;
7495 	}
7496 
7497 	/* Last one.  Send it upstream. */
7498 	mutex_exit(&connfp->connf_lock);
7499 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7500 	    recv_ill, ip_policy);
7501 	CONN_DEC_REF(connp);
7502 }
7503 
7504 /*
7505  * Complete the ip_wput header so that it
7506  * is possible to generate ICMP
7507  * errors.
7508  */
7509 int
7510 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7511 {
7512 	ire_t *ire;
7513 
7514 	if (ipha->ipha_src == INADDR_ANY) {
7515 		ire = ire_lookup_local(zoneid, ipst);
7516 		if (ire == NULL) {
7517 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7518 			return (1);
7519 		}
7520 		ipha->ipha_src = ire->ire_addr;
7521 		ire_refrele(ire);
7522 	}
7523 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7524 	ipha->ipha_hdr_checksum = 0;
7525 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7526 	return (0);
7527 }
7528 
7529 /*
7530  * Nobody should be sending
7531  * packets up this stream
7532  */
7533 static void
7534 ip_lrput(queue_t *q, mblk_t *mp)
7535 {
7536 	mblk_t *mp1;
7537 
7538 	switch (mp->b_datap->db_type) {
7539 	case M_FLUSH:
7540 		/* Turn around */
7541 		if (*mp->b_rptr & FLUSHW) {
7542 			*mp->b_rptr &= ~FLUSHR;
7543 			qreply(q, mp);
7544 			return;
7545 		}
7546 		break;
7547 	}
7548 	/* Could receive messages that passed through ar_rput */
7549 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7550 		mp1->b_prev = mp1->b_next = NULL;
7551 	freemsg(mp);
7552 }
7553 
7554 /* Nobody should be sending packets down this stream */
7555 /* ARGSUSED */
7556 void
7557 ip_lwput(queue_t *q, mblk_t *mp)
7558 {
7559 	freemsg(mp);
7560 }
7561 
7562 /*
7563  * Move the first hop in any source route to ipha_dst and remove that part of
7564  * the source route.  Called by other protocols.  Errors in option formatting
7565  * are ignored - will be handled by ip_wput_options Return the final
7566  * destination (either ipha_dst or the last entry in a source route.)
7567  */
7568 ipaddr_t
7569 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7570 {
7571 	ipoptp_t	opts;
7572 	uchar_t		*opt;
7573 	uint8_t		optval;
7574 	uint8_t		optlen;
7575 	ipaddr_t	dst;
7576 	int		i;
7577 	ire_t		*ire;
7578 	ip_stack_t	*ipst = ns->netstack_ip;
7579 
7580 	ip2dbg(("ip_massage_options\n"));
7581 	dst = ipha->ipha_dst;
7582 	for (optval = ipoptp_first(&opts, ipha);
7583 	    optval != IPOPT_EOL;
7584 	    optval = ipoptp_next(&opts)) {
7585 		opt = opts.ipoptp_cur;
7586 		switch (optval) {
7587 			uint8_t off;
7588 		case IPOPT_SSRR:
7589 		case IPOPT_LSRR:
7590 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7591 				ip1dbg(("ip_massage_options: bad src route\n"));
7592 				break;
7593 			}
7594 			optlen = opts.ipoptp_len;
7595 			off = opt[IPOPT_OFFSET];
7596 			off--;
7597 		redo_srr:
7598 			if (optlen < IP_ADDR_LEN ||
7599 			    off > optlen - IP_ADDR_LEN) {
7600 				/* End of source route */
7601 				ip1dbg(("ip_massage_options: end of SR\n"));
7602 				break;
7603 			}
7604 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7605 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7606 			    ntohl(dst)));
7607 			/*
7608 			 * Check if our address is present more than
7609 			 * once as consecutive hops in source route.
7610 			 * XXX verify per-interface ip_forwarding
7611 			 * for source route?
7612 			 */
7613 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7614 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7615 			if (ire != NULL) {
7616 				ire_refrele(ire);
7617 				off += IP_ADDR_LEN;
7618 				goto redo_srr;
7619 			}
7620 			if (dst == htonl(INADDR_LOOPBACK)) {
7621 				ip1dbg(("ip_massage_options: loopback addr in "
7622 				    "source route!\n"));
7623 				break;
7624 			}
7625 			/*
7626 			 * Update ipha_dst to be the first hop and remove the
7627 			 * first hop from the source route (by overwriting
7628 			 * part of the option with NOP options).
7629 			 */
7630 			ipha->ipha_dst = dst;
7631 			/* Put the last entry in dst */
7632 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7633 			    3;
7634 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7635 
7636 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7637 			    ntohl(dst)));
7638 			/* Move down and overwrite */
7639 			opt[IP_ADDR_LEN] = opt[0];
7640 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7641 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7642 			for (i = 0; i < IP_ADDR_LEN; i++)
7643 				opt[i] = IPOPT_NOP;
7644 			break;
7645 		}
7646 	}
7647 	return (dst);
7648 }
7649 
7650 /*
7651  * Return the network mask
7652  * associated with the specified address.
7653  */
7654 ipaddr_t
7655 ip_net_mask(ipaddr_t addr)
7656 {
7657 	uchar_t	*up = (uchar_t *)&addr;
7658 	ipaddr_t mask = 0;
7659 	uchar_t	*maskp = (uchar_t *)&mask;
7660 
7661 #if defined(__i386) || defined(__amd64)
7662 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7663 #endif
7664 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7665 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7666 #endif
7667 	if (CLASSD(addr)) {
7668 		maskp[0] = 0xF0;
7669 		return (mask);
7670 	}
7671 	if (addr == 0)
7672 		return (0);
7673 	maskp[0] = 0xFF;
7674 	if ((up[0] & 0x80) == 0)
7675 		return (mask);
7676 
7677 	maskp[1] = 0xFF;
7678 	if ((up[0] & 0xC0) == 0x80)
7679 		return (mask);
7680 
7681 	maskp[2] = 0xFF;
7682 	if ((up[0] & 0xE0) == 0xC0)
7683 		return (mask);
7684 
7685 	/* Must be experimental or multicast, indicate as much */
7686 	return ((ipaddr_t)0);
7687 }
7688 
7689 /*
7690  * Select an ill for the packet by considering load spreading across
7691  * a different ill in the group if dst_ill is part of some group.
7692  */
7693 ill_t *
7694 ip_newroute_get_dst_ill(ill_t *dst_ill)
7695 {
7696 	ill_t *ill;
7697 
7698 	/*
7699 	 * We schedule irrespective of whether the source address is
7700 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7701 	 */
7702 	ill = illgrp_scheduler(dst_ill);
7703 	if (ill == NULL)
7704 		return (NULL);
7705 
7706 	/*
7707 	 * For groups with names ip_sioctl_groupname ensures that all
7708 	 * ills are of same type. For groups without names, ifgrp_insert
7709 	 * ensures this.
7710 	 */
7711 	ASSERT(dst_ill->ill_type == ill->ill_type);
7712 
7713 	return (ill);
7714 }
7715 
7716 /*
7717  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7718  */
7719 ill_t *
7720 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6,
7721     ip_stack_t *ipst)
7722 {
7723 	ill_t *ret_ill;
7724 
7725 	ASSERT(ifindex != 0);
7726 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7727 	    ipst);
7728 	if (ret_ill == NULL ||
7729 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7730 		if (isv6) {
7731 			if (ill != NULL) {
7732 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7733 			} else {
7734 				BUMP_MIB(&ipst->ips_ip6_mib,
7735 				    ipIfStatsOutDiscards);
7736 			}
7737 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7738 			    "bad ifindex %d.\n", ifindex));
7739 		} else {
7740 			if (ill != NULL) {
7741 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7742 			} else {
7743 				BUMP_MIB(&ipst->ips_ip_mib,
7744 				    ipIfStatsOutDiscards);
7745 			}
7746 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7747 			    "bad ifindex %d.\n", ifindex));
7748 		}
7749 		if (ret_ill != NULL)
7750 			ill_refrele(ret_ill);
7751 		freemsg(first_mp);
7752 		return (NULL);
7753 	}
7754 
7755 	return (ret_ill);
7756 }
7757 
7758 /*
7759  * IPv4 -
7760  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7761  * out a packet to a destination address for which we do not have specific
7762  * (or sufficient) routing information.
7763  *
7764  * NOTE : These are the scopes of some of the variables that point at IRE,
7765  *	  which needs to be followed while making any future modifications
7766  *	  to avoid memory leaks.
7767  *
7768  *	- ire and sire are the entries looked up initially by
7769  *	  ire_ftable_lookup.
7770  *	- ipif_ire is used to hold the interface ire associated with
7771  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7772  *	  it before branching out to error paths.
7773  *	- save_ire is initialized before ire_create, so that ire returned
7774  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7775  *	  before breaking out of the switch.
7776  *
7777  *	Thus on failures, we have to REFRELE only ire and sire, if they
7778  *	are not NULL.
7779  */
7780 void
7781 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, conn_t *connp,
7782     zoneid_t zoneid, ip_stack_t *ipst)
7783 {
7784 	areq_t	*areq;
7785 	ipaddr_t gw = 0;
7786 	ire_t	*ire = NULL;
7787 	mblk_t	*res_mp;
7788 	ipaddr_t *addrp;
7789 	ipaddr_t nexthop_addr;
7790 	ipif_t  *src_ipif = NULL;
7791 	ill_t	*dst_ill = NULL;
7792 	ipha_t  *ipha;
7793 	ire_t	*sire = NULL;
7794 	mblk_t	*first_mp;
7795 	ire_t	*save_ire;
7796 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7797 	ushort_t ire_marks = 0;
7798 	boolean_t mctl_present;
7799 	ipsec_out_t *io;
7800 	mblk_t	*saved_mp;
7801 	ire_t	*first_sire = NULL;
7802 	mblk_t	*copy_mp = NULL;
7803 	mblk_t	*xmit_mp = NULL;
7804 	ipaddr_t save_dst;
7805 	uint32_t multirt_flags =
7806 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7807 	boolean_t multirt_is_resolvable;
7808 	boolean_t multirt_resolve_next;
7809 	boolean_t unspec_src;
7810 	boolean_t do_attach_ill = B_FALSE;
7811 	boolean_t ip_nexthop = B_FALSE;
7812 	tsol_ire_gw_secattr_t *attrp = NULL;
7813 	tsol_gcgrp_t *gcgrp = NULL;
7814 	tsol_gcgrp_addr_t ga;
7815 
7816 	if (ip_debug > 2) {
7817 		/* ip1dbg */
7818 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7819 	}
7820 
7821 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7822 	if (mctl_present) {
7823 		io = (ipsec_out_t *)first_mp->b_rptr;
7824 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7825 		ASSERT(zoneid == io->ipsec_out_zoneid);
7826 		ASSERT(zoneid != ALL_ZONES);
7827 	}
7828 
7829 	ipha = (ipha_t *)mp->b_rptr;
7830 
7831 	/* All multicast lookups come through ip_newroute_ipif() */
7832 	if (CLASSD(dst)) {
7833 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7834 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7835 		freemsg(first_mp);
7836 		return;
7837 	}
7838 
7839 	if (mctl_present && io->ipsec_out_attach_if) {
7840 		/* ip_grab_attach_ill returns a held ill */
7841 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7842 		    io->ipsec_out_ill_index, B_FALSE, ipst);
7843 
7844 		/* Failure case frees things for us. */
7845 		if (attach_ill == NULL)
7846 			return;
7847 
7848 		/*
7849 		 * Check if we need an ire that will not be
7850 		 * looked up by anybody else i.e. HIDDEN.
7851 		 */
7852 		if (ill_is_probeonly(attach_ill))
7853 			ire_marks = IRE_MARK_HIDDEN;
7854 	}
7855 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7856 		ip_nexthop = B_TRUE;
7857 		nexthop_addr = io->ipsec_out_nexthop_addr;
7858 	}
7859 	/*
7860 	 * If this IRE is created for forwarding or it is not for
7861 	 * traffic for congestion controlled protocols, mark it as temporary.
7862 	 */
7863 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7864 		ire_marks |= IRE_MARK_TEMPORARY;
7865 
7866 	/*
7867 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7868 	 * chain until it gets the most specific information available.
7869 	 * For example, we know that there is no IRE_CACHE for this dest,
7870 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7871 	 * ire_ftable_lookup will look up the gateway, etc.
7872 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7873 	 * to the destination, of equal netmask length in the forward table,
7874 	 * will be recursively explored. If no information is available
7875 	 * for the final gateway of that route, we force the returned ire
7876 	 * to be equal to sire using MATCH_IRE_PARENT.
7877 	 * At least, in this case we have a starting point (in the buckets)
7878 	 * to look for other routes to the destination in the forward table.
7879 	 * This is actually used only for multirouting, where a list
7880 	 * of routes has to be processed in sequence.
7881 	 *
7882 	 * In the process of coming up with the most specific information,
7883 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7884 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7885 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7886 	 * Two caveats when handling incomplete ire's in ip_newroute:
7887 	 * - we should be careful when accessing its ire_nce (specifically
7888 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7889 	 * - not all legacy code path callers are prepared to handle
7890 	 *   incomplete ire's, so we should not create/add incomplete
7891 	 *   ire_cache entries here. (See discussion about temporary solution
7892 	 *   further below).
7893 	 *
7894 	 * In order to minimize packet dropping, and to preserve existing
7895 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7896 	 * gateway, and instead use the IF_RESOLVER ire to send out
7897 	 * another request to ARP (this is achieved by passing the
7898 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
7899 	 * arp response comes back in ip_wput_nondata, we will create
7900 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
7901 	 *
7902 	 * Note that this is a temporary solution; the correct solution is
7903 	 * to create an incomplete  per-dst ire_cache entry, and send the
7904 	 * packet out when the gw's nce is resolved. In order to achieve this,
7905 	 * all packet processing must have been completed prior to calling
7906 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
7907 	 * to be modified to accomodate this solution.
7908 	 */
7909 	if (ip_nexthop) {
7910 		/*
7911 		 * The first time we come here, we look for an IRE_INTERFACE
7912 		 * entry for the specified nexthop, set the dst to be the
7913 		 * nexthop address and create an IRE_CACHE entry for the
7914 		 * nexthop. The next time around, we are able to find an
7915 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7916 		 * nexthop address and create an IRE_CACHE entry for the
7917 		 * destination address via the specified nexthop.
7918 		 */
7919 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7920 		    MBLK_GETLABEL(mp), ipst);
7921 		if (ire != NULL) {
7922 			gw = nexthop_addr;
7923 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7924 		} else {
7925 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7926 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7927 			    MBLK_GETLABEL(mp),
7928 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
7929 			    ipst);
7930 			if (ire != NULL) {
7931 				dst = nexthop_addr;
7932 			}
7933 		}
7934 	} else if (attach_ill == NULL) {
7935 		ire = ire_ftable_lookup(dst, 0, 0, 0,
7936 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
7937 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
7938 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
7939 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
7940 		    ipst);
7941 	} else {
7942 		/*
7943 		 * attach_ill is set only for communicating with
7944 		 * on-link hosts. So, don't look for DEFAULT.
7945 		 */
7946 		ipif_t	*attach_ipif;
7947 
7948 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
7949 		if (attach_ipif == NULL) {
7950 			ill_refrele(attach_ill);
7951 			goto icmp_err_ret;
7952 		}
7953 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
7954 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
7955 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
7956 		    MATCH_IRE_SECATTR, ipst);
7957 		ipif_refrele(attach_ipif);
7958 	}
7959 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
7960 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
7961 
7962 	/*
7963 	 * This loop is run only once in most cases.
7964 	 * We loop to resolve further routes only when the destination
7965 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7966 	 */
7967 	do {
7968 		/* Clear the previous iteration's values */
7969 		if (src_ipif != NULL) {
7970 			ipif_refrele(src_ipif);
7971 			src_ipif = NULL;
7972 		}
7973 		if (dst_ill != NULL) {
7974 			ill_refrele(dst_ill);
7975 			dst_ill = NULL;
7976 		}
7977 
7978 		multirt_resolve_next = B_FALSE;
7979 		/*
7980 		 * We check if packets have to be multirouted.
7981 		 * In this case, given the current <ire, sire> couple,
7982 		 * we look for the next suitable <ire, sire>.
7983 		 * This check is done in ire_multirt_lookup(),
7984 		 * which applies various criteria to find the next route
7985 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
7986 		 * unchanged if it detects it has not been tried yet.
7987 		 */
7988 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7989 			ip3dbg(("ip_newroute: starting next_resolution "
7990 			    "with first_mp %p, tag %d\n",
7991 			    (void *)first_mp,
7992 			    MULTIRT_DEBUG_TAGGED(first_mp)));
7993 
7994 			ASSERT(sire != NULL);
7995 			multirt_is_resolvable =
7996 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
7997 			    MBLK_GETLABEL(mp), ipst);
7998 
7999 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
8000 			    "ire %p, sire %p\n",
8001 			    multirt_is_resolvable,
8002 			    (void *)ire, (void *)sire));
8003 
8004 			if (!multirt_is_resolvable) {
8005 				/*
8006 				 * No more multirt route to resolve; give up
8007 				 * (all routes resolved or no more
8008 				 * resolvable routes).
8009 				 */
8010 				if (ire != NULL) {
8011 					ire_refrele(ire);
8012 					ire = NULL;
8013 				}
8014 			} else {
8015 				ASSERT(sire != NULL);
8016 				ASSERT(ire != NULL);
8017 				/*
8018 				 * We simply use first_sire as a flag that
8019 				 * indicates if a resolvable multirt route
8020 				 * has already been found.
8021 				 * If it is not the case, we may have to send
8022 				 * an ICMP error to report that the
8023 				 * destination is unreachable.
8024 				 * We do not IRE_REFHOLD first_sire.
8025 				 */
8026 				if (first_sire == NULL) {
8027 					first_sire = sire;
8028 				}
8029 			}
8030 		}
8031 		if (ire == NULL) {
8032 			if (ip_debug > 3) {
8033 				/* ip2dbg */
8034 				pr_addr_dbg("ip_newroute: "
8035 				    "can't resolve %s\n", AF_INET, &dst);
8036 			}
8037 			ip3dbg(("ip_newroute: "
8038 			    "ire %p, sire %p, first_sire %p\n",
8039 			    (void *)ire, (void *)sire, (void *)first_sire));
8040 
8041 			if (sire != NULL) {
8042 				ire_refrele(sire);
8043 				sire = NULL;
8044 			}
8045 
8046 			if (first_sire != NULL) {
8047 				/*
8048 				 * At least one multirt route has been found
8049 				 * in the same call to ip_newroute();
8050 				 * there is no need to report an ICMP error.
8051 				 * first_sire was not IRE_REFHOLDed.
8052 				 */
8053 				MULTIRT_DEBUG_UNTAG(first_mp);
8054 				freemsg(first_mp);
8055 				return;
8056 			}
8057 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8058 			    RTA_DST, ipst);
8059 			if (attach_ill != NULL)
8060 				ill_refrele(attach_ill);
8061 			goto icmp_err_ret;
8062 		}
8063 
8064 		/*
8065 		 * Verify that the returned IRE does not have either
8066 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8067 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8068 		 */
8069 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8070 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8071 			if (attach_ill != NULL)
8072 				ill_refrele(attach_ill);
8073 			goto icmp_err_ret;
8074 		}
8075 		/*
8076 		 * Increment the ire_ob_pkt_count field for ire if it is an
8077 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8078 		 * increment the same for the parent IRE, sire, if it is some
8079 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, and HOST)
8080 		 */
8081 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8082 			UPDATE_OB_PKT_COUNT(ire);
8083 			ire->ire_last_used_time = lbolt;
8084 		}
8085 
8086 		if (sire != NULL) {
8087 			gw = sire->ire_gateway_addr;
8088 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8089 			    IRE_INTERFACE)) == 0);
8090 			UPDATE_OB_PKT_COUNT(sire);
8091 			sire->ire_last_used_time = lbolt;
8092 		}
8093 		/*
8094 		 * We have a route to reach the destination.
8095 		 *
8096 		 * 1) If the interface is part of ill group, try to get a new
8097 		 *    ill taking load spreading into account.
8098 		 *
8099 		 * 2) After selecting the ill, get a source address that
8100 		 *    might create good inbound load spreading.
8101 		 *    ipif_select_source does this for us.
8102 		 *
8103 		 * If the application specified the ill (ifindex), we still
8104 		 * load spread. Only if the packets needs to go out
8105 		 * specifically on a given ill e.g. binding to
8106 		 * IPIF_NOFAILOVER address, then we don't try to use a
8107 		 * different ill for load spreading.
8108 		 */
8109 		if (attach_ill == NULL) {
8110 			/*
8111 			 * Don't perform outbound load spreading in the
8112 			 * case of an RTF_MULTIRT route, as we actually
8113 			 * typically want to replicate outgoing packets
8114 			 * through particular interfaces.
8115 			 */
8116 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8117 				dst_ill = ire->ire_ipif->ipif_ill;
8118 				/* for uniformity */
8119 				ill_refhold(dst_ill);
8120 			} else {
8121 				/*
8122 				 * If we are here trying to create an IRE_CACHE
8123 				 * for an offlink destination and have the
8124 				 * IRE_CACHE for the next hop and the latter is
8125 				 * using virtual IP source address selection i.e
8126 				 * it's ire->ire_ipif is pointing to a virtual
8127 				 * network interface (vni) then
8128 				 * ip_newroute_get_dst_ll() will return the vni
8129 				 * interface as the dst_ill. Since the vni is
8130 				 * virtual i.e not associated with any physical
8131 				 * interface, it cannot be the dst_ill, hence
8132 				 * in such a case call ip_newroute_get_dst_ll()
8133 				 * with the stq_ill instead of the ire_ipif ILL.
8134 				 * The function returns a refheld ill.
8135 				 */
8136 				if ((ire->ire_type == IRE_CACHE) &&
8137 				    IS_VNI(ire->ire_ipif->ipif_ill))
8138 					dst_ill = ip_newroute_get_dst_ill(
8139 					    ire->ire_stq->q_ptr);
8140 				else
8141 					dst_ill = ip_newroute_get_dst_ill(
8142 					    ire->ire_ipif->ipif_ill);
8143 			}
8144 			if (dst_ill == NULL) {
8145 				if (ip_debug > 2) {
8146 					pr_addr_dbg("ip_newroute: "
8147 					    "no dst ill for dst"
8148 					    " %s\n", AF_INET, &dst);
8149 				}
8150 				goto icmp_err_ret;
8151 			}
8152 		} else {
8153 			dst_ill = ire->ire_ipif->ipif_ill;
8154 			/* for uniformity */
8155 			ill_refhold(dst_ill);
8156 			/*
8157 			 * We should have found a route matching ill as we
8158 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
8159 			 * Rather than asserting, when there is a mismatch,
8160 			 * we just drop the packet.
8161 			 */
8162 			if (dst_ill != attach_ill) {
8163 				ip0dbg(("ip_newroute: Packet dropped as "
8164 				    "IPIF_NOFAILOVER ill is %s, "
8165 				    "ire->ire_ipif->ipif_ill is %s\n",
8166 				    attach_ill->ill_name,
8167 				    dst_ill->ill_name));
8168 				ill_refrele(attach_ill);
8169 				goto icmp_err_ret;
8170 			}
8171 		}
8172 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
8173 		if (attach_ill != NULL) {
8174 			ill_refrele(attach_ill);
8175 			attach_ill = NULL;
8176 			do_attach_ill = B_TRUE;
8177 		}
8178 		ASSERT(dst_ill != NULL);
8179 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8180 
8181 		/*
8182 		 * Pick the best source address from dst_ill.
8183 		 *
8184 		 * 1) If it is part of a multipathing group, we would
8185 		 *    like to spread the inbound packets across different
8186 		 *    interfaces. ipif_select_source picks a random source
8187 		 *    across the different ills in the group.
8188 		 *
8189 		 * 2) If it is not part of a multipathing group, we try
8190 		 *    to pick the source address from the destination
8191 		 *    route. Clustering assumes that when we have multiple
8192 		 *    prefixes hosted on an interface, the prefix of the
8193 		 *    source address matches the prefix of the destination
8194 		 *    route. We do this only if the address is not
8195 		 *    DEPRECATED.
8196 		 *
8197 		 * 3) If the conn is in a different zone than the ire, we
8198 		 *    need to pick a source address from the right zone.
8199 		 *
8200 		 * NOTE : If we hit case (1) above, the prefix of the source
8201 		 *	  address picked may not match the prefix of the
8202 		 *	  destination routes prefix as ipif_select_source
8203 		 *	  does not look at "dst" while picking a source
8204 		 *	  address.
8205 		 *	  If we want the same behavior as (2), we will need
8206 		 *	  to change the behavior of ipif_select_source.
8207 		 */
8208 		ASSERT(src_ipif == NULL);
8209 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8210 			/*
8211 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8212 			 * Check that the ipif matching the requested source
8213 			 * address still exists.
8214 			 */
8215 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8216 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8217 		}
8218 
8219 		unspec_src = (connp != NULL && connp->conn_unspec_src);
8220 
8221 		if (src_ipif == NULL &&
8222 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
8223 			ire_marks |= IRE_MARK_USESRC_CHECK;
8224 			if ((dst_ill->ill_group != NULL) ||
8225 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8226 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8227 			    ire->ire_zoneid != ALL_ZONES) ||
8228 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8229 				/*
8230 				 * If the destination is reachable via a
8231 				 * given gateway, the selected source address
8232 				 * should be in the same subnet as the gateway.
8233 				 * Otherwise, the destination is not reachable.
8234 				 *
8235 				 * If there are no interfaces on the same subnet
8236 				 * as the destination, ipif_select_source gives
8237 				 * first non-deprecated interface which might be
8238 				 * on a different subnet than the gateway.
8239 				 * This is not desirable. Hence pass the dst_ire
8240 				 * source address to ipif_select_source.
8241 				 * It is sure that the destination is reachable
8242 				 * with the dst_ire source address subnet.
8243 				 * So passing dst_ire source address to
8244 				 * ipif_select_source will make sure that the
8245 				 * selected source will be on the same subnet
8246 				 * as dst_ire source address.
8247 				 */
8248 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8249 				src_ipif = ipif_select_source(dst_ill, saddr,
8250 				    zoneid);
8251 				if (src_ipif == NULL) {
8252 					if (ip_debug > 2) {
8253 						pr_addr_dbg("ip_newroute: "
8254 						    "no src for dst %s ",
8255 						    AF_INET, &dst);
8256 						printf("through interface %s\n",
8257 						    dst_ill->ill_name);
8258 					}
8259 					goto icmp_err_ret;
8260 				}
8261 			} else {
8262 				src_ipif = ire->ire_ipif;
8263 				ASSERT(src_ipif != NULL);
8264 				/* hold src_ipif for uniformity */
8265 				ipif_refhold(src_ipif);
8266 			}
8267 		}
8268 
8269 		/*
8270 		 * Assign a source address while we have the conn.
8271 		 * We can't have ip_wput_ire pick a source address when the
8272 		 * packet returns from arp since we need to look at
8273 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8274 		 * going through arp.
8275 		 *
8276 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8277 		 *	  it uses ip6i to store this information.
8278 		 */
8279 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
8280 			ipha->ipha_src = src_ipif->ipif_src_addr;
8281 
8282 		if (ip_debug > 3) {
8283 			/* ip2dbg */
8284 			pr_addr_dbg("ip_newroute: first hop %s\n",
8285 			    AF_INET, &gw);
8286 		}
8287 		ip2dbg(("\tire type %s (%d)\n",
8288 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8289 
8290 		/*
8291 		 * The TTL of multirouted packets is bounded by the
8292 		 * ip_multirt_ttl ndd variable.
8293 		 */
8294 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8295 			/* Force TTL of multirouted packets */
8296 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8297 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8298 				ip2dbg(("ip_newroute: forcing multirt TTL "
8299 				    "to %d (was %d), dst 0x%08x\n",
8300 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8301 				    ntohl(sire->ire_addr)));
8302 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8303 			}
8304 		}
8305 		/*
8306 		 * At this point in ip_newroute(), ire is either the
8307 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8308 		 * destination or an IRE_INTERFACE type that should be used
8309 		 * to resolve an on-subnet destination or an on-subnet
8310 		 * next-hop gateway.
8311 		 *
8312 		 * In the IRE_CACHE case, we have the following :
8313 		 *
8314 		 * 1) src_ipif - used for getting a source address.
8315 		 *
8316 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8317 		 *    means packets using this IRE_CACHE will go out on
8318 		 *    dst_ill.
8319 		 *
8320 		 * 3) The IRE sire will point to the prefix that is the
8321 		 *    longest  matching route for the destination. These
8322 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8323 		 *
8324 		 *    The newly created IRE_CACHE entry for the off-subnet
8325 		 *    destination is tied to both the prefix route and the
8326 		 *    interface route used to resolve the next-hop gateway
8327 		 *    via the ire_phandle and ire_ihandle fields,
8328 		 *    respectively.
8329 		 *
8330 		 * In the IRE_INTERFACE case, we have the following :
8331 		 *
8332 		 * 1) src_ipif - used for getting a source address.
8333 		 *
8334 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8335 		 *    means packets using the IRE_CACHE that we will build
8336 		 *    here will go out on dst_ill.
8337 		 *
8338 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8339 		 *    to be created will only be tied to the IRE_INTERFACE
8340 		 *    that was derived from the ire_ihandle field.
8341 		 *
8342 		 *    If sire is non-NULL, it means the destination is
8343 		 *    off-link and we will first create the IRE_CACHE for the
8344 		 *    gateway. Next time through ip_newroute, we will create
8345 		 *    the IRE_CACHE for the final destination as described
8346 		 *    above.
8347 		 *
8348 		 * In both cases, after the current resolution has been
8349 		 * completed (or possibly initialised, in the IRE_INTERFACE
8350 		 * case), the loop may be re-entered to attempt the resolution
8351 		 * of another RTF_MULTIRT route.
8352 		 *
8353 		 * When an IRE_CACHE entry for the off-subnet destination is
8354 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8355 		 * for further processing in emission loops.
8356 		 */
8357 		save_ire = ire;
8358 		switch (ire->ire_type) {
8359 		case IRE_CACHE: {
8360 			ire_t	*ipif_ire;
8361 
8362 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8363 			if (gw == 0)
8364 				gw = ire->ire_gateway_addr;
8365 			/*
8366 			 * We need 3 ire's to create a new cache ire for an
8367 			 * off-link destination from the cache ire of the
8368 			 * gateway.
8369 			 *
8370 			 *	1. The prefix ire 'sire' (Note that this does
8371 			 *	   not apply to the conn_nexthop_set case)
8372 			 *	2. The cache ire of the gateway 'ire'
8373 			 *	3. The interface ire 'ipif_ire'
8374 			 *
8375 			 * We have (1) and (2). We lookup (3) below.
8376 			 *
8377 			 * If there is no interface route to the gateway,
8378 			 * it is a race condition, where we found the cache
8379 			 * but the interface route has been deleted.
8380 			 */
8381 			if (ip_nexthop) {
8382 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8383 			} else {
8384 				ipif_ire =
8385 				    ire_ihandle_lookup_offlink(ire, sire);
8386 			}
8387 			if (ipif_ire == NULL) {
8388 				ip1dbg(("ip_newroute: "
8389 				    "ire_ihandle_lookup_offlink failed\n"));
8390 				goto icmp_err_ret;
8391 			}
8392 
8393 			/*
8394 			 * Check cached gateway IRE for any security
8395 			 * attributes; if found, associate the gateway
8396 			 * credentials group to the destination IRE.
8397 			 */
8398 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8399 				mutex_enter(&attrp->igsa_lock);
8400 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8401 					GCGRP_REFHOLD(gcgrp);
8402 				mutex_exit(&attrp->igsa_lock);
8403 			}
8404 
8405 			/*
8406 			 * XXX For the source of the resolver mp,
8407 			 * we are using the same DL_UNITDATA_REQ
8408 			 * (from save_ire->ire_nce->nce_res_mp)
8409 			 * though the save_ire is not pointing at the same ill.
8410 			 * This is incorrect. We need to send it up to the
8411 			 * resolver to get the right res_mp. For ethernets
8412 			 * this may be okay (ill_type == DL_ETHER).
8413 			 */
8414 
8415 			ire = ire_create(
8416 			    (uchar_t *)&dst,		/* dest address */
8417 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8418 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8419 			    (uchar_t *)&gw,		/* gateway address */
8420 			    &save_ire->ire_max_frag,
8421 			    save_ire->ire_nce,		/* src nce */
8422 			    dst_ill->ill_rq,		/* recv-from queue */
8423 			    dst_ill->ill_wq,		/* send-to queue */
8424 			    IRE_CACHE,			/* IRE type */
8425 			    src_ipif,
8426 			    (sire != NULL) ?
8427 			    sire->ire_mask : 0, 	/* Parent mask */
8428 			    (sire != NULL) ?
8429 			    sire->ire_phandle : 0,	/* Parent handle */
8430 			    ipif_ire->ire_ihandle,	/* Interface handle */
8431 			    (sire != NULL) ? (sire->ire_flags &
8432 			    (RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8433 			    (sire != NULL) ?
8434 			    &(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8435 			    NULL,
8436 			    gcgrp,
8437 			    ipst);
8438 
8439 			if (ire == NULL) {
8440 				if (gcgrp != NULL) {
8441 					GCGRP_REFRELE(gcgrp);
8442 					gcgrp = NULL;
8443 				}
8444 				ire_refrele(ipif_ire);
8445 				ire_refrele(save_ire);
8446 				break;
8447 			}
8448 
8449 			/* reference now held by IRE */
8450 			gcgrp = NULL;
8451 
8452 			ire->ire_marks |= ire_marks;
8453 
8454 			/*
8455 			 * Prevent sire and ipif_ire from getting deleted.
8456 			 * The newly created ire is tied to both of them via
8457 			 * the phandle and ihandle respectively.
8458 			 */
8459 			if (sire != NULL) {
8460 				IRB_REFHOLD(sire->ire_bucket);
8461 				/* Has it been removed already ? */
8462 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8463 					IRB_REFRELE(sire->ire_bucket);
8464 					ire_refrele(ipif_ire);
8465 					ire_refrele(save_ire);
8466 					break;
8467 				}
8468 			}
8469 
8470 			IRB_REFHOLD(ipif_ire->ire_bucket);
8471 			/* Has it been removed already ? */
8472 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8473 				IRB_REFRELE(ipif_ire->ire_bucket);
8474 				if (sire != NULL)
8475 					IRB_REFRELE(sire->ire_bucket);
8476 				ire_refrele(ipif_ire);
8477 				ire_refrele(save_ire);
8478 				break;
8479 			}
8480 
8481 			xmit_mp = first_mp;
8482 			/*
8483 			 * In the case of multirouting, a copy
8484 			 * of the packet is done before its sending.
8485 			 * The copy is used to attempt another
8486 			 * route resolution, in a next loop.
8487 			 */
8488 			if (ire->ire_flags & RTF_MULTIRT) {
8489 				copy_mp = copymsg(first_mp);
8490 				if (copy_mp != NULL) {
8491 					xmit_mp = copy_mp;
8492 					MULTIRT_DEBUG_TAG(first_mp);
8493 				}
8494 			}
8495 			ire_add_then_send(q, ire, xmit_mp);
8496 			ire_refrele(save_ire);
8497 
8498 			/* Assert that sire is not deleted yet. */
8499 			if (sire != NULL) {
8500 				ASSERT(sire->ire_ptpn != NULL);
8501 				IRB_REFRELE(sire->ire_bucket);
8502 			}
8503 
8504 			/* Assert that ipif_ire is not deleted yet. */
8505 			ASSERT(ipif_ire->ire_ptpn != NULL);
8506 			IRB_REFRELE(ipif_ire->ire_bucket);
8507 			ire_refrele(ipif_ire);
8508 
8509 			/*
8510 			 * If copy_mp is not NULL, multirouting was
8511 			 * requested. We loop to initiate a next
8512 			 * route resolution attempt, starting from sire.
8513 			 */
8514 			if (copy_mp != NULL) {
8515 				/*
8516 				 * Search for the next unresolved
8517 				 * multirt route.
8518 				 */
8519 				copy_mp = NULL;
8520 				ipif_ire = NULL;
8521 				ire = NULL;
8522 				multirt_resolve_next = B_TRUE;
8523 				continue;
8524 			}
8525 			if (sire != NULL)
8526 				ire_refrele(sire);
8527 			ipif_refrele(src_ipif);
8528 			ill_refrele(dst_ill);
8529 			return;
8530 		}
8531 		case IRE_IF_NORESOLVER: {
8532 
8533 			if (dst_ill->ill_phys_addr_length != IP_ADDR_LEN &&
8534 			    dst_ill->ill_resolver_mp == NULL) {
8535 				ip1dbg(("ip_newroute: dst_ill %p "
8536 				    "for IRE_IF_NORESOLVER ire %p has "
8537 				    "no ill_resolver_mp\n",
8538 				    (void *)dst_ill, (void *)ire));
8539 				break;
8540 			}
8541 
8542 			/*
8543 			 * TSol note: We are creating the ire cache for the
8544 			 * destination 'dst'. If 'dst' is offlink, going
8545 			 * through the first hop 'gw', the security attributes
8546 			 * of 'dst' must be set to point to the gateway
8547 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8548 			 * is possible that 'dst' is a potential gateway that is
8549 			 * referenced by some route that has some security
8550 			 * attributes. Thus in the former case, we need to do a
8551 			 * gcgrp_lookup of 'gw' while in the latter case we
8552 			 * need to do gcgrp_lookup of 'dst' itself.
8553 			 */
8554 			ga.ga_af = AF_INET;
8555 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8556 			    &ga.ga_addr);
8557 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8558 
8559 			ire = ire_create(
8560 			    (uchar_t *)&dst,		/* dest address */
8561 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8562 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8563 			    (uchar_t *)&gw,		/* gateway address */
8564 			    &save_ire->ire_max_frag,
8565 			    NULL,			/* no src nce */
8566 			    dst_ill->ill_rq,		/* recv-from queue */
8567 			    dst_ill->ill_wq,		/* send-to queue */
8568 			    IRE_CACHE,
8569 			    src_ipif,
8570 			    save_ire->ire_mask,		/* Parent mask */
8571 			    (sire != NULL) ?		/* Parent handle */
8572 			    sire->ire_phandle : 0,
8573 			    save_ire->ire_ihandle,	/* Interface handle */
8574 			    (sire != NULL) ? sire->ire_flags &
8575 			    (RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8576 			    &(save_ire->ire_uinfo),
8577 			    NULL,
8578 			    gcgrp,
8579 			    ipst);
8580 
8581 			if (ire == NULL) {
8582 				if (gcgrp != NULL) {
8583 					GCGRP_REFRELE(gcgrp);
8584 					gcgrp = NULL;
8585 				}
8586 				ire_refrele(save_ire);
8587 				break;
8588 			}
8589 
8590 			/* reference now held by IRE */
8591 			gcgrp = NULL;
8592 
8593 			ire->ire_marks |= ire_marks;
8594 
8595 			/* Prevent save_ire from getting deleted */
8596 			IRB_REFHOLD(save_ire->ire_bucket);
8597 			/* Has it been removed already ? */
8598 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8599 				IRB_REFRELE(save_ire->ire_bucket);
8600 				ire_refrele(save_ire);
8601 				break;
8602 			}
8603 
8604 			/*
8605 			 * In the case of multirouting, a copy
8606 			 * of the packet is made before it is sent.
8607 			 * The copy is used in the next
8608 			 * loop to attempt another resolution.
8609 			 */
8610 			xmit_mp = first_mp;
8611 			if ((sire != NULL) &&
8612 			    (sire->ire_flags & RTF_MULTIRT)) {
8613 				copy_mp = copymsg(first_mp);
8614 				if (copy_mp != NULL) {
8615 					xmit_mp = copy_mp;
8616 					MULTIRT_DEBUG_TAG(first_mp);
8617 				}
8618 			}
8619 			ire_add_then_send(q, ire, xmit_mp);
8620 
8621 			/* Assert that it is not deleted yet. */
8622 			ASSERT(save_ire->ire_ptpn != NULL);
8623 			IRB_REFRELE(save_ire->ire_bucket);
8624 			ire_refrele(save_ire);
8625 
8626 			if (copy_mp != NULL) {
8627 				/*
8628 				 * If we found a (no)resolver, we ignore any
8629 				 * trailing top priority IRE_CACHE in further
8630 				 * loops. This ensures that we do not omit any
8631 				 * (no)resolver.
8632 				 * This IRE_CACHE, if any, will be processed
8633 				 * by another thread entering ip_newroute().
8634 				 * IRE_CACHE entries, if any, will be processed
8635 				 * by another thread entering ip_newroute(),
8636 				 * (upon resolver response, for instance).
8637 				 * This aims to force parallel multirt
8638 				 * resolutions as soon as a packet must be sent.
8639 				 * In the best case, after the tx of only one
8640 				 * packet, all reachable routes are resolved.
8641 				 * Otherwise, the resolution of all RTF_MULTIRT
8642 				 * routes would require several emissions.
8643 				 */
8644 				multirt_flags &= ~MULTIRT_CACHEGW;
8645 
8646 				/*
8647 				 * Search for the next unresolved multirt
8648 				 * route.
8649 				 */
8650 				copy_mp = NULL;
8651 				save_ire = NULL;
8652 				ire = NULL;
8653 				multirt_resolve_next = B_TRUE;
8654 				continue;
8655 			}
8656 
8657 			/*
8658 			 * Don't need sire anymore
8659 			 */
8660 			if (sire != NULL)
8661 				ire_refrele(sire);
8662 
8663 			ipif_refrele(src_ipif);
8664 			ill_refrele(dst_ill);
8665 			return;
8666 		}
8667 		case IRE_IF_RESOLVER:
8668 			/*
8669 			 * We can't build an IRE_CACHE yet, but at least we
8670 			 * found a resolver that can help.
8671 			 */
8672 			res_mp = dst_ill->ill_resolver_mp;
8673 			if (!OK_RESOLVER_MP(res_mp))
8674 				break;
8675 
8676 			/*
8677 			 * To be at this point in the code with a non-zero gw
8678 			 * means that dst is reachable through a gateway that
8679 			 * we have never resolved.  By changing dst to the gw
8680 			 * addr we resolve the gateway first.
8681 			 * When ire_add_then_send() tries to put the IP dg
8682 			 * to dst, it will reenter ip_newroute() at which
8683 			 * time we will find the IRE_CACHE for the gw and
8684 			 * create another IRE_CACHE in case IRE_CACHE above.
8685 			 */
8686 			if (gw != INADDR_ANY) {
8687 				/*
8688 				 * The source ipif that was determined above was
8689 				 * relative to the destination address, not the
8690 				 * gateway's. If src_ipif was not taken out of
8691 				 * the IRE_IF_RESOLVER entry, we'll need to call
8692 				 * ipif_select_source() again.
8693 				 */
8694 				if (src_ipif != ire->ire_ipif) {
8695 					ipif_refrele(src_ipif);
8696 					src_ipif = ipif_select_source(dst_ill,
8697 					    gw, zoneid);
8698 					if (src_ipif == NULL) {
8699 						if (ip_debug > 2) {
8700 							pr_addr_dbg(
8701 							    "ip_newroute: no "
8702 							    "src for gw %s ",
8703 							    AF_INET, &gw);
8704 							printf("through "
8705 							    "interface %s\n",
8706 							    dst_ill->ill_name);
8707 						}
8708 						goto icmp_err_ret;
8709 					}
8710 				}
8711 				save_dst = dst;
8712 				dst = gw;
8713 				gw = INADDR_ANY;
8714 			}
8715 
8716 			/*
8717 			 * We obtain a partial IRE_CACHE which we will pass
8718 			 * along with the resolver query.  When the response
8719 			 * comes back it will be there ready for us to add.
8720 			 * The ire_max_frag is atomically set under the
8721 			 * irebucket lock in ire_add_v[46].
8722 			 */
8723 
8724 			ire = ire_create_mp(
8725 			    (uchar_t *)&dst,		/* dest address */
8726 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8727 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8728 			    (uchar_t *)&gw,		/* gateway address */
8729 			    NULL,			/* ire_max_frag */
8730 			    NULL,			/* no src nce */
8731 			    dst_ill->ill_rq,		/* recv-from queue */
8732 			    dst_ill->ill_wq,		/* send-to queue */
8733 			    IRE_CACHE,
8734 			    src_ipif,			/* Interface ipif */
8735 			    save_ire->ire_mask,		/* Parent mask */
8736 			    0,
8737 			    save_ire->ire_ihandle,	/* Interface handle */
8738 			    0,				/* flags if any */
8739 			    &(save_ire->ire_uinfo),
8740 			    NULL,
8741 			    NULL,
8742 			    ipst);
8743 
8744 			if (ire == NULL) {
8745 				ire_refrele(save_ire);
8746 				break;
8747 			}
8748 
8749 			if ((sire != NULL) &&
8750 			    (sire->ire_flags & RTF_MULTIRT)) {
8751 				copy_mp = copymsg(first_mp);
8752 				if (copy_mp != NULL)
8753 					MULTIRT_DEBUG_TAG(copy_mp);
8754 			}
8755 
8756 			ire->ire_marks |= ire_marks;
8757 
8758 			/*
8759 			 * Construct message chain for the resolver
8760 			 * of the form:
8761 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8762 			 * Packet could contain a IPSEC_OUT mp.
8763 			 *
8764 			 * NOTE : ire will be added later when the response
8765 			 * comes back from ARP. If the response does not
8766 			 * come back, ARP frees the packet. For this reason,
8767 			 * we can't REFHOLD the bucket of save_ire to prevent
8768 			 * deletions. We may not be able to REFRELE the bucket
8769 			 * if the response never comes back. Thus, before
8770 			 * adding the ire, ire_add_v4 will make sure that the
8771 			 * interface route does not get deleted. This is the
8772 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8773 			 * where we can always prevent deletions because of
8774 			 * the synchronous nature of adding IRES i.e
8775 			 * ire_add_then_send is called after creating the IRE.
8776 			 */
8777 			ASSERT(ire->ire_mp != NULL);
8778 			ire->ire_mp->b_cont = first_mp;
8779 			/* Have saved_mp handy, for cleanup if canput fails */
8780 			saved_mp = mp;
8781 			mp = copyb(res_mp);
8782 			if (mp == NULL) {
8783 				/* Prepare for cleanup */
8784 				mp = saved_mp; /* pkt */
8785 				ire_delete(ire); /* ire_mp */
8786 				ire = NULL;
8787 				ire_refrele(save_ire);
8788 				if (copy_mp != NULL) {
8789 					MULTIRT_DEBUG_UNTAG(copy_mp);
8790 					freemsg(copy_mp);
8791 					copy_mp = NULL;
8792 				}
8793 				break;
8794 			}
8795 			linkb(mp, ire->ire_mp);
8796 
8797 			/*
8798 			 * Fill in the source and dest addrs for the resolver.
8799 			 * NOTE: this depends on memory layouts imposed by
8800 			 * ill_init().
8801 			 */
8802 			areq = (areq_t *)mp->b_rptr;
8803 			addrp = (ipaddr_t *)((char *)areq +
8804 			    areq->areq_sender_addr_offset);
8805 			if (do_attach_ill) {
8806 				/*
8807 				 * This is bind to no failover case.
8808 				 * arp packet also must go out on attach_ill.
8809 				 */
8810 				ASSERT(ipha->ipha_src != NULL);
8811 				*addrp = ipha->ipha_src;
8812 			} else {
8813 				*addrp = save_ire->ire_src_addr;
8814 			}
8815 
8816 			ire_refrele(save_ire);
8817 			addrp = (ipaddr_t *)((char *)areq +
8818 			    areq->areq_target_addr_offset);
8819 			*addrp = dst;
8820 			/* Up to the resolver. */
8821 			if (canputnext(dst_ill->ill_rq) &&
8822 			    !(dst_ill->ill_arp_closing)) {
8823 				putnext(dst_ill->ill_rq, mp);
8824 				ire = NULL;
8825 				if (copy_mp != NULL) {
8826 					/*
8827 					 * If we found a resolver, we ignore
8828 					 * any trailing top priority IRE_CACHE
8829 					 * in the further loops. This ensures
8830 					 * that we do not omit any resolver.
8831 					 * IRE_CACHE entries, if any, will be
8832 					 * processed next time we enter
8833 					 * ip_newroute().
8834 					 */
8835 					multirt_flags &= ~MULTIRT_CACHEGW;
8836 					/*
8837 					 * Search for the next unresolved
8838 					 * multirt route.
8839 					 */
8840 					first_mp = copy_mp;
8841 					copy_mp = NULL;
8842 					/* Prepare the next resolution loop. */
8843 					mp = first_mp;
8844 					EXTRACT_PKT_MP(mp, first_mp,
8845 					    mctl_present);
8846 					if (mctl_present)
8847 						io = (ipsec_out_t *)
8848 						    first_mp->b_rptr;
8849 					ipha = (ipha_t *)mp->b_rptr;
8850 
8851 					ASSERT(sire != NULL);
8852 
8853 					dst = save_dst;
8854 					multirt_resolve_next = B_TRUE;
8855 					continue;
8856 				}
8857 
8858 				if (sire != NULL)
8859 					ire_refrele(sire);
8860 
8861 				/*
8862 				 * The response will come back in ip_wput
8863 				 * with db_type IRE_DB_TYPE.
8864 				 */
8865 				ipif_refrele(src_ipif);
8866 				ill_refrele(dst_ill);
8867 				return;
8868 			} else {
8869 				/* Prepare for cleanup */
8870 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8871 				    mp);
8872 				mp->b_cont = NULL;
8873 				freeb(mp); /* areq */
8874 				/*
8875 				 * this is an ire that is not added to the
8876 				 * cache. ire_freemblk will handle the release
8877 				 * of any resources associated with the ire.
8878 				 */
8879 				ire_delete(ire); /* ire_mp */
8880 				mp = saved_mp; /* pkt */
8881 				ire = NULL;
8882 				if (copy_mp != NULL) {
8883 					MULTIRT_DEBUG_UNTAG(copy_mp);
8884 					freemsg(copy_mp);
8885 					copy_mp = NULL;
8886 				}
8887 				break;
8888 			}
8889 		default:
8890 			break;
8891 		}
8892 	} while (multirt_resolve_next);
8893 
8894 	ip1dbg(("ip_newroute: dropped\n"));
8895 	/* Did this packet originate externally? */
8896 	if (mp->b_prev) {
8897 		mp->b_next = NULL;
8898 		mp->b_prev = NULL;
8899 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
8900 	} else {
8901 		if (dst_ill != NULL) {
8902 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
8903 		} else {
8904 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
8905 		}
8906 	}
8907 	ASSERT(copy_mp == NULL);
8908 	MULTIRT_DEBUG_UNTAG(first_mp);
8909 	freemsg(first_mp);
8910 	if (ire != NULL)
8911 		ire_refrele(ire);
8912 	if (sire != NULL)
8913 		ire_refrele(sire);
8914 	if (src_ipif != NULL)
8915 		ipif_refrele(src_ipif);
8916 	if (dst_ill != NULL)
8917 		ill_refrele(dst_ill);
8918 	return;
8919 
8920 icmp_err_ret:
8921 	ip1dbg(("ip_newroute: no route\n"));
8922 	if (src_ipif != NULL)
8923 		ipif_refrele(src_ipif);
8924 	if (dst_ill != NULL)
8925 		ill_refrele(dst_ill);
8926 	if (sire != NULL)
8927 		ire_refrele(sire);
8928 	/* Did this packet originate externally? */
8929 	if (mp->b_prev) {
8930 		mp->b_next = NULL;
8931 		mp->b_prev = NULL;
8932 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
8933 		q = WR(q);
8934 	} else {
8935 		/*
8936 		 * There is no outgoing ill, so just increment the
8937 		 * system MIB.
8938 		 */
8939 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
8940 		/*
8941 		 * Since ip_wput() isn't close to finished, we fill
8942 		 * in enough of the header for credible error reporting.
8943 		 */
8944 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
8945 			/* Failed */
8946 			MULTIRT_DEBUG_UNTAG(first_mp);
8947 			freemsg(first_mp);
8948 			if (ire != NULL)
8949 				ire_refrele(ire);
8950 			return;
8951 		}
8952 	}
8953 
8954 	/*
8955 	 * At this point we will have ire only if RTF_BLACKHOLE
8956 	 * or RTF_REJECT flags are set on the IRE. It will not
8957 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8958 	 */
8959 	if (ire != NULL) {
8960 		if (ire->ire_flags & RTF_BLACKHOLE) {
8961 			ire_refrele(ire);
8962 			MULTIRT_DEBUG_UNTAG(first_mp);
8963 			freemsg(first_mp);
8964 			return;
8965 		}
8966 		ire_refrele(ire);
8967 	}
8968 	if (ip_source_routed(ipha, ipst)) {
8969 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
8970 		    zoneid, ipst);
8971 		return;
8972 	}
8973 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
8974 }
8975 
8976 ip_opt_info_t zero_info;
8977 
8978 /*
8979  * IPv4 -
8980  * ip_newroute_ipif is called by ip_wput_multicast and
8981  * ip_rput_forward_multicast whenever we need to send
8982  * out a packet to a destination address for which we do not have specific
8983  * routing information. It is used when the packet will be sent out
8984  * on a specific interface. It is also called by ip_wput() when IP_BOUND_IF
8985  * socket option is set or icmp error message wants to go out on a particular
8986  * interface for a unicast packet.
8987  *
8988  * In most cases, the destination address is resolved thanks to the ipif
8989  * intrinsic resolver. However, there are some cases where the call to
8990  * ip_newroute_ipif must take into account the potential presence of
8991  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
8992  * that uses the interface. This is specified through flags,
8993  * which can be a combination of:
8994  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
8995  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
8996  *   and flags. Additionally, the packet source address has to be set to
8997  *   the specified address. The caller is thus expected to set this flag
8998  *   if the packet has no specific source address yet.
8999  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
9000  *   flag, the resulting ire will inherit the flag. All unresolved routes
9001  *   to the destination must be explored in the same call to
9002  *   ip_newroute_ipif().
9003  */
9004 static void
9005 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
9006     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
9007 {
9008 	areq_t	*areq;
9009 	ire_t	*ire = NULL;
9010 	mblk_t	*res_mp;
9011 	ipaddr_t *addrp;
9012 	mblk_t *first_mp;
9013 	ire_t	*save_ire = NULL;
9014 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
9015 	ipif_t	*src_ipif = NULL;
9016 	ushort_t ire_marks = 0;
9017 	ill_t	*dst_ill = NULL;
9018 	boolean_t mctl_present;
9019 	ipsec_out_t *io;
9020 	ipha_t *ipha;
9021 	int	ihandle = 0;
9022 	mblk_t	*saved_mp;
9023 	ire_t   *fire = NULL;
9024 	mblk_t  *copy_mp = NULL;
9025 	boolean_t multirt_resolve_next;
9026 	boolean_t unspec_src;
9027 	ipaddr_t ipha_dst;
9028 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
9029 
9030 	/*
9031 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
9032 	 * here for uniformity
9033 	 */
9034 	ipif_refhold(ipif);
9035 
9036 	/*
9037 	 * This loop is run only once in most cases.
9038 	 * We loop to resolve further routes only when the destination
9039 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
9040 	 */
9041 	do {
9042 		if (dst_ill != NULL) {
9043 			ill_refrele(dst_ill);
9044 			dst_ill = NULL;
9045 		}
9046 		if (src_ipif != NULL) {
9047 			ipif_refrele(src_ipif);
9048 			src_ipif = NULL;
9049 		}
9050 		multirt_resolve_next = B_FALSE;
9051 
9052 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9053 		    ipif->ipif_ill->ill_name));
9054 
9055 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
9056 		if (mctl_present)
9057 			io = (ipsec_out_t *)first_mp->b_rptr;
9058 
9059 		ipha = (ipha_t *)mp->b_rptr;
9060 
9061 		/*
9062 		 * Save the packet destination address, we may need it after
9063 		 * the packet has been consumed.
9064 		 */
9065 		ipha_dst = ipha->ipha_dst;
9066 
9067 		/*
9068 		 * If the interface is a pt-pt interface we look for an
9069 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9070 		 * local_address and the pt-pt destination address. Otherwise
9071 		 * we just match the local address.
9072 		 * NOTE: dst could be different than ipha->ipha_dst in case
9073 		 * of sending igmp multicast packets over a point-to-point
9074 		 * connection.
9075 		 * Thus we must be careful enough to check ipha_dst to be a
9076 		 * multicast address, otherwise it will take xmit_if path for
9077 		 * multicast packets resulting into kernel stack overflow by
9078 		 * repeated calls to ip_newroute_ipif from ire_send().
9079 		 */
9080 		if (CLASSD(ipha_dst) &&
9081 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9082 			goto err_ret;
9083 		}
9084 
9085 		/*
9086 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9087 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9088 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9089 		 * propagate its flags to the new ire.
9090 		 */
9091 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9092 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9093 			ip2dbg(("ip_newroute_ipif: "
9094 			    "ipif_lookup_multi_ire("
9095 			    "ipif %p, dst %08x) = fire %p\n",
9096 			    (void *)ipif, ntohl(dst), (void *)fire));
9097 		}
9098 
9099 		if (mctl_present && io->ipsec_out_attach_if) {
9100 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
9101 			    io->ipsec_out_ill_index, B_FALSE, ipst);
9102 
9103 			/* Failure case frees things for us. */
9104 			if (attach_ill == NULL) {
9105 				ipif_refrele(ipif);
9106 				if (fire != NULL)
9107 					ire_refrele(fire);
9108 				return;
9109 			}
9110 
9111 			/*
9112 			 * Check if we need an ire that will not be
9113 			 * looked up by anybody else i.e. HIDDEN.
9114 			 */
9115 			if (ill_is_probeonly(attach_ill)) {
9116 				ire_marks = IRE_MARK_HIDDEN;
9117 			}
9118 			/*
9119 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
9120 			 * case.
9121 			 */
9122 			dst_ill = ipif->ipif_ill;
9123 			/* attach_ill has been refheld by ip_grab_attach_ill */
9124 			ASSERT(dst_ill == attach_ill);
9125 		} else {
9126 			/*
9127 			 * If the interface belongs to an interface group,
9128 			 * make sure the next possible interface in the group
9129 			 * is used.  This encourages load spreading among
9130 			 * peers in an interface group.
9131 			 * Note: load spreading is disabled for RTF_MULTIRT
9132 			 * routes.
9133 			 */
9134 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9135 			    (fire->ire_flags & RTF_MULTIRT)) {
9136 				/*
9137 				 * Don't perform outbound load spreading
9138 				 * in the case of an RTF_MULTIRT issued route,
9139 				 * we actually typically want to replicate
9140 				 * outgoing packets through particular
9141 				 * interfaces.
9142 				 */
9143 				dst_ill = ipif->ipif_ill;
9144 				ill_refhold(dst_ill);
9145 			} else {
9146 				dst_ill = ip_newroute_get_dst_ill(
9147 				    ipif->ipif_ill);
9148 			}
9149 			if (dst_ill == NULL) {
9150 				if (ip_debug > 2) {
9151 					pr_addr_dbg("ip_newroute_ipif: "
9152 					    "no dst ill for dst %s\n",
9153 					    AF_INET, &dst);
9154 				}
9155 				goto err_ret;
9156 			}
9157 		}
9158 
9159 		/*
9160 		 * Pick a source address preferring non-deprecated ones.
9161 		 * Unlike ip_newroute, we don't do any source address
9162 		 * selection here since for multicast it really does not help
9163 		 * in inbound load spreading as in the unicast case.
9164 		 */
9165 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9166 		    (fire->ire_flags & RTF_SETSRC)) {
9167 			/*
9168 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9169 			 * on that interface. This ire has RTF_SETSRC flag, so
9170 			 * the source address of the packet must be changed.
9171 			 * Check that the ipif matching the requested source
9172 			 * address still exists.
9173 			 */
9174 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9175 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9176 		}
9177 
9178 		unspec_src = (connp != NULL && connp->conn_unspec_src);
9179 
9180 		if (((!ipif->ipif_isv6 && ipif->ipif_lcl_addr == INADDR_ANY) ||
9181 		    (ipif->ipif_flags & (IPIF_DEPRECATED|IPIF_UP)) != IPIF_UP ||
9182 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9183 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9184 		    (src_ipif == NULL) &&
9185 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
9186 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9187 			if (src_ipif == NULL) {
9188 				if (ip_debug > 2) {
9189 					/* ip1dbg */
9190 					pr_addr_dbg("ip_newroute_ipif: "
9191 					    "no src for dst %s",
9192 					    AF_INET, &dst);
9193 				}
9194 				ip1dbg((" through interface %s\n",
9195 				    dst_ill->ill_name));
9196 				goto err_ret;
9197 			}
9198 			ipif_refrele(ipif);
9199 			ipif = src_ipif;
9200 			ipif_refhold(ipif);
9201 		}
9202 		if (src_ipif == NULL) {
9203 			src_ipif = ipif;
9204 			ipif_refhold(src_ipif);
9205 		}
9206 
9207 		/*
9208 		 * Assign a source address while we have the conn.
9209 		 * We can't have ip_wput_ire pick a source address when the
9210 		 * packet returns from arp since conn_unspec_src might be set
9211 		 * and we lose the conn when going through arp.
9212 		 */
9213 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
9214 			ipha->ipha_src = src_ipif->ipif_src_addr;
9215 
9216 		/*
9217 		 * In the case of IP_BOUND_IF and IP_PKTINFO, it is possible
9218 		 * that the outgoing interface does not have an interface ire.
9219 		 */
9220 		if (CLASSD(ipha_dst) && (connp == NULL ||
9221 		    connp->conn_outgoing_ill == NULL) &&
9222 		    infop->ip_opt_ill_index == 0) {
9223 			/* ipif_to_ire returns an held ire */
9224 			ire = ipif_to_ire(ipif);
9225 			if (ire == NULL)
9226 				goto err_ret;
9227 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9228 				goto err_ret;
9229 			/*
9230 			 * ihandle is needed when the ire is added to
9231 			 * cache table.
9232 			 */
9233 			save_ire = ire;
9234 			ihandle = save_ire->ire_ihandle;
9235 
9236 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9237 			    "flags %04x\n",
9238 			    (void *)ire, (void *)ipif, flags));
9239 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9240 			    (fire->ire_flags & RTF_MULTIRT)) {
9241 				/*
9242 				 * As requested by flags, an IRE_OFFSUBNET was
9243 				 * looked up on that interface. This ire has
9244 				 * RTF_MULTIRT flag, so the resolution loop will
9245 				 * be re-entered to resolve additional routes on
9246 				 * other interfaces. For that purpose, a copy of
9247 				 * the packet is performed at this point.
9248 				 */
9249 				fire->ire_last_used_time = lbolt;
9250 				copy_mp = copymsg(first_mp);
9251 				if (copy_mp) {
9252 					MULTIRT_DEBUG_TAG(copy_mp);
9253 				}
9254 			}
9255 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9256 			    (fire->ire_flags & RTF_SETSRC)) {
9257 				/*
9258 				 * As requested by flags, an IRE_OFFSUBET was
9259 				 * looked up on that interface. This ire has
9260 				 * RTF_SETSRC flag, so the source address of the
9261 				 * packet must be changed.
9262 				 */
9263 				ipha->ipha_src = fire->ire_src_addr;
9264 			}
9265 		} else {
9266 			ASSERT((connp == NULL) ||
9267 			    (connp->conn_outgoing_ill != NULL) ||
9268 			    (connp->conn_dontroute) ||
9269 			    infop->ip_opt_ill_index != 0);
9270 			/*
9271 			 * The only ways we can come here are:
9272 			 * 1) IP_BOUND_IF socket option is set
9273 			 * 2) SO_DONTROUTE socket option is set
9274 			 * 3) IP_PKTINFO option is passed in as ancillary data.
9275 			 * In all cases, the new ire will not be added
9276 			 * into cache table.
9277 			 */
9278 			ire_marks |= IRE_MARK_NOADD;
9279 		}
9280 
9281 		switch (ipif->ipif_net_type) {
9282 		case IRE_IF_NORESOLVER: {
9283 			/* We have what we need to build an IRE_CACHE. */
9284 
9285 			if ((dst_ill->ill_phys_addr_length != IP_ADDR_LEN) &&
9286 			    (dst_ill->ill_resolver_mp == NULL)) {
9287 				ip1dbg(("ip_newroute_ipif: dst_ill %p "
9288 				    "for IRE_IF_NORESOLVER ire %p has "
9289 				    "no ill_resolver_mp\n",
9290 				    (void *)dst_ill, (void *)ire));
9291 				break;
9292 			}
9293 
9294 			/*
9295 			 * The new ire inherits the IRE_OFFSUBNET flags
9296 			 * and source address, if this was requested.
9297 			 */
9298 			ire = ire_create(
9299 			    (uchar_t *)&dst,		/* dest address */
9300 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9301 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9302 			    NULL,			/* gateway address */
9303 			    &ipif->ipif_mtu,
9304 			    NULL,			/* no src nce */
9305 			    dst_ill->ill_rq,		/* recv-from queue */
9306 			    dst_ill->ill_wq,		/* send-to queue */
9307 			    IRE_CACHE,
9308 			    src_ipif,
9309 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9310 			    (fire != NULL) ?		/* Parent handle */
9311 			    fire->ire_phandle : 0,
9312 			    ihandle,			/* Interface handle */
9313 			    (fire != NULL) ?
9314 			    (fire->ire_flags &
9315 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9316 			    (save_ire == NULL ? &ire_uinfo_null :
9317 			    &save_ire->ire_uinfo),
9318 			    NULL,
9319 			    NULL,
9320 			    ipst);
9321 
9322 			if (ire == NULL) {
9323 				if (save_ire != NULL)
9324 					ire_refrele(save_ire);
9325 				break;
9326 			}
9327 
9328 			ire->ire_marks |= ire_marks;
9329 
9330 			/*
9331 			 * If IRE_MARK_NOADD is set then we need to convert
9332 			 * the max_fragp to a useable value now. This is
9333 			 * normally done in ire_add_v[46]. We also need to
9334 			 * associate the ire with an nce (normally would be
9335 			 * done in ip_wput_nondata()).
9336 			 *
9337 			 * Note that IRE_MARK_NOADD packets created here
9338 			 * do not have a non-null ire_mp pointer. The null
9339 			 * value of ire_bucket indicates that they were
9340 			 * never added.
9341 			 */
9342 			if (ire->ire_marks & IRE_MARK_NOADD) {
9343 				uint_t  max_frag;
9344 
9345 				max_frag = *ire->ire_max_fragp;
9346 				ire->ire_max_fragp = NULL;
9347 				ire->ire_max_frag = max_frag;
9348 
9349 				if ((ire->ire_nce = ndp_lookup_v4(
9350 				    ire_to_ill(ire),
9351 				    (ire->ire_gateway_addr != INADDR_ANY ?
9352 				    &ire->ire_gateway_addr : &ire->ire_addr),
9353 				    B_FALSE)) == NULL) {
9354 					if (save_ire != NULL)
9355 						ire_refrele(save_ire);
9356 					break;
9357 				}
9358 				ASSERT(ire->ire_nce->nce_state ==
9359 				    ND_REACHABLE);
9360 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9361 			}
9362 
9363 			/* Prevent save_ire from getting deleted */
9364 			if (save_ire != NULL) {
9365 				IRB_REFHOLD(save_ire->ire_bucket);
9366 				/* Has it been removed already ? */
9367 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9368 					IRB_REFRELE(save_ire->ire_bucket);
9369 					ire_refrele(save_ire);
9370 					break;
9371 				}
9372 			}
9373 
9374 			ire_add_then_send(q, ire, first_mp);
9375 
9376 			/* Assert that save_ire is not deleted yet. */
9377 			if (save_ire != NULL) {
9378 				ASSERT(save_ire->ire_ptpn != NULL);
9379 				IRB_REFRELE(save_ire->ire_bucket);
9380 				ire_refrele(save_ire);
9381 				save_ire = NULL;
9382 			}
9383 			if (fire != NULL) {
9384 				ire_refrele(fire);
9385 				fire = NULL;
9386 			}
9387 
9388 			/*
9389 			 * the resolution loop is re-entered if this
9390 			 * was requested through flags and if we
9391 			 * actually are in a multirouting case.
9392 			 */
9393 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9394 				boolean_t need_resolve =
9395 				    ire_multirt_need_resolve(ipha_dst,
9396 				    MBLK_GETLABEL(copy_mp), ipst);
9397 				if (!need_resolve) {
9398 					MULTIRT_DEBUG_UNTAG(copy_mp);
9399 					freemsg(copy_mp);
9400 					copy_mp = NULL;
9401 				} else {
9402 					/*
9403 					 * ipif_lookup_group() calls
9404 					 * ire_lookup_multi() that uses
9405 					 * ire_ftable_lookup() to find
9406 					 * an IRE_INTERFACE for the group.
9407 					 * In the multirt case,
9408 					 * ire_lookup_multi() then invokes
9409 					 * ire_multirt_lookup() to find
9410 					 * the next resolvable ire.
9411 					 * As a result, we obtain an new
9412 					 * interface, derived from the
9413 					 * next ire.
9414 					 */
9415 					ipif_refrele(ipif);
9416 					ipif = ipif_lookup_group(ipha_dst,
9417 					    zoneid, ipst);
9418 					ip2dbg(("ip_newroute_ipif: "
9419 					    "multirt dst %08x, ipif %p\n",
9420 					    htonl(dst), (void *)ipif));
9421 					if (ipif != NULL) {
9422 						mp = copy_mp;
9423 						copy_mp = NULL;
9424 						multirt_resolve_next = B_TRUE;
9425 						continue;
9426 					} else {
9427 						freemsg(copy_mp);
9428 					}
9429 				}
9430 			}
9431 			if (ipif != NULL)
9432 				ipif_refrele(ipif);
9433 			ill_refrele(dst_ill);
9434 			ipif_refrele(src_ipif);
9435 			return;
9436 		}
9437 		case IRE_IF_RESOLVER:
9438 			/*
9439 			 * We can't build an IRE_CACHE yet, but at least
9440 			 * we found a resolver that can help.
9441 			 */
9442 			res_mp = dst_ill->ill_resolver_mp;
9443 			if (!OK_RESOLVER_MP(res_mp))
9444 				break;
9445 
9446 			/*
9447 			 * We obtain a partial IRE_CACHE which we will pass
9448 			 * along with the resolver query.  When the response
9449 			 * comes back it will be there ready for us to add.
9450 			 * The new ire inherits the IRE_OFFSUBNET flags
9451 			 * and source address, if this was requested.
9452 			 * The ire_max_frag is atomically set under the
9453 			 * irebucket lock in ire_add_v[46]. Only in the
9454 			 * case of IRE_MARK_NOADD, we set it here itself.
9455 			 */
9456 			ire = ire_create_mp(
9457 			    (uchar_t *)&dst,		/* dest address */
9458 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9459 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9460 			    NULL,			/* gateway address */
9461 			    (ire_marks & IRE_MARK_NOADD) ?
9462 			    ipif->ipif_mtu : 0,		/* max_frag */
9463 			    NULL,			/* no src nce */
9464 			    dst_ill->ill_rq,		/* recv-from queue */
9465 			    dst_ill->ill_wq,		/* send-to queue */
9466 			    IRE_CACHE,
9467 			    src_ipif,
9468 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9469 			    (fire != NULL) ?		/* Parent handle */
9470 			    fire->ire_phandle : 0,
9471 			    ihandle,			/* Interface handle */
9472 			    (fire != NULL) ?		/* flags if any */
9473 			    (fire->ire_flags &
9474 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9475 			    (save_ire == NULL ? &ire_uinfo_null :
9476 			    &save_ire->ire_uinfo),
9477 			    NULL,
9478 			    NULL,
9479 			    ipst);
9480 
9481 			if (save_ire != NULL) {
9482 				ire_refrele(save_ire);
9483 				save_ire = NULL;
9484 			}
9485 			if (ire == NULL)
9486 				break;
9487 
9488 			ire->ire_marks |= ire_marks;
9489 			/*
9490 			 * Construct message chain for the resolver of the
9491 			 * form:
9492 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9493 			 *
9494 			 * NOTE : ire will be added later when the response
9495 			 * comes back from ARP. If the response does not
9496 			 * come back, ARP frees the packet. For this reason,
9497 			 * we can't REFHOLD the bucket of save_ire to prevent
9498 			 * deletions. We may not be able to REFRELE the
9499 			 * bucket if the response never comes back.
9500 			 * Thus, before adding the ire, ire_add_v4 will make
9501 			 * sure that the interface route does not get deleted.
9502 			 * This is the only case unlike ip_newroute_v6,
9503 			 * ip_newroute_ipif_v6 where we can always prevent
9504 			 * deletions because ire_add_then_send is called after
9505 			 * creating the IRE.
9506 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9507 			 * does not add this IRE into the IRE CACHE.
9508 			 */
9509 			ASSERT(ire->ire_mp != NULL);
9510 			ire->ire_mp->b_cont = first_mp;
9511 			/* Have saved_mp handy, for cleanup if canput fails */
9512 			saved_mp = mp;
9513 			mp = copyb(res_mp);
9514 			if (mp == NULL) {
9515 				/* Prepare for cleanup */
9516 				mp = saved_mp; /* pkt */
9517 				ire_delete(ire); /* ire_mp */
9518 				ire = NULL;
9519 				if (copy_mp != NULL) {
9520 					MULTIRT_DEBUG_UNTAG(copy_mp);
9521 					freemsg(copy_mp);
9522 					copy_mp = NULL;
9523 				}
9524 				break;
9525 			}
9526 			linkb(mp, ire->ire_mp);
9527 
9528 			/*
9529 			 * Fill in the source and dest addrs for the resolver.
9530 			 * NOTE: this depends on memory layouts imposed by
9531 			 * ill_init().
9532 			 */
9533 			areq = (areq_t *)mp->b_rptr;
9534 			addrp = (ipaddr_t *)((char *)areq +
9535 			    areq->areq_sender_addr_offset);
9536 			*addrp = ire->ire_src_addr;
9537 			addrp = (ipaddr_t *)((char *)areq +
9538 			    areq->areq_target_addr_offset);
9539 			*addrp = dst;
9540 			/* Up to the resolver. */
9541 			if (canputnext(dst_ill->ill_rq) &&
9542 			    !(dst_ill->ill_arp_closing)) {
9543 				putnext(dst_ill->ill_rq, mp);
9544 				/*
9545 				 * The response will come back in ip_wput
9546 				 * with db_type IRE_DB_TYPE.
9547 				 */
9548 			} else {
9549 				mp->b_cont = NULL;
9550 				freeb(mp); /* areq */
9551 				ire_delete(ire); /* ire_mp */
9552 				saved_mp->b_next = NULL;
9553 				saved_mp->b_prev = NULL;
9554 				freemsg(first_mp); /* pkt */
9555 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9556 			}
9557 
9558 			if (fire != NULL) {
9559 				ire_refrele(fire);
9560 				fire = NULL;
9561 			}
9562 
9563 
9564 			/*
9565 			 * The resolution loop is re-entered if this was
9566 			 * requested through flags and we actually are
9567 			 * in a multirouting case.
9568 			 */
9569 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9570 				boolean_t need_resolve =
9571 				    ire_multirt_need_resolve(ipha_dst,
9572 				    MBLK_GETLABEL(copy_mp), ipst);
9573 				if (!need_resolve) {
9574 					MULTIRT_DEBUG_UNTAG(copy_mp);
9575 					freemsg(copy_mp);
9576 					copy_mp = NULL;
9577 				} else {
9578 					/*
9579 					 * ipif_lookup_group() calls
9580 					 * ire_lookup_multi() that uses
9581 					 * ire_ftable_lookup() to find
9582 					 * an IRE_INTERFACE for the group.
9583 					 * In the multirt case,
9584 					 * ire_lookup_multi() then invokes
9585 					 * ire_multirt_lookup() to find
9586 					 * the next resolvable ire.
9587 					 * As a result, we obtain an new
9588 					 * interface, derived from the
9589 					 * next ire.
9590 					 */
9591 					ipif_refrele(ipif);
9592 					ipif = ipif_lookup_group(ipha_dst,
9593 					    zoneid, ipst);
9594 					if (ipif != NULL) {
9595 						mp = copy_mp;
9596 						copy_mp = NULL;
9597 						multirt_resolve_next = B_TRUE;
9598 						continue;
9599 					} else {
9600 						freemsg(copy_mp);
9601 					}
9602 				}
9603 			}
9604 			if (ipif != NULL)
9605 				ipif_refrele(ipif);
9606 			ill_refrele(dst_ill);
9607 			ipif_refrele(src_ipif);
9608 			return;
9609 		default:
9610 			break;
9611 		}
9612 	} while (multirt_resolve_next);
9613 
9614 err_ret:
9615 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9616 	if (fire != NULL)
9617 		ire_refrele(fire);
9618 	ipif_refrele(ipif);
9619 	/* Did this packet originate externally? */
9620 	if (dst_ill != NULL)
9621 		ill_refrele(dst_ill);
9622 	if (src_ipif != NULL)
9623 		ipif_refrele(src_ipif);
9624 	if (mp->b_prev || mp->b_next) {
9625 		mp->b_next = NULL;
9626 		mp->b_prev = NULL;
9627 	} else {
9628 		/*
9629 		 * Since ip_wput() isn't close to finished, we fill
9630 		 * in enough of the header for credible error reporting.
9631 		 */
9632 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9633 			/* Failed */
9634 			freemsg(first_mp);
9635 			if (ire != NULL)
9636 				ire_refrele(ire);
9637 			return;
9638 		}
9639 	}
9640 	/*
9641 	 * At this point we will have ire only if RTF_BLACKHOLE
9642 	 * or RTF_REJECT flags are set on the IRE. It will not
9643 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9644 	 */
9645 	if (ire != NULL) {
9646 		if (ire->ire_flags & RTF_BLACKHOLE) {
9647 			ire_refrele(ire);
9648 			freemsg(first_mp);
9649 			return;
9650 		}
9651 		ire_refrele(ire);
9652 	}
9653 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9654 }
9655 
9656 /* Name/Value Table Lookup Routine */
9657 char *
9658 ip_nv_lookup(nv_t *nv, int value)
9659 {
9660 	if (!nv)
9661 		return (NULL);
9662 	for (; nv->nv_name; nv++) {
9663 		if (nv->nv_value == value)
9664 			return (nv->nv_name);
9665 	}
9666 	return ("unknown");
9667 }
9668 
9669 /*
9670  * This is a module open, i.e. this is a control stream for access
9671  * to a DLPI device.  We allocate an ill_t as the instance data in
9672  * this case.
9673  */
9674 int
9675 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9676 {
9677 	ill_t	*ill;
9678 	int	err;
9679 	zoneid_t zoneid;
9680 	netstack_t *ns;
9681 	ip_stack_t *ipst;
9682 
9683 	/*
9684 	 * Prevent unprivileged processes from pushing IP so that
9685 	 * they can't send raw IP.
9686 	 */
9687 	if (secpolicy_net_rawaccess(credp) != 0)
9688 		return (EPERM);
9689 
9690 	ns = netstack_find_by_cred(credp);
9691 	ASSERT(ns != NULL);
9692 	ipst = ns->netstack_ip;
9693 	ASSERT(ipst != NULL);
9694 
9695 	/*
9696 	 * For exclusive stacks we set the zoneid to zero
9697 	 * to make IP operate as if in the global zone.
9698 	 */
9699 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9700 		zoneid = GLOBAL_ZONEID;
9701 	else
9702 		zoneid = crgetzoneid(credp);
9703 
9704 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9705 	q->q_ptr = WR(q)->q_ptr = ill;
9706 	ill->ill_ipst = ipst;
9707 	ill->ill_zoneid = zoneid;
9708 
9709 	/*
9710 	 * ill_init initializes the ill fields and then sends down
9711 	 * down a DL_INFO_REQ after calling qprocson.
9712 	 */
9713 	err = ill_init(q, ill);
9714 	if (err != 0) {
9715 		mi_free(ill);
9716 		netstack_rele(ipst->ips_netstack);
9717 		q->q_ptr = NULL;
9718 		WR(q)->q_ptr = NULL;
9719 		return (err);
9720 	}
9721 
9722 	/* ill_init initializes the ipsq marking this thread as writer */
9723 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
9724 	/* Wait for the DL_INFO_ACK */
9725 	mutex_enter(&ill->ill_lock);
9726 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9727 		/*
9728 		 * Return value of 0 indicates a pending signal.
9729 		 */
9730 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9731 		if (err == 0) {
9732 			mutex_exit(&ill->ill_lock);
9733 			(void) ip_close(q, 0);
9734 			return (EINTR);
9735 		}
9736 	}
9737 	mutex_exit(&ill->ill_lock);
9738 
9739 	/*
9740 	 * ip_rput_other could have set an error  in ill_error on
9741 	 * receipt of M_ERROR.
9742 	 */
9743 
9744 	err = ill->ill_error;
9745 	if (err != 0) {
9746 		(void) ip_close(q, 0);
9747 		return (err);
9748 	}
9749 
9750 	ill->ill_credp = credp;
9751 	crhold(credp);
9752 
9753 	mutex_enter(&ipst->ips_ip_mi_lock);
9754 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
9755 	    credp);
9756 	mutex_exit(&ipst->ips_ip_mi_lock);
9757 	if (err) {
9758 		(void) ip_close(q, 0);
9759 		return (err);
9760 	}
9761 	return (0);
9762 }
9763 
9764 /* For /dev/ip aka AF_INET open */
9765 int
9766 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9767 {
9768 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
9769 }
9770 
9771 /* For /dev/ip6 aka AF_INET6 open */
9772 int
9773 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9774 {
9775 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
9776 }
9777 
9778 /* IP open routine. */
9779 int
9780 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9781     boolean_t isv6)
9782 {
9783 	conn_t 		*connp;
9784 	major_t		maj;
9785 	zoneid_t	zoneid;
9786 	netstack_t	*ns;
9787 	ip_stack_t	*ipst;
9788 
9789 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9790 
9791 	/* Allow reopen. */
9792 	if (q->q_ptr != NULL)
9793 		return (0);
9794 
9795 	if (sflag & MODOPEN) {
9796 		/* This is a module open */
9797 		return (ip_modopen(q, devp, flag, sflag, credp));
9798 	}
9799 
9800 	ns = netstack_find_by_cred(credp);
9801 	ASSERT(ns != NULL);
9802 	ipst = ns->netstack_ip;
9803 	ASSERT(ipst != NULL);
9804 
9805 	/*
9806 	 * For exclusive stacks we set the zoneid to zero
9807 	 * to make IP operate as if in the global zone.
9808 	 */
9809 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9810 		zoneid = GLOBAL_ZONEID;
9811 	else
9812 		zoneid = crgetzoneid(credp);
9813 
9814 	/*
9815 	 * We are opening as a device. This is an IP client stream, and we
9816 	 * allocate an conn_t as the instance data.
9817 	 */
9818 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
9819 
9820 	/*
9821 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
9822 	 * done by netstack_find_by_cred()
9823 	 */
9824 	netstack_rele(ipst->ips_netstack);
9825 
9826 	connp->conn_zoneid = zoneid;
9827 
9828 	connp->conn_upq = q;
9829 	q->q_ptr = WR(q)->q_ptr = connp;
9830 
9831 	if (flag & SO_SOCKSTR)
9832 		connp->conn_flags |= IPCL_SOCKET;
9833 
9834 	/* Minor tells us which /dev entry was opened */
9835 	if (isv6) {
9836 		connp->conn_flags |= IPCL_ISV6;
9837 		connp->conn_af_isv6 = B_TRUE;
9838 		ip_setpktversion(connp, isv6, B_FALSE, ipst);
9839 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9840 	} else {
9841 		connp->conn_af_isv6 = B_FALSE;
9842 		connp->conn_pkt_isv6 = B_FALSE;
9843 	}
9844 
9845 	if ((connp->conn_dev = inet_minor_alloc(ip_minor_arena)) == 0) {
9846 		/* CONN_DEC_REF takes care of netstack_rele() */
9847 		q->q_ptr = WR(q)->q_ptr = NULL;
9848 		CONN_DEC_REF(connp);
9849 		return (EBUSY);
9850 	}
9851 
9852 	maj = getemajor(*devp);
9853 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9854 
9855 	/*
9856 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9857 	 */
9858 	connp->conn_cred = credp;
9859 
9860 	/*
9861 	 * Handle IP_RTS_REQUEST and other ioctls which use conn_recv
9862 	 */
9863 	connp->conn_recv = ip_conn_input;
9864 
9865 	crhold(connp->conn_cred);
9866 
9867 	/*
9868 	 * If the caller has the process-wide flag set, then default to MAC
9869 	 * exempt mode.  This allows read-down to unlabeled hosts.
9870 	 */
9871 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9872 		connp->conn_mac_exempt = B_TRUE;
9873 
9874 	connp->conn_rq = q;
9875 	connp->conn_wq = WR(q);
9876 
9877 	/* Non-zero default values */
9878 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9879 
9880 	/*
9881 	 * Make the conn globally visible to walkers
9882 	 */
9883 	ASSERT(connp->conn_ref == 1);
9884 	mutex_enter(&connp->conn_lock);
9885 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9886 	mutex_exit(&connp->conn_lock);
9887 
9888 	qprocson(q);
9889 
9890 	return (0);
9891 }
9892 
9893 /*
9894  * Change the output format (IPv4 vs. IPv6) for a conn_t.
9895  * Note that there is no race since either ip_output function works - it
9896  * is just an optimization to enter the best ip_output routine directly.
9897  */
9898 void
9899 ip_setpktversion(conn_t *connp, boolean_t isv6, boolean_t bump_mib,
9900     ip_stack_t *ipst)
9901 {
9902 	if (isv6)  {
9903 		if (bump_mib) {
9904 			BUMP_MIB(&ipst->ips_ip6_mib,
9905 			    ipIfStatsOutSwitchIPVersion);
9906 		}
9907 		connp->conn_send = ip_output_v6;
9908 		connp->conn_pkt_isv6 = B_TRUE;
9909 	} else {
9910 		if (bump_mib) {
9911 			BUMP_MIB(&ipst->ips_ip_mib,
9912 			    ipIfStatsOutSwitchIPVersion);
9913 		}
9914 		connp->conn_send = ip_output;
9915 		connp->conn_pkt_isv6 = B_FALSE;
9916 	}
9917 
9918 }
9919 
9920 /*
9921  * See if IPsec needs loading because of the options in mp.
9922  */
9923 static boolean_t
9924 ipsec_opt_present(mblk_t *mp)
9925 {
9926 	uint8_t *optcp, *next_optcp, *opt_endcp;
9927 	struct opthdr *opt;
9928 	struct T_opthdr *topt;
9929 	int opthdr_len;
9930 	t_uscalar_t optname, optlevel;
9931 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9932 	ipsec_req_t *ipsr;
9933 
9934 	/*
9935 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9936 	 * return TRUE.
9937 	 */
9938 
9939 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9940 	opt_endcp = optcp + tor->OPT_length;
9941 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9942 		opthdr_len = sizeof (struct T_opthdr);
9943 	} else {		/* O_OPTMGMT_REQ */
9944 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9945 		opthdr_len = sizeof (struct opthdr);
9946 	}
9947 	for (; optcp < opt_endcp; optcp = next_optcp) {
9948 		if (optcp + opthdr_len > opt_endcp)
9949 			return (B_FALSE);	/* Not enough option header. */
9950 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9951 			topt = (struct T_opthdr *)optcp;
9952 			optlevel = topt->level;
9953 			optname = topt->name;
9954 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9955 		} else {
9956 			opt = (struct opthdr *)optcp;
9957 			optlevel = opt->level;
9958 			optname = opt->name;
9959 			next_optcp = optcp + opthdr_len +
9960 			    _TPI_ALIGN_OPT(opt->len);
9961 		}
9962 		if ((next_optcp < optcp) || /* wraparound pointer space */
9963 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9964 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9965 			return (B_FALSE); /* bad option buffer */
9966 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9967 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9968 			/*
9969 			 * Check to see if it's an all-bypass or all-zeroes
9970 			 * IPsec request.  Don't bother loading IPsec if
9971 			 * the socket doesn't want to use it.  (A good example
9972 			 * is a bypass request.)
9973 			 *
9974 			 * Basically, if any of the non-NEVER bits are set,
9975 			 * load IPsec.
9976 			 */
9977 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
9978 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
9979 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
9980 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
9981 			    != 0)
9982 				return (B_TRUE);
9983 		}
9984 	}
9985 	return (B_FALSE);
9986 }
9987 
9988 /*
9989  * If conn is is waiting for ipsec to finish loading, kick it.
9990  */
9991 /* ARGSUSED */
9992 static void
9993 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
9994 {
9995 	t_scalar_t	optreq_prim;
9996 	mblk_t		*mp;
9997 	cred_t		*cr;
9998 	int		err = 0;
9999 
10000 	/*
10001 	 * This function is called, after ipsec loading is complete.
10002 	 * Since IP checks exclusively and atomically (i.e it prevents
10003 	 * ipsec load from completing until ip_optcom_req completes)
10004 	 * whether ipsec load is complete, there cannot be a race with IP
10005 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
10006 	 */
10007 	mutex_enter(&connp->conn_lock);
10008 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
10009 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
10010 		mp = connp->conn_ipsec_opt_mp;
10011 		connp->conn_ipsec_opt_mp = NULL;
10012 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
10013 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
10014 		mutex_exit(&connp->conn_lock);
10015 
10016 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
10017 
10018 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
10019 		if (optreq_prim == T_OPTMGMT_REQ) {
10020 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10021 			    &ip_opt_obj, B_FALSE);
10022 		} else {
10023 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
10024 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10025 			    &ip_opt_obj, B_FALSE);
10026 		}
10027 		if (err != EINPROGRESS)
10028 			CONN_OPER_PENDING_DONE(connp);
10029 		return;
10030 	}
10031 	mutex_exit(&connp->conn_lock);
10032 }
10033 
10034 /*
10035  * Called from the ipsec_loader thread, outside any perimeter, to tell
10036  * ip qenable any of the queues waiting for the ipsec loader to
10037  * complete.
10038  */
10039 void
10040 ip_ipsec_load_complete(ipsec_stack_t *ipss)
10041 {
10042 	netstack_t *ns = ipss->ipsec_netstack;
10043 
10044 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
10045 }
10046 
10047 /*
10048  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10049  * determines the grp on which it has to become exclusive, queues the mp
10050  * and sq draining restarts the optmgmt
10051  */
10052 static boolean_t
10053 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10054 {
10055 	conn_t *connp = Q_TO_CONN(q);
10056 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
10057 
10058 	/*
10059 	 * Take IPsec requests and treat them special.
10060 	 */
10061 	if (ipsec_opt_present(mp)) {
10062 		/* First check if IPsec is loaded. */
10063 		mutex_enter(&ipss->ipsec_loader_lock);
10064 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
10065 			mutex_exit(&ipss->ipsec_loader_lock);
10066 			return (B_FALSE);
10067 		}
10068 		mutex_enter(&connp->conn_lock);
10069 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10070 
10071 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10072 		connp->conn_ipsec_opt_mp = mp;
10073 		mutex_exit(&connp->conn_lock);
10074 		mutex_exit(&ipss->ipsec_loader_lock);
10075 
10076 		ipsec_loader_loadnow(ipss);
10077 		return (B_TRUE);
10078 	}
10079 	return (B_FALSE);
10080 }
10081 
10082 /*
10083  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10084  * all of them are copied to the conn_t. If the req is "zero", the policy is
10085  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10086  * fields.
10087  * We keep only the latest setting of the policy and thus policy setting
10088  * is not incremental/cumulative.
10089  *
10090  * Requests to set policies with multiple alternative actions will
10091  * go through a different API.
10092  */
10093 int
10094 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10095 {
10096 	uint_t ah_req = 0;
10097 	uint_t esp_req = 0;
10098 	uint_t se_req = 0;
10099 	ipsec_selkey_t sel;
10100 	ipsec_act_t *actp = NULL;
10101 	uint_t nact;
10102 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
10103 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
10104 	ipsec_policy_root_t *pr;
10105 	ipsec_policy_head_t *ph;
10106 	int fam;
10107 	boolean_t is_pol_reset;
10108 	int error = 0;
10109 	netstack_t	*ns = connp->conn_netstack;
10110 	ip_stack_t	*ipst = ns->netstack_ip;
10111 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10112 
10113 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10114 
10115 	/*
10116 	 * The IP_SEC_OPT option does not allow variable length parameters,
10117 	 * hence a request cannot be NULL.
10118 	 */
10119 	if (req == NULL)
10120 		return (EINVAL);
10121 
10122 	ah_req = req->ipsr_ah_req;
10123 	esp_req = req->ipsr_esp_req;
10124 	se_req = req->ipsr_self_encap_req;
10125 
10126 	/*
10127 	 * Are we dealing with a request to reset the policy (i.e.
10128 	 * zero requests).
10129 	 */
10130 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10131 	    (esp_req & REQ_MASK) == 0 &&
10132 	    (se_req & REQ_MASK) == 0);
10133 
10134 	if (!is_pol_reset) {
10135 		/*
10136 		 * If we couldn't load IPsec, fail with "protocol
10137 		 * not supported".
10138 		 * IPsec may not have been loaded for a request with zero
10139 		 * policies, so we don't fail in this case.
10140 		 */
10141 		mutex_enter(&ipss->ipsec_loader_lock);
10142 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10143 			mutex_exit(&ipss->ipsec_loader_lock);
10144 			return (EPROTONOSUPPORT);
10145 		}
10146 		mutex_exit(&ipss->ipsec_loader_lock);
10147 
10148 		/*
10149 		 * Test for valid requests. Invalid algorithms
10150 		 * need to be tested by IPsec code because new
10151 		 * algorithms can be added dynamically.
10152 		 */
10153 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10154 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10155 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10156 			return (EINVAL);
10157 		}
10158 
10159 		/*
10160 		 * Only privileged users can issue these
10161 		 * requests.
10162 		 */
10163 		if (((ah_req & IPSEC_PREF_NEVER) ||
10164 		    (esp_req & IPSEC_PREF_NEVER) ||
10165 		    (se_req & IPSEC_PREF_NEVER)) &&
10166 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10167 			return (EPERM);
10168 		}
10169 
10170 		/*
10171 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10172 		 * are mutually exclusive.
10173 		 */
10174 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10175 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10176 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10177 			/* Both of them are set */
10178 			return (EINVAL);
10179 		}
10180 	}
10181 
10182 	mutex_enter(&connp->conn_lock);
10183 
10184 	/*
10185 	 * If we have already cached policies in ip_bind_connected*(), don't
10186 	 * let them change now. We cache policies for connections
10187 	 * whose src,dst [addr, port] is known.
10188 	 */
10189 	if (connp->conn_policy_cached) {
10190 		mutex_exit(&connp->conn_lock);
10191 		return (EINVAL);
10192 	}
10193 
10194 	/*
10195 	 * We have a zero policies, reset the connection policy if already
10196 	 * set. This will cause the connection to inherit the
10197 	 * global policy, if any.
10198 	 */
10199 	if (is_pol_reset) {
10200 		if (connp->conn_policy != NULL) {
10201 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10202 			connp->conn_policy = NULL;
10203 		}
10204 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10205 		connp->conn_in_enforce_policy = B_FALSE;
10206 		connp->conn_out_enforce_policy = B_FALSE;
10207 		mutex_exit(&connp->conn_lock);
10208 		return (0);
10209 	}
10210 
10211 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10212 	    ipst->ips_netstack);
10213 	if (ph == NULL)
10214 		goto enomem;
10215 
10216 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10217 	if (actp == NULL)
10218 		goto enomem;
10219 
10220 	/*
10221 	 * Always allocate IPv4 policy entries, since they can also
10222 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10223 	 */
10224 	bzero(&sel, sizeof (sel));
10225 	sel.ipsl_valid = IPSL_IPV4;
10226 
10227 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10228 	    ipst->ips_netstack);
10229 	if (pin4 == NULL)
10230 		goto enomem;
10231 
10232 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10233 	    ipst->ips_netstack);
10234 	if (pout4 == NULL)
10235 		goto enomem;
10236 
10237 	if (connp->conn_af_isv6) {
10238 		/*
10239 		 * We're looking at a v6 socket, also allocate the
10240 		 * v6-specific entries...
10241 		 */
10242 		sel.ipsl_valid = IPSL_IPV6;
10243 		pin6 = ipsec_policy_create(&sel, actp, nact,
10244 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10245 		if (pin6 == NULL)
10246 			goto enomem;
10247 
10248 		pout6 = ipsec_policy_create(&sel, actp, nact,
10249 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10250 		if (pout6 == NULL)
10251 			goto enomem;
10252 
10253 		/*
10254 		 * .. and file them away in the right place.
10255 		 */
10256 		fam = IPSEC_AF_V6;
10257 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10258 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10259 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10260 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10261 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10262 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10263 	}
10264 
10265 	ipsec_actvec_free(actp, nact);
10266 
10267 	/*
10268 	 * File the v4 policies.
10269 	 */
10270 	fam = IPSEC_AF_V4;
10271 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10272 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10273 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10274 
10275 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10276 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10277 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10278 
10279 	/*
10280 	 * If the requests need security, set enforce_policy.
10281 	 * If the requests are IPSEC_PREF_NEVER, one should
10282 	 * still set conn_out_enforce_policy so that an ipsec_out
10283 	 * gets attached in ip_wput. This is needed so that
10284 	 * for connections that we don't cache policy in ip_bind,
10285 	 * if global policy matches in ip_wput_attach_policy, we
10286 	 * don't wrongly inherit global policy. Similarly, we need
10287 	 * to set conn_in_enforce_policy also so that we don't verify
10288 	 * policy wrongly.
10289 	 */
10290 	if ((ah_req & REQ_MASK) != 0 ||
10291 	    (esp_req & REQ_MASK) != 0 ||
10292 	    (se_req & REQ_MASK) != 0) {
10293 		connp->conn_in_enforce_policy = B_TRUE;
10294 		connp->conn_out_enforce_policy = B_TRUE;
10295 		connp->conn_flags |= IPCL_CHECK_POLICY;
10296 	}
10297 
10298 	mutex_exit(&connp->conn_lock);
10299 	return (error);
10300 #undef REQ_MASK
10301 
10302 	/*
10303 	 * Common memory-allocation-failure exit path.
10304 	 */
10305 enomem:
10306 	mutex_exit(&connp->conn_lock);
10307 	if (actp != NULL)
10308 		ipsec_actvec_free(actp, nact);
10309 	if (pin4 != NULL)
10310 		IPPOL_REFRELE(pin4, ipst->ips_netstack);
10311 	if (pout4 != NULL)
10312 		IPPOL_REFRELE(pout4, ipst->ips_netstack);
10313 	if (pin6 != NULL)
10314 		IPPOL_REFRELE(pin6, ipst->ips_netstack);
10315 	if (pout6 != NULL)
10316 		IPPOL_REFRELE(pout6, ipst->ips_netstack);
10317 	return (ENOMEM);
10318 }
10319 
10320 /*
10321  * Only for options that pass in an IP addr. Currently only V4 options
10322  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10323  * So this function assumes level is IPPROTO_IP
10324  */
10325 int
10326 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10327     mblk_t *first_mp)
10328 {
10329 	ipif_t *ipif = NULL;
10330 	int error;
10331 	ill_t *ill;
10332 	int zoneid;
10333 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10334 
10335 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10336 
10337 	if (addr != INADDR_ANY || checkonly) {
10338 		ASSERT(connp != NULL);
10339 		zoneid = IPCL_ZONEID(connp);
10340 		if (option == IP_NEXTHOP) {
10341 			ipif = ipif_lookup_onlink_addr(addr,
10342 			    connp->conn_zoneid, ipst);
10343 		} else {
10344 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10345 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10346 			    &error, ipst);
10347 		}
10348 		if (ipif == NULL) {
10349 			if (error == EINPROGRESS)
10350 				return (error);
10351 			else if ((option == IP_MULTICAST_IF) ||
10352 			    (option == IP_NEXTHOP))
10353 				return (EHOSTUNREACH);
10354 			else
10355 				return (EINVAL);
10356 		} else if (checkonly) {
10357 			if (option == IP_MULTICAST_IF) {
10358 				ill = ipif->ipif_ill;
10359 				/* not supported by the virtual network iface */
10360 				if (IS_VNI(ill)) {
10361 					ipif_refrele(ipif);
10362 					return (EINVAL);
10363 				}
10364 			}
10365 			ipif_refrele(ipif);
10366 			return (0);
10367 		}
10368 		ill = ipif->ipif_ill;
10369 		mutex_enter(&connp->conn_lock);
10370 		mutex_enter(&ill->ill_lock);
10371 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10372 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10373 			mutex_exit(&ill->ill_lock);
10374 			mutex_exit(&connp->conn_lock);
10375 			ipif_refrele(ipif);
10376 			return (option == IP_MULTICAST_IF ?
10377 			    EHOSTUNREACH : EINVAL);
10378 		}
10379 	} else {
10380 		mutex_enter(&connp->conn_lock);
10381 	}
10382 
10383 	/* None of the options below are supported on the VNI */
10384 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10385 		mutex_exit(&ill->ill_lock);
10386 		mutex_exit(&connp->conn_lock);
10387 		ipif_refrele(ipif);
10388 		return (EINVAL);
10389 	}
10390 
10391 	switch (option) {
10392 	case IP_DONTFAILOVER_IF:
10393 		/*
10394 		 * This option is used by in.mpathd to ensure
10395 		 * that IPMP probe packets only go out on the
10396 		 * test interfaces. in.mpathd sets this option
10397 		 * on the non-failover interfaces.
10398 		 * For backward compatibility, this option
10399 		 * implicitly sets IP_MULTICAST_IF, as used
10400 		 * be done in bind(), so that ip_wput gets
10401 		 * this ipif to send mcast packets.
10402 		 */
10403 		if (ipif != NULL) {
10404 			ASSERT(addr != INADDR_ANY);
10405 			connp->conn_nofailover_ill = ipif->ipif_ill;
10406 			connp->conn_multicast_ipif = ipif;
10407 		} else {
10408 			ASSERT(addr == INADDR_ANY);
10409 			connp->conn_nofailover_ill = NULL;
10410 			connp->conn_multicast_ipif = NULL;
10411 		}
10412 		break;
10413 
10414 	case IP_MULTICAST_IF:
10415 		connp->conn_multicast_ipif = ipif;
10416 		break;
10417 	case IP_NEXTHOP:
10418 		connp->conn_nexthop_v4 = addr;
10419 		connp->conn_nexthop_set = B_TRUE;
10420 		break;
10421 	}
10422 
10423 	if (ipif != NULL) {
10424 		mutex_exit(&ill->ill_lock);
10425 		mutex_exit(&connp->conn_lock);
10426 		ipif_refrele(ipif);
10427 		return (0);
10428 	}
10429 	mutex_exit(&connp->conn_lock);
10430 	/* We succeded in cleared the option */
10431 	return (0);
10432 }
10433 
10434 /*
10435  * For options that pass in an ifindex specifying the ill. V6 options always
10436  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10437  */
10438 int
10439 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10440     int level, int option, mblk_t *first_mp)
10441 {
10442 	ill_t *ill = NULL;
10443 	int error = 0;
10444 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10445 
10446 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10447 	if (ifindex != 0) {
10448 		ASSERT(connp != NULL);
10449 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10450 		    first_mp, ip_restart_optmgmt, &error, ipst);
10451 		if (ill != NULL) {
10452 			if (checkonly) {
10453 				/* not supported by the virtual network iface */
10454 				if (IS_VNI(ill)) {
10455 					ill_refrele(ill);
10456 					return (EINVAL);
10457 				}
10458 				ill_refrele(ill);
10459 				return (0);
10460 			}
10461 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
10462 			    0, NULL)) {
10463 				ill_refrele(ill);
10464 				ill = NULL;
10465 				mutex_enter(&connp->conn_lock);
10466 				goto setit;
10467 			}
10468 			mutex_enter(&connp->conn_lock);
10469 			mutex_enter(&ill->ill_lock);
10470 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10471 				mutex_exit(&ill->ill_lock);
10472 				mutex_exit(&connp->conn_lock);
10473 				ill_refrele(ill);
10474 				ill = NULL;
10475 				mutex_enter(&connp->conn_lock);
10476 			}
10477 			goto setit;
10478 		} else if (error == EINPROGRESS) {
10479 			return (error);
10480 		} else {
10481 			error = 0;
10482 		}
10483 	}
10484 	mutex_enter(&connp->conn_lock);
10485 setit:
10486 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10487 
10488 	/*
10489 	 * The options below assume that the ILL (if any) transmits and/or
10490 	 * receives traffic. Neither of which is true for the virtual network
10491 	 * interface, so fail setting these on a VNI.
10492 	 */
10493 	if (IS_VNI(ill)) {
10494 		ASSERT(ill != NULL);
10495 		mutex_exit(&ill->ill_lock);
10496 		mutex_exit(&connp->conn_lock);
10497 		ill_refrele(ill);
10498 		return (EINVAL);
10499 	}
10500 
10501 	if (level == IPPROTO_IP) {
10502 		switch (option) {
10503 		case IP_BOUND_IF:
10504 			connp->conn_incoming_ill = ill;
10505 			connp->conn_outgoing_ill = ill;
10506 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10507 			    0 : ifindex;
10508 			break;
10509 
10510 		case IP_MULTICAST_IF:
10511 			/*
10512 			 * This option is an internal special. The socket
10513 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10514 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10515 			 * specifies an ifindex and we try first on V6 ill's.
10516 			 * If we don't find one, we they try using on v4 ill's
10517 			 * intenally and we come here.
10518 			 */
10519 			if (!checkonly && ill != NULL) {
10520 				ipif_t	*ipif;
10521 				ipif = ill->ill_ipif;
10522 
10523 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10524 					mutex_exit(&ill->ill_lock);
10525 					mutex_exit(&connp->conn_lock);
10526 					ill_refrele(ill);
10527 					ill = NULL;
10528 					mutex_enter(&connp->conn_lock);
10529 				} else {
10530 					connp->conn_multicast_ipif = ipif;
10531 				}
10532 			}
10533 			break;
10534 
10535 		case IP_DHCPINIT_IF:
10536 			if (connp->conn_dhcpinit_ill != NULL) {
10537 				/*
10538 				 * We've locked the conn so conn_cleanup_ill()
10539 				 * cannot clear conn_dhcpinit_ill -- so it's
10540 				 * safe to access the ill.
10541 				 */
10542 				ill_t *oill = connp->conn_dhcpinit_ill;
10543 
10544 				ASSERT(oill->ill_dhcpinit != 0);
10545 				atomic_dec_32(&oill->ill_dhcpinit);
10546 				connp->conn_dhcpinit_ill = NULL;
10547 			}
10548 
10549 			if (ill != NULL) {
10550 				connp->conn_dhcpinit_ill = ill;
10551 				atomic_inc_32(&ill->ill_dhcpinit);
10552 			}
10553 			break;
10554 		}
10555 	} else {
10556 		switch (option) {
10557 		case IPV6_BOUND_IF:
10558 			connp->conn_incoming_ill = ill;
10559 			connp->conn_outgoing_ill = ill;
10560 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10561 			    0 : ifindex;
10562 			break;
10563 
10564 		case IPV6_BOUND_PIF:
10565 			/*
10566 			 * Limit all transmit to this ill.
10567 			 * Unlike IPV6_BOUND_IF, using this option
10568 			 * prevents load spreading and failover from
10569 			 * happening when the interface is part of the
10570 			 * group. That's why we don't need to remember
10571 			 * the ifindex in orig_bound_ifindex as in
10572 			 * IPV6_BOUND_IF.
10573 			 */
10574 			connp->conn_outgoing_pill = ill;
10575 			break;
10576 
10577 		case IPV6_DONTFAILOVER_IF:
10578 			/*
10579 			 * This option is used by in.mpathd to ensure
10580 			 * that IPMP probe packets only go out on the
10581 			 * test interfaces. in.mpathd sets this option
10582 			 * on the non-failover interfaces.
10583 			 */
10584 			connp->conn_nofailover_ill = ill;
10585 			/*
10586 			 * For backward compatibility, this option
10587 			 * implicitly sets ip_multicast_ill as used in
10588 			 * IPV6_MULTICAST_IF so that ip_wput gets
10589 			 * this ill to send mcast packets.
10590 			 */
10591 			connp->conn_multicast_ill = ill;
10592 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
10593 			    0 : ifindex;
10594 			break;
10595 
10596 		case IPV6_MULTICAST_IF:
10597 			/*
10598 			 * Set conn_multicast_ill to be the IPv6 ill.
10599 			 * Set conn_multicast_ipif to be an IPv4 ipif
10600 			 * for ifindex to make IPv4 mapped addresses
10601 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10602 			 * Even if no IPv6 ill exists for the ifindex
10603 			 * we need to check for an IPv4 ifindex in order
10604 			 * for this to work with mapped addresses. In that
10605 			 * case only set conn_multicast_ipif.
10606 			 */
10607 			if (!checkonly) {
10608 				if (ifindex == 0) {
10609 					connp->conn_multicast_ill = NULL;
10610 					connp->conn_orig_multicast_ifindex = 0;
10611 					connp->conn_multicast_ipif = NULL;
10612 				} else if (ill != NULL) {
10613 					connp->conn_multicast_ill = ill;
10614 					connp->conn_orig_multicast_ifindex =
10615 					    ifindex;
10616 				}
10617 			}
10618 			break;
10619 		}
10620 	}
10621 
10622 	if (ill != NULL) {
10623 		mutex_exit(&ill->ill_lock);
10624 		mutex_exit(&connp->conn_lock);
10625 		ill_refrele(ill);
10626 		return (0);
10627 	}
10628 	mutex_exit(&connp->conn_lock);
10629 	/*
10630 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10631 	 * locate the ill and could not set the option (ifindex != 0)
10632 	 */
10633 	return (ifindex == 0 ? 0 : EINVAL);
10634 }
10635 
10636 /* This routine sets socket options. */
10637 /* ARGSUSED */
10638 int
10639 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10640     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10641     void *dummy, cred_t *cr, mblk_t *first_mp)
10642 {
10643 	int		*i1 = (int *)invalp;
10644 	conn_t		*connp = Q_TO_CONN(q);
10645 	int		error = 0;
10646 	boolean_t	checkonly;
10647 	ire_t		*ire;
10648 	boolean_t	found;
10649 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10650 
10651 	switch (optset_context) {
10652 
10653 	case SETFN_OPTCOM_CHECKONLY:
10654 		checkonly = B_TRUE;
10655 		/*
10656 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10657 		 * inlen != 0 implies value supplied and
10658 		 * 	we have to "pretend" to set it.
10659 		 * inlen == 0 implies that there is no
10660 		 * 	value part in T_CHECK request and just validation
10661 		 * done elsewhere should be enough, we just return here.
10662 		 */
10663 		if (inlen == 0) {
10664 			*outlenp = 0;
10665 			return (0);
10666 		}
10667 		break;
10668 	case SETFN_OPTCOM_NEGOTIATE:
10669 	case SETFN_UD_NEGOTIATE:
10670 	case SETFN_CONN_NEGOTIATE:
10671 		checkonly = B_FALSE;
10672 		break;
10673 	default:
10674 		/*
10675 		 * We should never get here
10676 		 */
10677 		*outlenp = 0;
10678 		return (EINVAL);
10679 	}
10680 
10681 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10682 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10683 
10684 	/*
10685 	 * For fixed length options, no sanity check
10686 	 * of passed in length is done. It is assumed *_optcom_req()
10687 	 * routines do the right thing.
10688 	 */
10689 
10690 	switch (level) {
10691 	case SOL_SOCKET:
10692 		/*
10693 		 * conn_lock protects the bitfields, and is used to
10694 		 * set the fields atomically.
10695 		 */
10696 		switch (name) {
10697 		case SO_BROADCAST:
10698 			if (!checkonly) {
10699 				/* TODO: use value someplace? */
10700 				mutex_enter(&connp->conn_lock);
10701 				connp->conn_broadcast = *i1 ? 1 : 0;
10702 				mutex_exit(&connp->conn_lock);
10703 			}
10704 			break;	/* goto sizeof (int) option return */
10705 		case SO_USELOOPBACK:
10706 			if (!checkonly) {
10707 				/* TODO: use value someplace? */
10708 				mutex_enter(&connp->conn_lock);
10709 				connp->conn_loopback = *i1 ? 1 : 0;
10710 				mutex_exit(&connp->conn_lock);
10711 			}
10712 			break;	/* goto sizeof (int) option return */
10713 		case SO_DONTROUTE:
10714 			if (!checkonly) {
10715 				mutex_enter(&connp->conn_lock);
10716 				connp->conn_dontroute = *i1 ? 1 : 0;
10717 				mutex_exit(&connp->conn_lock);
10718 			}
10719 			break;	/* goto sizeof (int) option return */
10720 		case SO_REUSEADDR:
10721 			if (!checkonly) {
10722 				mutex_enter(&connp->conn_lock);
10723 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10724 				mutex_exit(&connp->conn_lock);
10725 			}
10726 			break;	/* goto sizeof (int) option return */
10727 		case SO_PROTOTYPE:
10728 			if (!checkonly) {
10729 				mutex_enter(&connp->conn_lock);
10730 				connp->conn_proto = *i1;
10731 				mutex_exit(&connp->conn_lock);
10732 			}
10733 			break;	/* goto sizeof (int) option return */
10734 		case SO_ALLZONES:
10735 			if (!checkonly) {
10736 				mutex_enter(&connp->conn_lock);
10737 				if (IPCL_IS_BOUND(connp)) {
10738 					mutex_exit(&connp->conn_lock);
10739 					return (EINVAL);
10740 				}
10741 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10742 				mutex_exit(&connp->conn_lock);
10743 			}
10744 			break;	/* goto sizeof (int) option return */
10745 		case SO_ANON_MLP:
10746 			if (!checkonly) {
10747 				mutex_enter(&connp->conn_lock);
10748 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10749 				mutex_exit(&connp->conn_lock);
10750 			}
10751 			break;	/* goto sizeof (int) option return */
10752 		case SO_MAC_EXEMPT:
10753 			if (secpolicy_net_mac_aware(cr) != 0 ||
10754 			    IPCL_IS_BOUND(connp))
10755 				return (EACCES);
10756 			if (!checkonly) {
10757 				mutex_enter(&connp->conn_lock);
10758 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10759 				mutex_exit(&connp->conn_lock);
10760 			}
10761 			break;	/* goto sizeof (int) option return */
10762 		default:
10763 			/*
10764 			 * "soft" error (negative)
10765 			 * option not handled at this level
10766 			 * Note: Do not modify *outlenp
10767 			 */
10768 			return (-EINVAL);
10769 		}
10770 		break;
10771 	case IPPROTO_IP:
10772 		switch (name) {
10773 		case IP_NEXTHOP:
10774 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
10775 				return (EPERM);
10776 			/* FALLTHRU */
10777 		case IP_MULTICAST_IF:
10778 		case IP_DONTFAILOVER_IF: {
10779 			ipaddr_t addr = *i1;
10780 
10781 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10782 			    first_mp);
10783 			if (error != 0)
10784 				return (error);
10785 			break;	/* goto sizeof (int) option return */
10786 		}
10787 
10788 		case IP_MULTICAST_TTL:
10789 			/* Recorded in transport above IP */
10790 			*outvalp = *invalp;
10791 			*outlenp = sizeof (uchar_t);
10792 			return (0);
10793 		case IP_MULTICAST_LOOP:
10794 			if (!checkonly) {
10795 				mutex_enter(&connp->conn_lock);
10796 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10797 				mutex_exit(&connp->conn_lock);
10798 			}
10799 			*outvalp = *invalp;
10800 			*outlenp = sizeof (uchar_t);
10801 			return (0);
10802 		case IP_ADD_MEMBERSHIP:
10803 		case MCAST_JOIN_GROUP:
10804 		case IP_DROP_MEMBERSHIP:
10805 		case MCAST_LEAVE_GROUP: {
10806 			struct ip_mreq *mreqp;
10807 			struct group_req *greqp;
10808 			ire_t *ire;
10809 			boolean_t done = B_FALSE;
10810 			ipaddr_t group, ifaddr;
10811 			struct sockaddr_in *sin;
10812 			uint32_t *ifindexp;
10813 			boolean_t mcast_opt = B_TRUE;
10814 			mcast_record_t fmode;
10815 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10816 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10817 
10818 			switch (name) {
10819 			case IP_ADD_MEMBERSHIP:
10820 				mcast_opt = B_FALSE;
10821 				/* FALLTHRU */
10822 			case MCAST_JOIN_GROUP:
10823 				fmode = MODE_IS_EXCLUDE;
10824 				optfn = ip_opt_add_group;
10825 				break;
10826 
10827 			case IP_DROP_MEMBERSHIP:
10828 				mcast_opt = B_FALSE;
10829 				/* FALLTHRU */
10830 			case MCAST_LEAVE_GROUP:
10831 				fmode = MODE_IS_INCLUDE;
10832 				optfn = ip_opt_delete_group;
10833 				break;
10834 			}
10835 
10836 			if (mcast_opt) {
10837 				greqp = (struct group_req *)i1;
10838 				sin = (struct sockaddr_in *)&greqp->gr_group;
10839 				if (sin->sin_family != AF_INET) {
10840 					*outlenp = 0;
10841 					return (ENOPROTOOPT);
10842 				}
10843 				group = (ipaddr_t)sin->sin_addr.s_addr;
10844 				ifaddr = INADDR_ANY;
10845 				ifindexp = &greqp->gr_interface;
10846 			} else {
10847 				mreqp = (struct ip_mreq *)i1;
10848 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10849 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10850 				ifindexp = NULL;
10851 			}
10852 
10853 			/*
10854 			 * In the multirouting case, we need to replicate
10855 			 * the request on all interfaces that will take part
10856 			 * in replication.  We do so because multirouting is
10857 			 * reflective, thus we will probably receive multi-
10858 			 * casts on those interfaces.
10859 			 * The ip_multirt_apply_membership() succeeds if the
10860 			 * operation succeeds on at least one interface.
10861 			 */
10862 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10863 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10864 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10865 			if (ire != NULL) {
10866 				if (ire->ire_flags & RTF_MULTIRT) {
10867 					error = ip_multirt_apply_membership(
10868 					    optfn, ire, connp, checkonly, group,
10869 					    fmode, INADDR_ANY, first_mp);
10870 					done = B_TRUE;
10871 				}
10872 				ire_refrele(ire);
10873 			}
10874 			if (!done) {
10875 				error = optfn(connp, checkonly, group, ifaddr,
10876 				    ifindexp, fmode, INADDR_ANY, first_mp);
10877 			}
10878 			if (error) {
10879 				/*
10880 				 * EINPROGRESS is a soft error, needs retry
10881 				 * so don't make *outlenp zero.
10882 				 */
10883 				if (error != EINPROGRESS)
10884 					*outlenp = 0;
10885 				return (error);
10886 			}
10887 			/* OK return - copy input buffer into output buffer */
10888 			if (invalp != outvalp) {
10889 				/* don't trust bcopy for identical src/dst */
10890 				bcopy(invalp, outvalp, inlen);
10891 			}
10892 			*outlenp = inlen;
10893 			return (0);
10894 		}
10895 		case IP_BLOCK_SOURCE:
10896 		case IP_UNBLOCK_SOURCE:
10897 		case IP_ADD_SOURCE_MEMBERSHIP:
10898 		case IP_DROP_SOURCE_MEMBERSHIP:
10899 		case MCAST_BLOCK_SOURCE:
10900 		case MCAST_UNBLOCK_SOURCE:
10901 		case MCAST_JOIN_SOURCE_GROUP:
10902 		case MCAST_LEAVE_SOURCE_GROUP: {
10903 			struct ip_mreq_source *imreqp;
10904 			struct group_source_req *gsreqp;
10905 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10906 			uint32_t ifindex = 0;
10907 			mcast_record_t fmode;
10908 			struct sockaddr_in *sin;
10909 			ire_t *ire;
10910 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10911 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10912 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10913 
10914 			switch (name) {
10915 			case IP_BLOCK_SOURCE:
10916 				mcast_opt = B_FALSE;
10917 				/* FALLTHRU */
10918 			case MCAST_BLOCK_SOURCE:
10919 				fmode = MODE_IS_EXCLUDE;
10920 				optfn = ip_opt_add_group;
10921 				break;
10922 
10923 			case IP_UNBLOCK_SOURCE:
10924 				mcast_opt = B_FALSE;
10925 				/* FALLTHRU */
10926 			case MCAST_UNBLOCK_SOURCE:
10927 				fmode = MODE_IS_EXCLUDE;
10928 				optfn = ip_opt_delete_group;
10929 				break;
10930 
10931 			case IP_ADD_SOURCE_MEMBERSHIP:
10932 				mcast_opt = B_FALSE;
10933 				/* FALLTHRU */
10934 			case MCAST_JOIN_SOURCE_GROUP:
10935 				fmode = MODE_IS_INCLUDE;
10936 				optfn = ip_opt_add_group;
10937 				break;
10938 
10939 			case IP_DROP_SOURCE_MEMBERSHIP:
10940 				mcast_opt = B_FALSE;
10941 				/* FALLTHRU */
10942 			case MCAST_LEAVE_SOURCE_GROUP:
10943 				fmode = MODE_IS_INCLUDE;
10944 				optfn = ip_opt_delete_group;
10945 				break;
10946 			}
10947 
10948 			if (mcast_opt) {
10949 				gsreqp = (struct group_source_req *)i1;
10950 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10951 					*outlenp = 0;
10952 					return (ENOPROTOOPT);
10953 				}
10954 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10955 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10956 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10957 				src = (ipaddr_t)sin->sin_addr.s_addr;
10958 				ifindex = gsreqp->gsr_interface;
10959 			} else {
10960 				imreqp = (struct ip_mreq_source *)i1;
10961 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10962 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10963 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10964 			}
10965 
10966 			/*
10967 			 * In the multirouting case, we need to replicate
10968 			 * the request as noted in the mcast cases above.
10969 			 */
10970 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10971 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10972 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10973 			if (ire != NULL) {
10974 				if (ire->ire_flags & RTF_MULTIRT) {
10975 					error = ip_multirt_apply_membership(
10976 					    optfn, ire, connp, checkonly, grp,
10977 					    fmode, src, first_mp);
10978 					done = B_TRUE;
10979 				}
10980 				ire_refrele(ire);
10981 			}
10982 			if (!done) {
10983 				error = optfn(connp, checkonly, grp, ifaddr,
10984 				    &ifindex, fmode, src, first_mp);
10985 			}
10986 			if (error != 0) {
10987 				/*
10988 				 * EINPROGRESS is a soft error, needs retry
10989 				 * so don't make *outlenp zero.
10990 				 */
10991 				if (error != EINPROGRESS)
10992 					*outlenp = 0;
10993 				return (error);
10994 			}
10995 			/* OK return - copy input buffer into output buffer */
10996 			if (invalp != outvalp) {
10997 				bcopy(invalp, outvalp, inlen);
10998 			}
10999 			*outlenp = inlen;
11000 			return (0);
11001 		}
11002 		case IP_SEC_OPT:
11003 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11004 			if (error != 0) {
11005 				*outlenp = 0;
11006 				return (error);
11007 			}
11008 			break;
11009 		case IP_HDRINCL:
11010 		case IP_OPTIONS:
11011 		case T_IP_OPTIONS:
11012 		case IP_TOS:
11013 		case T_IP_TOS:
11014 		case IP_TTL:
11015 		case IP_RECVDSTADDR:
11016 		case IP_RECVOPTS:
11017 			/* OK return - copy input buffer into output buffer */
11018 			if (invalp != outvalp) {
11019 				/* don't trust bcopy for identical src/dst */
11020 				bcopy(invalp, outvalp, inlen);
11021 			}
11022 			*outlenp = inlen;
11023 			return (0);
11024 		case IP_RECVIF:
11025 			/* Retrieve the inbound interface index */
11026 			if (!checkonly) {
11027 				mutex_enter(&connp->conn_lock);
11028 				connp->conn_recvif = *i1 ? 1 : 0;
11029 				mutex_exit(&connp->conn_lock);
11030 			}
11031 			break;	/* goto sizeof (int) option return */
11032 		case IP_RECVPKTINFO:
11033 			if (!checkonly) {
11034 				mutex_enter(&connp->conn_lock);
11035 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11036 				mutex_exit(&connp->conn_lock);
11037 			}
11038 			break;	/* goto sizeof (int) option return */
11039 		case IP_RECVSLLA:
11040 			/* Retrieve the source link layer address */
11041 			if (!checkonly) {
11042 				mutex_enter(&connp->conn_lock);
11043 				connp->conn_recvslla = *i1 ? 1 : 0;
11044 				mutex_exit(&connp->conn_lock);
11045 			}
11046 			break;	/* goto sizeof (int) option return */
11047 		case MRT_INIT:
11048 		case MRT_DONE:
11049 		case MRT_ADD_VIF:
11050 		case MRT_DEL_VIF:
11051 		case MRT_ADD_MFC:
11052 		case MRT_DEL_MFC:
11053 		case MRT_ASSERT:
11054 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
11055 				*outlenp = 0;
11056 				return (error);
11057 			}
11058 			error = ip_mrouter_set((int)name, q, checkonly,
11059 			    (uchar_t *)invalp, inlen, first_mp);
11060 			if (error) {
11061 				*outlenp = 0;
11062 				return (error);
11063 			}
11064 			/* OK return - copy input buffer into output buffer */
11065 			if (invalp != outvalp) {
11066 				/* don't trust bcopy for identical src/dst */
11067 				bcopy(invalp, outvalp, inlen);
11068 			}
11069 			*outlenp = inlen;
11070 			return (0);
11071 		case IP_BOUND_IF:
11072 		case IP_DHCPINIT_IF:
11073 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11074 			    level, name, first_mp);
11075 			if (error != 0)
11076 				return (error);
11077 			break; 		/* goto sizeof (int) option return */
11078 
11079 		case IP_UNSPEC_SRC:
11080 			/* Allow sending with a zero source address */
11081 			if (!checkonly) {
11082 				mutex_enter(&connp->conn_lock);
11083 				connp->conn_unspec_src = *i1 ? 1 : 0;
11084 				mutex_exit(&connp->conn_lock);
11085 			}
11086 			break;	/* goto sizeof (int) option return */
11087 		default:
11088 			/*
11089 			 * "soft" error (negative)
11090 			 * option not handled at this level
11091 			 * Note: Do not modify *outlenp
11092 			 */
11093 			return (-EINVAL);
11094 		}
11095 		break;
11096 	case IPPROTO_IPV6:
11097 		switch (name) {
11098 		case IPV6_BOUND_IF:
11099 		case IPV6_BOUND_PIF:
11100 		case IPV6_DONTFAILOVER_IF:
11101 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11102 			    level, name, first_mp);
11103 			if (error != 0)
11104 				return (error);
11105 			break; 		/* goto sizeof (int) option return */
11106 
11107 		case IPV6_MULTICAST_IF:
11108 			/*
11109 			 * The only possible errors are EINPROGRESS and
11110 			 * EINVAL. EINPROGRESS will be restarted and is not
11111 			 * a hard error. We call this option on both V4 and V6
11112 			 * If both return EINVAL, then this call returns
11113 			 * EINVAL. If at least one of them succeeds we
11114 			 * return success.
11115 			 */
11116 			found = B_FALSE;
11117 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11118 			    level, name, first_mp);
11119 			if (error == EINPROGRESS)
11120 				return (error);
11121 			if (error == 0)
11122 				found = B_TRUE;
11123 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11124 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11125 			if (error == 0)
11126 				found = B_TRUE;
11127 			if (!found)
11128 				return (error);
11129 			break; 		/* goto sizeof (int) option return */
11130 
11131 		case IPV6_MULTICAST_HOPS:
11132 			/* Recorded in transport above IP */
11133 			break;	/* goto sizeof (int) option return */
11134 		case IPV6_MULTICAST_LOOP:
11135 			if (!checkonly) {
11136 				mutex_enter(&connp->conn_lock);
11137 				connp->conn_multicast_loop = *i1;
11138 				mutex_exit(&connp->conn_lock);
11139 			}
11140 			break;	/* goto sizeof (int) option return */
11141 		case IPV6_JOIN_GROUP:
11142 		case MCAST_JOIN_GROUP:
11143 		case IPV6_LEAVE_GROUP:
11144 		case MCAST_LEAVE_GROUP: {
11145 			struct ipv6_mreq *ip_mreqp;
11146 			struct group_req *greqp;
11147 			ire_t *ire;
11148 			boolean_t done = B_FALSE;
11149 			in6_addr_t groupv6;
11150 			uint32_t ifindex;
11151 			boolean_t mcast_opt = B_TRUE;
11152 			mcast_record_t fmode;
11153 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11154 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11155 
11156 			switch (name) {
11157 			case IPV6_JOIN_GROUP:
11158 				mcast_opt = B_FALSE;
11159 				/* FALLTHRU */
11160 			case MCAST_JOIN_GROUP:
11161 				fmode = MODE_IS_EXCLUDE;
11162 				optfn = ip_opt_add_group_v6;
11163 				break;
11164 
11165 			case IPV6_LEAVE_GROUP:
11166 				mcast_opt = B_FALSE;
11167 				/* FALLTHRU */
11168 			case MCAST_LEAVE_GROUP:
11169 				fmode = MODE_IS_INCLUDE;
11170 				optfn = ip_opt_delete_group_v6;
11171 				break;
11172 			}
11173 
11174 			if (mcast_opt) {
11175 				struct sockaddr_in *sin;
11176 				struct sockaddr_in6 *sin6;
11177 				greqp = (struct group_req *)i1;
11178 				if (greqp->gr_group.ss_family == AF_INET) {
11179 					sin = (struct sockaddr_in *)
11180 					    &(greqp->gr_group);
11181 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11182 					    &groupv6);
11183 				} else {
11184 					sin6 = (struct sockaddr_in6 *)
11185 					    &(greqp->gr_group);
11186 					groupv6 = sin6->sin6_addr;
11187 				}
11188 				ifindex = greqp->gr_interface;
11189 			} else {
11190 				ip_mreqp = (struct ipv6_mreq *)i1;
11191 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11192 				ifindex = ip_mreqp->ipv6mr_interface;
11193 			}
11194 			/*
11195 			 * In the multirouting case, we need to replicate
11196 			 * the request on all interfaces that will take part
11197 			 * in replication.  We do so because multirouting is
11198 			 * reflective, thus we will probably receive multi-
11199 			 * casts on those interfaces.
11200 			 * The ip_multirt_apply_membership_v6() succeeds if
11201 			 * the operation succeeds on at least one interface.
11202 			 */
11203 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11204 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11205 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11206 			if (ire != NULL) {
11207 				if (ire->ire_flags & RTF_MULTIRT) {
11208 					error = ip_multirt_apply_membership_v6(
11209 					    optfn, ire, connp, checkonly,
11210 					    &groupv6, fmode, &ipv6_all_zeros,
11211 					    first_mp);
11212 					done = B_TRUE;
11213 				}
11214 				ire_refrele(ire);
11215 			}
11216 			if (!done) {
11217 				error = optfn(connp, checkonly, &groupv6,
11218 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11219 			}
11220 			if (error) {
11221 				/*
11222 				 * EINPROGRESS is a soft error, needs retry
11223 				 * so don't make *outlenp zero.
11224 				 */
11225 				if (error != EINPROGRESS)
11226 					*outlenp = 0;
11227 				return (error);
11228 			}
11229 			/* OK return - copy input buffer into output buffer */
11230 			if (invalp != outvalp) {
11231 				/* don't trust bcopy for identical src/dst */
11232 				bcopy(invalp, outvalp, inlen);
11233 			}
11234 			*outlenp = inlen;
11235 			return (0);
11236 		}
11237 		case MCAST_BLOCK_SOURCE:
11238 		case MCAST_UNBLOCK_SOURCE:
11239 		case MCAST_JOIN_SOURCE_GROUP:
11240 		case MCAST_LEAVE_SOURCE_GROUP: {
11241 			struct group_source_req *gsreqp;
11242 			in6_addr_t v6grp, v6src;
11243 			uint32_t ifindex;
11244 			mcast_record_t fmode;
11245 			ire_t *ire;
11246 			boolean_t done = B_FALSE;
11247 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11248 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11249 
11250 			switch (name) {
11251 			case MCAST_BLOCK_SOURCE:
11252 				fmode = MODE_IS_EXCLUDE;
11253 				optfn = ip_opt_add_group_v6;
11254 				break;
11255 			case MCAST_UNBLOCK_SOURCE:
11256 				fmode = MODE_IS_EXCLUDE;
11257 				optfn = ip_opt_delete_group_v6;
11258 				break;
11259 			case MCAST_JOIN_SOURCE_GROUP:
11260 				fmode = MODE_IS_INCLUDE;
11261 				optfn = ip_opt_add_group_v6;
11262 				break;
11263 			case MCAST_LEAVE_SOURCE_GROUP:
11264 				fmode = MODE_IS_INCLUDE;
11265 				optfn = ip_opt_delete_group_v6;
11266 				break;
11267 			}
11268 
11269 			gsreqp = (struct group_source_req *)i1;
11270 			ifindex = gsreqp->gsr_interface;
11271 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11272 				struct sockaddr_in *s;
11273 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11274 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11275 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11276 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11277 			} else {
11278 				struct sockaddr_in6 *s6;
11279 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11280 				v6grp = s6->sin6_addr;
11281 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11282 				v6src = s6->sin6_addr;
11283 			}
11284 
11285 			/*
11286 			 * In the multirouting case, we need to replicate
11287 			 * the request as noted in the mcast cases above.
11288 			 */
11289 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11290 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11291 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11292 			if (ire != NULL) {
11293 				if (ire->ire_flags & RTF_MULTIRT) {
11294 					error = ip_multirt_apply_membership_v6(
11295 					    optfn, ire, connp, checkonly,
11296 					    &v6grp, fmode, &v6src, first_mp);
11297 					done = B_TRUE;
11298 				}
11299 				ire_refrele(ire);
11300 			}
11301 			if (!done) {
11302 				error = optfn(connp, checkonly, &v6grp,
11303 				    ifindex, fmode, &v6src, first_mp);
11304 			}
11305 			if (error != 0) {
11306 				/*
11307 				 * EINPROGRESS is a soft error, needs retry
11308 				 * so don't make *outlenp zero.
11309 				 */
11310 				if (error != EINPROGRESS)
11311 					*outlenp = 0;
11312 				return (error);
11313 			}
11314 			/* OK return - copy input buffer into output buffer */
11315 			if (invalp != outvalp) {
11316 				bcopy(invalp, outvalp, inlen);
11317 			}
11318 			*outlenp = inlen;
11319 			return (0);
11320 		}
11321 		case IPV6_UNICAST_HOPS:
11322 			/* Recorded in transport above IP */
11323 			break;	/* goto sizeof (int) option return */
11324 		case IPV6_UNSPEC_SRC:
11325 			/* Allow sending with a zero source address */
11326 			if (!checkonly) {
11327 				mutex_enter(&connp->conn_lock);
11328 				connp->conn_unspec_src = *i1 ? 1 : 0;
11329 				mutex_exit(&connp->conn_lock);
11330 			}
11331 			break;	/* goto sizeof (int) option return */
11332 		case IPV6_RECVPKTINFO:
11333 			if (!checkonly) {
11334 				mutex_enter(&connp->conn_lock);
11335 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11336 				mutex_exit(&connp->conn_lock);
11337 			}
11338 			break;	/* goto sizeof (int) option return */
11339 		case IPV6_RECVTCLASS:
11340 			if (!checkonly) {
11341 				if (*i1 < 0 || *i1 > 1) {
11342 					return (EINVAL);
11343 				}
11344 				mutex_enter(&connp->conn_lock);
11345 				connp->conn_ipv6_recvtclass = *i1;
11346 				mutex_exit(&connp->conn_lock);
11347 			}
11348 			break;
11349 		case IPV6_RECVPATHMTU:
11350 			if (!checkonly) {
11351 				if (*i1 < 0 || *i1 > 1) {
11352 					return (EINVAL);
11353 				}
11354 				mutex_enter(&connp->conn_lock);
11355 				connp->conn_ipv6_recvpathmtu = *i1;
11356 				mutex_exit(&connp->conn_lock);
11357 			}
11358 			break;
11359 		case IPV6_RECVHOPLIMIT:
11360 			if (!checkonly) {
11361 				mutex_enter(&connp->conn_lock);
11362 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11363 				mutex_exit(&connp->conn_lock);
11364 			}
11365 			break;	/* goto sizeof (int) option return */
11366 		case IPV6_RECVHOPOPTS:
11367 			if (!checkonly) {
11368 				mutex_enter(&connp->conn_lock);
11369 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11370 				mutex_exit(&connp->conn_lock);
11371 			}
11372 			break;	/* goto sizeof (int) option return */
11373 		case IPV6_RECVDSTOPTS:
11374 			if (!checkonly) {
11375 				mutex_enter(&connp->conn_lock);
11376 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11377 				mutex_exit(&connp->conn_lock);
11378 			}
11379 			break;	/* goto sizeof (int) option return */
11380 		case IPV6_RECVRTHDR:
11381 			if (!checkonly) {
11382 				mutex_enter(&connp->conn_lock);
11383 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11384 				mutex_exit(&connp->conn_lock);
11385 			}
11386 			break;	/* goto sizeof (int) option return */
11387 		case IPV6_RECVRTHDRDSTOPTS:
11388 			if (!checkonly) {
11389 				mutex_enter(&connp->conn_lock);
11390 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11391 				mutex_exit(&connp->conn_lock);
11392 			}
11393 			break;	/* goto sizeof (int) option return */
11394 		case IPV6_PKTINFO:
11395 			if (inlen == 0)
11396 				return (-EINVAL);	/* clearing option */
11397 			error = ip6_set_pktinfo(cr, connp,
11398 			    (struct in6_pktinfo *)invalp, first_mp);
11399 			if (error != 0)
11400 				*outlenp = 0;
11401 			else
11402 				*outlenp = inlen;
11403 			return (error);
11404 		case IPV6_NEXTHOP: {
11405 			struct sockaddr_in6 *sin6;
11406 
11407 			/* Verify that the nexthop is reachable */
11408 			if (inlen == 0)
11409 				return (-EINVAL);	/* clearing option */
11410 
11411 			sin6 = (struct sockaddr_in6 *)invalp;
11412 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11413 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11414 			    NULL, MATCH_IRE_DEFAULT, ipst);
11415 
11416 			if (ire == NULL) {
11417 				*outlenp = 0;
11418 				return (EHOSTUNREACH);
11419 			}
11420 			ire_refrele(ire);
11421 			return (-EINVAL);
11422 		}
11423 		case IPV6_SEC_OPT:
11424 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11425 			if (error != 0) {
11426 				*outlenp = 0;
11427 				return (error);
11428 			}
11429 			break;
11430 		case IPV6_SRC_PREFERENCES: {
11431 			/*
11432 			 * This is implemented strictly in the ip module
11433 			 * (here and in tcp_opt_*() to accomodate tcp
11434 			 * sockets).  Modules above ip pass this option
11435 			 * down here since ip is the only one that needs to
11436 			 * be aware of source address preferences.
11437 			 *
11438 			 * This socket option only affects connected
11439 			 * sockets that haven't already bound to a specific
11440 			 * IPv6 address.  In other words, sockets that
11441 			 * don't call bind() with an address other than the
11442 			 * unspecified address and that call connect().
11443 			 * ip_bind_connected_v6() passes these preferences
11444 			 * to the ipif_select_source_v6() function.
11445 			 */
11446 			if (inlen != sizeof (uint32_t))
11447 				return (EINVAL);
11448 			error = ip6_set_src_preferences(connp,
11449 			    *(uint32_t *)invalp);
11450 			if (error != 0) {
11451 				*outlenp = 0;
11452 				return (error);
11453 			} else {
11454 				*outlenp = sizeof (uint32_t);
11455 			}
11456 			break;
11457 		}
11458 		case IPV6_V6ONLY:
11459 			if (*i1 < 0 || *i1 > 1) {
11460 				return (EINVAL);
11461 			}
11462 			mutex_enter(&connp->conn_lock);
11463 			connp->conn_ipv6_v6only = *i1;
11464 			mutex_exit(&connp->conn_lock);
11465 			break;
11466 		default:
11467 			return (-EINVAL);
11468 		}
11469 		break;
11470 	default:
11471 		/*
11472 		 * "soft" error (negative)
11473 		 * option not handled at this level
11474 		 * Note: Do not modify *outlenp
11475 		 */
11476 		return (-EINVAL);
11477 	}
11478 	/*
11479 	 * Common case of return from an option that is sizeof (int)
11480 	 */
11481 	*(int *)outvalp = *i1;
11482 	*outlenp = sizeof (int);
11483 	return (0);
11484 }
11485 
11486 /*
11487  * This routine gets default values of certain options whose default
11488  * values are maintained by protocol specific code
11489  */
11490 /* ARGSUSED */
11491 int
11492 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11493 {
11494 	int *i1 = (int *)ptr;
11495 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11496 
11497 	switch (level) {
11498 	case IPPROTO_IP:
11499 		switch (name) {
11500 		case IP_MULTICAST_TTL:
11501 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11502 			return (sizeof (uchar_t));
11503 		case IP_MULTICAST_LOOP:
11504 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11505 			return (sizeof (uchar_t));
11506 		default:
11507 			return (-1);
11508 		}
11509 	case IPPROTO_IPV6:
11510 		switch (name) {
11511 		case IPV6_UNICAST_HOPS:
11512 			*i1 = ipst->ips_ipv6_def_hops;
11513 			return (sizeof (int));
11514 		case IPV6_MULTICAST_HOPS:
11515 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11516 			return (sizeof (int));
11517 		case IPV6_MULTICAST_LOOP:
11518 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11519 			return (sizeof (int));
11520 		case IPV6_V6ONLY:
11521 			*i1 = 1;
11522 			return (sizeof (int));
11523 		default:
11524 			return (-1);
11525 		}
11526 	default:
11527 		return (-1);
11528 	}
11529 	/* NOTREACHED */
11530 }
11531 
11532 /*
11533  * Given a destination address and a pointer to where to put the information
11534  * this routine fills in the mtuinfo.
11535  */
11536 int
11537 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11538     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11539 {
11540 	ire_t *ire;
11541 	ip_stack_t	*ipst = ns->netstack_ip;
11542 
11543 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11544 		return (-1);
11545 
11546 	bzero(mtuinfo, sizeof (*mtuinfo));
11547 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11548 	mtuinfo->ip6m_addr.sin6_port = port;
11549 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11550 
11551 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11552 	if (ire != NULL) {
11553 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11554 		ire_refrele(ire);
11555 	} else {
11556 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11557 	}
11558 	return (sizeof (struct ip6_mtuinfo));
11559 }
11560 
11561 /*
11562  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11563  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11564  * isn't.  This doesn't matter as the error checking is done properly for the
11565  * other MRT options coming in through ip_opt_set.
11566  */
11567 int
11568 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11569 {
11570 	conn_t		*connp = Q_TO_CONN(q);
11571 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11572 
11573 	switch (level) {
11574 	case IPPROTO_IP:
11575 		switch (name) {
11576 		case MRT_VERSION:
11577 		case MRT_ASSERT:
11578 			(void) ip_mrouter_get(name, q, ptr);
11579 			return (sizeof (int));
11580 		case IP_SEC_OPT:
11581 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11582 		case IP_NEXTHOP:
11583 			if (connp->conn_nexthop_set) {
11584 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11585 				return (sizeof (ipaddr_t));
11586 			} else
11587 				return (0);
11588 		case IP_RECVPKTINFO:
11589 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11590 			return (sizeof (int));
11591 		default:
11592 			break;
11593 		}
11594 		break;
11595 	case IPPROTO_IPV6:
11596 		switch (name) {
11597 		case IPV6_SEC_OPT:
11598 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11599 		case IPV6_SRC_PREFERENCES: {
11600 			return (ip6_get_src_preferences(connp,
11601 			    (uint32_t *)ptr));
11602 		}
11603 		case IPV6_V6ONLY:
11604 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11605 			return (sizeof (int));
11606 		case IPV6_PATHMTU:
11607 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11608 			    (struct ip6_mtuinfo *)ptr, connp->conn_netstack));
11609 		default:
11610 			break;
11611 		}
11612 		break;
11613 	default:
11614 		break;
11615 	}
11616 	return (-1);
11617 }
11618 
11619 /* Named Dispatch routine to get a current value out of our parameter table. */
11620 /* ARGSUSED */
11621 static int
11622 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11623 {
11624 	ipparam_t *ippa = (ipparam_t *)cp;
11625 
11626 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11627 	return (0);
11628 }
11629 
11630 /* ARGSUSED */
11631 static int
11632 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11633 {
11634 
11635 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11636 	return (0);
11637 }
11638 
11639 /*
11640  * Set ip{,6}_forwarding values.  This means walking through all of the
11641  * ill's and toggling their forwarding values.
11642  */
11643 /* ARGSUSED */
11644 static int
11645 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11646 {
11647 	long new_value;
11648 	int *forwarding_value = (int *)cp;
11649 	ill_t *ill;
11650 	boolean_t isv6;
11651 	ill_walk_context_t ctx;
11652 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11653 
11654 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11655 
11656 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11657 	    new_value < 0 || new_value > 1) {
11658 		return (EINVAL);
11659 	}
11660 
11661 	*forwarding_value = new_value;
11662 
11663 	/*
11664 	 * Regardless of the current value of ip_forwarding, set all per-ill
11665 	 * values of ip_forwarding to the value being set.
11666 	 *
11667 	 * Bring all the ill's up to date with the new global value.
11668 	 */
11669 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11670 
11671 	if (isv6)
11672 		ill = ILL_START_WALK_V6(&ctx, ipst);
11673 	else
11674 		ill = ILL_START_WALK_V4(&ctx, ipst);
11675 
11676 	for (; ill != NULL; ill = ill_next(&ctx, ill))
11677 		(void) ill_forward_set(ill, new_value != 0);
11678 
11679 	rw_exit(&ipst->ips_ill_g_lock);
11680 	return (0);
11681 }
11682 
11683 /*
11684  * Walk through the param array specified registering each element with the
11685  * Named Dispatch handler. This is called only during init. So it is ok
11686  * not to acquire any locks
11687  */
11688 static boolean_t
11689 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11690     ipndp_t *ipnd, size_t ipnd_cnt)
11691 {
11692 	for (; ippa_cnt-- > 0; ippa++) {
11693 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11694 			if (!nd_load(ndp, ippa->ip_param_name,
11695 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11696 				nd_free(ndp);
11697 				return (B_FALSE);
11698 			}
11699 		}
11700 	}
11701 
11702 	for (; ipnd_cnt-- > 0; ipnd++) {
11703 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11704 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11705 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11706 			    ipnd->ip_ndp_data)) {
11707 				nd_free(ndp);
11708 				return (B_FALSE);
11709 			}
11710 		}
11711 	}
11712 
11713 	return (B_TRUE);
11714 }
11715 
11716 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11717 /* ARGSUSED */
11718 static int
11719 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11720 {
11721 	long		new_value;
11722 	ipparam_t	*ippa = (ipparam_t *)cp;
11723 
11724 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11725 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11726 		return (EINVAL);
11727 	}
11728 	ippa->ip_param_value = new_value;
11729 	return (0);
11730 }
11731 
11732 /*
11733  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11734  * When an ipf is passed here for the first time, if
11735  * we already have in-order fragments on the queue, we convert from the fast-
11736  * path reassembly scheme to the hard-case scheme.  From then on, additional
11737  * fragments are reassembled here.  We keep track of the start and end offsets
11738  * of each piece, and the number of holes in the chain.  When the hole count
11739  * goes to zero, we are done!
11740  *
11741  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11742  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11743  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11744  * after the call to ip_reassemble().
11745  */
11746 int
11747 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11748     size_t msg_len)
11749 {
11750 	uint_t	end;
11751 	mblk_t	*next_mp;
11752 	mblk_t	*mp1;
11753 	uint_t	offset;
11754 	boolean_t incr_dups = B_TRUE;
11755 	boolean_t offset_zero_seen = B_FALSE;
11756 	boolean_t pkt_boundary_checked = B_FALSE;
11757 
11758 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11759 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11760 
11761 	/* Add in byte count */
11762 	ipf->ipf_count += msg_len;
11763 	if (ipf->ipf_end) {
11764 		/*
11765 		 * We were part way through in-order reassembly, but now there
11766 		 * is a hole.  We walk through messages already queued, and
11767 		 * mark them for hard case reassembly.  We know that up till
11768 		 * now they were in order starting from offset zero.
11769 		 */
11770 		offset = 0;
11771 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11772 			IP_REASS_SET_START(mp1, offset);
11773 			if (offset == 0) {
11774 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11775 				offset = -ipf->ipf_nf_hdr_len;
11776 			}
11777 			offset += mp1->b_wptr - mp1->b_rptr;
11778 			IP_REASS_SET_END(mp1, offset);
11779 		}
11780 		/* One hole at the end. */
11781 		ipf->ipf_hole_cnt = 1;
11782 		/* Brand it as a hard case, forever. */
11783 		ipf->ipf_end = 0;
11784 	}
11785 	/* Walk through all the new pieces. */
11786 	do {
11787 		end = start + (mp->b_wptr - mp->b_rptr);
11788 		/*
11789 		 * If start is 0, decrease 'end' only for the first mblk of
11790 		 * the fragment. Otherwise 'end' can get wrong value in the
11791 		 * second pass of the loop if first mblk is exactly the
11792 		 * size of ipf_nf_hdr_len.
11793 		 */
11794 		if (start == 0 && !offset_zero_seen) {
11795 			/* First segment */
11796 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11797 			end -= ipf->ipf_nf_hdr_len;
11798 			offset_zero_seen = B_TRUE;
11799 		}
11800 		next_mp = mp->b_cont;
11801 		/*
11802 		 * We are checking to see if there is any interesing data
11803 		 * to process.  If there isn't and the mblk isn't the
11804 		 * one which carries the unfragmentable header then we
11805 		 * drop it.  It's possible to have just the unfragmentable
11806 		 * header come through without any data.  That needs to be
11807 		 * saved.
11808 		 *
11809 		 * If the assert at the top of this function holds then the
11810 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11811 		 * is infrequently traveled enough that the test is left in
11812 		 * to protect against future code changes which break that
11813 		 * invariant.
11814 		 */
11815 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11816 			/* Empty.  Blast it. */
11817 			IP_REASS_SET_START(mp, 0);
11818 			IP_REASS_SET_END(mp, 0);
11819 			/*
11820 			 * If the ipf points to the mblk we are about to free,
11821 			 * update ipf to point to the next mblk (or NULL
11822 			 * if none).
11823 			 */
11824 			if (ipf->ipf_mp->b_cont == mp)
11825 				ipf->ipf_mp->b_cont = next_mp;
11826 			freeb(mp);
11827 			continue;
11828 		}
11829 		mp->b_cont = NULL;
11830 		IP_REASS_SET_START(mp, start);
11831 		IP_REASS_SET_END(mp, end);
11832 		if (!ipf->ipf_tail_mp) {
11833 			ipf->ipf_tail_mp = mp;
11834 			ipf->ipf_mp->b_cont = mp;
11835 			if (start == 0 || !more) {
11836 				ipf->ipf_hole_cnt = 1;
11837 				/*
11838 				 * if the first fragment comes in more than one
11839 				 * mblk, this loop will be executed for each
11840 				 * mblk. Need to adjust hole count so exiting
11841 				 * this routine will leave hole count at 1.
11842 				 */
11843 				if (next_mp)
11844 					ipf->ipf_hole_cnt++;
11845 			} else
11846 				ipf->ipf_hole_cnt = 2;
11847 			continue;
11848 		} else if (ipf->ipf_last_frag_seen && !more &&
11849 		    !pkt_boundary_checked) {
11850 			/*
11851 			 * We check datagram boundary only if this fragment
11852 			 * claims to be the last fragment and we have seen a
11853 			 * last fragment in the past too. We do this only
11854 			 * once for a given fragment.
11855 			 *
11856 			 * start cannot be 0 here as fragments with start=0
11857 			 * and MF=0 gets handled as a complete packet. These
11858 			 * fragments should not reach here.
11859 			 */
11860 
11861 			if (start + msgdsize(mp) !=
11862 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11863 				/*
11864 				 * We have two fragments both of which claim
11865 				 * to be the last fragment but gives conflicting
11866 				 * information about the whole datagram size.
11867 				 * Something fishy is going on. Drop the
11868 				 * fragment and free up the reassembly list.
11869 				 */
11870 				return (IP_REASS_FAILED);
11871 			}
11872 
11873 			/*
11874 			 * We shouldn't come to this code block again for this
11875 			 * particular fragment.
11876 			 */
11877 			pkt_boundary_checked = B_TRUE;
11878 		}
11879 
11880 		/* New stuff at or beyond tail? */
11881 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11882 		if (start >= offset) {
11883 			if (ipf->ipf_last_frag_seen) {
11884 				/* current fragment is beyond last fragment */
11885 				return (IP_REASS_FAILED);
11886 			}
11887 			/* Link it on end. */
11888 			ipf->ipf_tail_mp->b_cont = mp;
11889 			ipf->ipf_tail_mp = mp;
11890 			if (more) {
11891 				if (start != offset)
11892 					ipf->ipf_hole_cnt++;
11893 			} else if (start == offset && next_mp == NULL)
11894 					ipf->ipf_hole_cnt--;
11895 			continue;
11896 		}
11897 		mp1 = ipf->ipf_mp->b_cont;
11898 		offset = IP_REASS_START(mp1);
11899 		/* New stuff at the front? */
11900 		if (start < offset) {
11901 			if (start == 0) {
11902 				if (end >= offset) {
11903 					/* Nailed the hole at the begining. */
11904 					ipf->ipf_hole_cnt--;
11905 				}
11906 			} else if (end < offset) {
11907 				/*
11908 				 * A hole, stuff, and a hole where there used
11909 				 * to be just a hole.
11910 				 */
11911 				ipf->ipf_hole_cnt++;
11912 			}
11913 			mp->b_cont = mp1;
11914 			/* Check for overlap. */
11915 			while (end > offset) {
11916 				if (end < IP_REASS_END(mp1)) {
11917 					mp->b_wptr -= end - offset;
11918 					IP_REASS_SET_END(mp, offset);
11919 					BUMP_MIB(ill->ill_ip_mib,
11920 					    ipIfStatsReasmPartDups);
11921 					break;
11922 				}
11923 				/* Did we cover another hole? */
11924 				if ((mp1->b_cont &&
11925 				    IP_REASS_END(mp1) !=
11926 				    IP_REASS_START(mp1->b_cont) &&
11927 				    end >= IP_REASS_START(mp1->b_cont)) ||
11928 				    (!ipf->ipf_last_frag_seen && !more)) {
11929 					ipf->ipf_hole_cnt--;
11930 				}
11931 				/* Clip out mp1. */
11932 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11933 					/*
11934 					 * After clipping out mp1, this guy
11935 					 * is now hanging off the end.
11936 					 */
11937 					ipf->ipf_tail_mp = mp;
11938 				}
11939 				IP_REASS_SET_START(mp1, 0);
11940 				IP_REASS_SET_END(mp1, 0);
11941 				/* Subtract byte count */
11942 				ipf->ipf_count -= mp1->b_datap->db_lim -
11943 				    mp1->b_datap->db_base;
11944 				freeb(mp1);
11945 				BUMP_MIB(ill->ill_ip_mib,
11946 				    ipIfStatsReasmPartDups);
11947 				mp1 = mp->b_cont;
11948 				if (!mp1)
11949 					break;
11950 				offset = IP_REASS_START(mp1);
11951 			}
11952 			ipf->ipf_mp->b_cont = mp;
11953 			continue;
11954 		}
11955 		/*
11956 		 * The new piece starts somewhere between the start of the head
11957 		 * and before the end of the tail.
11958 		 */
11959 		for (; mp1; mp1 = mp1->b_cont) {
11960 			offset = IP_REASS_END(mp1);
11961 			if (start < offset) {
11962 				if (end <= offset) {
11963 					/* Nothing new. */
11964 					IP_REASS_SET_START(mp, 0);
11965 					IP_REASS_SET_END(mp, 0);
11966 					/* Subtract byte count */
11967 					ipf->ipf_count -= mp->b_datap->db_lim -
11968 					    mp->b_datap->db_base;
11969 					if (incr_dups) {
11970 						ipf->ipf_num_dups++;
11971 						incr_dups = B_FALSE;
11972 					}
11973 					freeb(mp);
11974 					BUMP_MIB(ill->ill_ip_mib,
11975 					    ipIfStatsReasmDuplicates);
11976 					break;
11977 				}
11978 				/*
11979 				 * Trim redundant stuff off beginning of new
11980 				 * piece.
11981 				 */
11982 				IP_REASS_SET_START(mp, offset);
11983 				mp->b_rptr += offset - start;
11984 				BUMP_MIB(ill->ill_ip_mib,
11985 				    ipIfStatsReasmPartDups);
11986 				start = offset;
11987 				if (!mp1->b_cont) {
11988 					/*
11989 					 * After trimming, this guy is now
11990 					 * hanging off the end.
11991 					 */
11992 					mp1->b_cont = mp;
11993 					ipf->ipf_tail_mp = mp;
11994 					if (!more) {
11995 						ipf->ipf_hole_cnt--;
11996 					}
11997 					break;
11998 				}
11999 			}
12000 			if (start >= IP_REASS_START(mp1->b_cont))
12001 				continue;
12002 			/* Fill a hole */
12003 			if (start > offset)
12004 				ipf->ipf_hole_cnt++;
12005 			mp->b_cont = mp1->b_cont;
12006 			mp1->b_cont = mp;
12007 			mp1 = mp->b_cont;
12008 			offset = IP_REASS_START(mp1);
12009 			if (end >= offset) {
12010 				ipf->ipf_hole_cnt--;
12011 				/* Check for overlap. */
12012 				while (end > offset) {
12013 					if (end < IP_REASS_END(mp1)) {
12014 						mp->b_wptr -= end - offset;
12015 						IP_REASS_SET_END(mp, offset);
12016 						/*
12017 						 * TODO we might bump
12018 						 * this up twice if there is
12019 						 * overlap at both ends.
12020 						 */
12021 						BUMP_MIB(ill->ill_ip_mib,
12022 						    ipIfStatsReasmPartDups);
12023 						break;
12024 					}
12025 					/* Did we cover another hole? */
12026 					if ((mp1->b_cont &&
12027 					    IP_REASS_END(mp1)
12028 					    != IP_REASS_START(mp1->b_cont) &&
12029 					    end >=
12030 					    IP_REASS_START(mp1->b_cont)) ||
12031 					    (!ipf->ipf_last_frag_seen &&
12032 					    !more)) {
12033 						ipf->ipf_hole_cnt--;
12034 					}
12035 					/* Clip out mp1. */
12036 					if ((mp->b_cont = mp1->b_cont) ==
12037 					    NULL) {
12038 						/*
12039 						 * After clipping out mp1,
12040 						 * this guy is now hanging
12041 						 * off the end.
12042 						 */
12043 						ipf->ipf_tail_mp = mp;
12044 					}
12045 					IP_REASS_SET_START(mp1, 0);
12046 					IP_REASS_SET_END(mp1, 0);
12047 					/* Subtract byte count */
12048 					ipf->ipf_count -=
12049 					    mp1->b_datap->db_lim -
12050 					    mp1->b_datap->db_base;
12051 					freeb(mp1);
12052 					BUMP_MIB(ill->ill_ip_mib,
12053 					    ipIfStatsReasmPartDups);
12054 					mp1 = mp->b_cont;
12055 					if (!mp1)
12056 						break;
12057 					offset = IP_REASS_START(mp1);
12058 				}
12059 			}
12060 			break;
12061 		}
12062 	} while (start = end, mp = next_mp);
12063 
12064 	/* Fragment just processed could be the last one. Remember this fact */
12065 	if (!more)
12066 		ipf->ipf_last_frag_seen = B_TRUE;
12067 
12068 	/* Still got holes? */
12069 	if (ipf->ipf_hole_cnt)
12070 		return (IP_REASS_PARTIAL);
12071 	/* Clean up overloaded fields to avoid upstream disasters. */
12072 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12073 		IP_REASS_SET_START(mp1, 0);
12074 		IP_REASS_SET_END(mp1, 0);
12075 	}
12076 	return (IP_REASS_COMPLETE);
12077 }
12078 
12079 /*
12080  * ipsec processing for the fast path, used for input UDP Packets
12081  * Returns true if ready for passup to UDP.
12082  * Return false if packet is not passable to UDP (e.g. it failed IPsec policy,
12083  * was an ESP-in-UDP packet, etc.).
12084  */
12085 static boolean_t
12086 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
12087     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present, ire_t *ire)
12088 {
12089 	uint32_t	ill_index;
12090 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
12091 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
12092 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12093 	udp_t		*udp = connp->conn_udp;
12094 
12095 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12096 	/* The ill_index of the incoming ILL */
12097 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
12098 
12099 	/* pass packet up to the transport */
12100 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
12101 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
12102 		    NULL, mctl_present);
12103 		if (*first_mpp == NULL) {
12104 			return (B_FALSE);
12105 		}
12106 	}
12107 
12108 	/* Initiate IPPF processing for fastpath UDP */
12109 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12110 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
12111 		if (*mpp == NULL) {
12112 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
12113 			    "deferred/dropped during IPPF processing\n"));
12114 			return (B_FALSE);
12115 		}
12116 	}
12117 	/*
12118 	 * Remove 0-spi if it's 0, or move everything behind
12119 	 * the UDP header over it and forward to ESP via
12120 	 * ip_proto_input().
12121 	 */
12122 	if (udp->udp_nat_t_endpoint) {
12123 		if (mctl_present) {
12124 			/* mctl_present *shouldn't* happen. */
12125 			ip_drop_packet(*first_mpp, B_TRUE, NULL,
12126 			    NULL, DROPPER(ipss, ipds_esp_nat_t_ipsec),
12127 			    &ipss->ipsec_dropper);
12128 			*first_mpp = NULL;
12129 			return (B_FALSE);
12130 		}
12131 
12132 		/* "ill" is "recv_ill" in actuality. */
12133 		if (!zero_spi_check(q, *mpp, ire, ill, ipss))
12134 			return (B_FALSE);
12135 
12136 		/* Else continue like a normal UDP packet. */
12137 	}
12138 
12139 	/*
12140 	 * We make the checks as below since we are in the fast path
12141 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12142 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12143 	 */
12144 	if (connp->conn_recvif || connp->conn_recvslla ||
12145 	    connp->conn_ip_recvpktinfo) {
12146 		if (connp->conn_recvif) {
12147 			in_flags = IPF_RECVIF;
12148 		}
12149 		/*
12150 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12151 		 * so the flag passed to ip_add_info is based on IP version
12152 		 * of connp.
12153 		 */
12154 		if (connp->conn_ip_recvpktinfo) {
12155 			if (connp->conn_af_isv6) {
12156 				/*
12157 				 * V6 only needs index
12158 				 */
12159 				in_flags |= IPF_RECVIF;
12160 			} else {
12161 				/*
12162 				 * V4 needs index + matching address.
12163 				 */
12164 				in_flags |= IPF_RECVADDR;
12165 			}
12166 		}
12167 		if (connp->conn_recvslla) {
12168 			in_flags |= IPF_RECVSLLA;
12169 		}
12170 		/*
12171 		 * since in_flags are being set ill will be
12172 		 * referenced in ip_add_info, so it better not
12173 		 * be NULL.
12174 		 */
12175 		/*
12176 		 * the actual data will be contained in b_cont
12177 		 * upon successful return of the following call.
12178 		 * If the call fails then the original mblk is
12179 		 * returned.
12180 		 */
12181 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12182 		    ipst);
12183 	}
12184 
12185 	return (B_TRUE);
12186 }
12187 
12188 /*
12189  * Fragmentation reassembly.  Each ILL has a hash table for
12190  * queuing packets undergoing reassembly for all IPIFs
12191  * associated with the ILL.  The hash is based on the packet
12192  * IP ident field.  The ILL frag hash table was allocated
12193  * as a timer block at the time the ILL was created.  Whenever
12194  * there is anything on the reassembly queue, the timer will
12195  * be running.  Returns B_TRUE if successful else B_FALSE;
12196  * frees mp on failure.
12197  */
12198 static boolean_t
12199 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
12200     uint32_t *cksum_val, uint16_t *cksum_flags)
12201 {
12202 	uint32_t	frag_offset_flags;
12203 	ill_t		*ill = (ill_t *)q->q_ptr;
12204 	mblk_t		*mp = *mpp;
12205 	mblk_t		*t_mp;
12206 	ipaddr_t	dst;
12207 	uint8_t		proto = ipha->ipha_protocol;
12208 	uint32_t	sum_val;
12209 	uint16_t	sum_flags;
12210 	ipf_t		*ipf;
12211 	ipf_t		**ipfp;
12212 	ipfb_t		*ipfb;
12213 	uint16_t	ident;
12214 	uint32_t	offset;
12215 	ipaddr_t	src;
12216 	uint_t		hdr_length;
12217 	uint32_t	end;
12218 	mblk_t		*mp1;
12219 	mblk_t		*tail_mp;
12220 	size_t		count;
12221 	size_t		msg_len;
12222 	uint8_t		ecn_info = 0;
12223 	uint32_t	packet_size;
12224 	boolean_t	pruned = B_FALSE;
12225 	ip_stack_t *ipst = ill->ill_ipst;
12226 
12227 	if (cksum_val != NULL)
12228 		*cksum_val = 0;
12229 	if (cksum_flags != NULL)
12230 		*cksum_flags = 0;
12231 
12232 	/*
12233 	 * Drop the fragmented as early as possible, if
12234 	 * we don't have resource(s) to re-assemble.
12235 	 */
12236 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12237 		freemsg(mp);
12238 		return (B_FALSE);
12239 	}
12240 
12241 	/* Check for fragmentation offset; return if there's none */
12242 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12243 	    (IPH_MF | IPH_OFFSET)) == 0)
12244 		return (B_TRUE);
12245 
12246 	/*
12247 	 * We utilize hardware computed checksum info only for UDP since
12248 	 * IP fragmentation is a normal occurence for the protocol.  In
12249 	 * addition, checksum offload support for IP fragments carrying
12250 	 * UDP payload is commonly implemented across network adapters.
12251 	 */
12252 	ASSERT(ill != NULL);
12253 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
12254 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12255 		mblk_t *mp1 = mp->b_cont;
12256 		int32_t len;
12257 
12258 		/* Record checksum information from the packet */
12259 		sum_val = (uint32_t)DB_CKSUM16(mp);
12260 		sum_flags = DB_CKSUMFLAGS(mp);
12261 
12262 		/* IP payload offset from beginning of mblk */
12263 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12264 
12265 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12266 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12267 		    offset >= DB_CKSUMSTART(mp) &&
12268 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12269 			uint32_t adj;
12270 			/*
12271 			 * Partial checksum has been calculated by hardware
12272 			 * and attached to the packet; in addition, any
12273 			 * prepended extraneous data is even byte aligned.
12274 			 * If any such data exists, we adjust the checksum;
12275 			 * this would also handle any postpended data.
12276 			 */
12277 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12278 			    mp, mp1, len, adj);
12279 
12280 			/* One's complement subtract extraneous checksum */
12281 			if (adj >= sum_val)
12282 				sum_val = ~(adj - sum_val) & 0xFFFF;
12283 			else
12284 				sum_val -= adj;
12285 		}
12286 	} else {
12287 		sum_val = 0;
12288 		sum_flags = 0;
12289 	}
12290 
12291 	/* Clear hardware checksumming flag */
12292 	DB_CKSUMFLAGS(mp) = 0;
12293 
12294 	ident = ipha->ipha_ident;
12295 	offset = (frag_offset_flags << 3) & 0xFFFF;
12296 	src = ipha->ipha_src;
12297 	dst = ipha->ipha_dst;
12298 	hdr_length = IPH_HDR_LENGTH(ipha);
12299 	end = ntohs(ipha->ipha_length) - hdr_length;
12300 
12301 	/* If end == 0 then we have a packet with no data, so just free it */
12302 	if (end == 0) {
12303 		freemsg(mp);
12304 		return (B_FALSE);
12305 	}
12306 
12307 	/* Record the ECN field info. */
12308 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12309 	if (offset != 0) {
12310 		/*
12311 		 * If this isn't the first piece, strip the header, and
12312 		 * add the offset to the end value.
12313 		 */
12314 		mp->b_rptr += hdr_length;
12315 		end += offset;
12316 	}
12317 
12318 	msg_len = MBLKSIZE(mp);
12319 	tail_mp = mp;
12320 	while (tail_mp->b_cont != NULL) {
12321 		tail_mp = tail_mp->b_cont;
12322 		msg_len += MBLKSIZE(tail_mp);
12323 	}
12324 
12325 	/* If the reassembly list for this ILL will get too big, prune it */
12326 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12327 	    ipst->ips_ip_reass_queue_bytes) {
12328 		ill_frag_prune(ill,
12329 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12330 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12331 		pruned = B_TRUE;
12332 	}
12333 
12334 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12335 	mutex_enter(&ipfb->ipfb_lock);
12336 
12337 	ipfp = &ipfb->ipfb_ipf;
12338 	/* Try to find an existing fragment queue for this packet. */
12339 	for (;;) {
12340 		ipf = ipfp[0];
12341 		if (ipf != NULL) {
12342 			/*
12343 			 * It has to match on ident and src/dst address.
12344 			 */
12345 			if (ipf->ipf_ident == ident &&
12346 			    ipf->ipf_src == src &&
12347 			    ipf->ipf_dst == dst &&
12348 			    ipf->ipf_protocol == proto) {
12349 				/*
12350 				 * If we have received too many
12351 				 * duplicate fragments for this packet
12352 				 * free it.
12353 				 */
12354 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12355 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12356 					freemsg(mp);
12357 					mutex_exit(&ipfb->ipfb_lock);
12358 					return (B_FALSE);
12359 				}
12360 				/* Found it. */
12361 				break;
12362 			}
12363 			ipfp = &ipf->ipf_hash_next;
12364 			continue;
12365 		}
12366 
12367 		/*
12368 		 * If we pruned the list, do we want to store this new
12369 		 * fragment?. We apply an optimization here based on the
12370 		 * fact that most fragments will be received in order.
12371 		 * So if the offset of this incoming fragment is zero,
12372 		 * it is the first fragment of a new packet. We will
12373 		 * keep it.  Otherwise drop the fragment, as we have
12374 		 * probably pruned the packet already (since the
12375 		 * packet cannot be found).
12376 		 */
12377 		if (pruned && offset != 0) {
12378 			mutex_exit(&ipfb->ipfb_lock);
12379 			freemsg(mp);
12380 			return (B_FALSE);
12381 		}
12382 
12383 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12384 			/*
12385 			 * Too many fragmented packets in this hash
12386 			 * bucket. Free the oldest.
12387 			 */
12388 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12389 		}
12390 
12391 		/* New guy.  Allocate a frag message. */
12392 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12393 		if (mp1 == NULL) {
12394 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12395 			freemsg(mp);
12396 reass_done:
12397 			mutex_exit(&ipfb->ipfb_lock);
12398 			return (B_FALSE);
12399 		}
12400 
12401 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12402 		mp1->b_cont = mp;
12403 
12404 		/* Initialize the fragment header. */
12405 		ipf = (ipf_t *)mp1->b_rptr;
12406 		ipf->ipf_mp = mp1;
12407 		ipf->ipf_ptphn = ipfp;
12408 		ipfp[0] = ipf;
12409 		ipf->ipf_hash_next = NULL;
12410 		ipf->ipf_ident = ident;
12411 		ipf->ipf_protocol = proto;
12412 		ipf->ipf_src = src;
12413 		ipf->ipf_dst = dst;
12414 		ipf->ipf_nf_hdr_len = 0;
12415 		/* Record reassembly start time. */
12416 		ipf->ipf_timestamp = gethrestime_sec();
12417 		/* Record ipf generation and account for frag header */
12418 		ipf->ipf_gen = ill->ill_ipf_gen++;
12419 		ipf->ipf_count = MBLKSIZE(mp1);
12420 		ipf->ipf_last_frag_seen = B_FALSE;
12421 		ipf->ipf_ecn = ecn_info;
12422 		ipf->ipf_num_dups = 0;
12423 		ipfb->ipfb_frag_pkts++;
12424 		ipf->ipf_checksum = 0;
12425 		ipf->ipf_checksum_flags = 0;
12426 
12427 		/* Store checksum value in fragment header */
12428 		if (sum_flags != 0) {
12429 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12430 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12431 			ipf->ipf_checksum = sum_val;
12432 			ipf->ipf_checksum_flags = sum_flags;
12433 		}
12434 
12435 		/*
12436 		 * We handle reassembly two ways.  In the easy case,
12437 		 * where all the fragments show up in order, we do
12438 		 * minimal bookkeeping, and just clip new pieces on
12439 		 * the end.  If we ever see a hole, then we go off
12440 		 * to ip_reassemble which has to mark the pieces and
12441 		 * keep track of the number of holes, etc.  Obviously,
12442 		 * the point of having both mechanisms is so we can
12443 		 * handle the easy case as efficiently as possible.
12444 		 */
12445 		if (offset == 0) {
12446 			/* Easy case, in-order reassembly so far. */
12447 			ipf->ipf_count += msg_len;
12448 			ipf->ipf_tail_mp = tail_mp;
12449 			/*
12450 			 * Keep track of next expected offset in
12451 			 * ipf_end.
12452 			 */
12453 			ipf->ipf_end = end;
12454 			ipf->ipf_nf_hdr_len = hdr_length;
12455 		} else {
12456 			/* Hard case, hole at the beginning. */
12457 			ipf->ipf_tail_mp = NULL;
12458 			/*
12459 			 * ipf_end == 0 means that we have given up
12460 			 * on easy reassembly.
12461 			 */
12462 			ipf->ipf_end = 0;
12463 
12464 			/* Forget checksum offload from now on */
12465 			ipf->ipf_checksum_flags = 0;
12466 
12467 			/*
12468 			 * ipf_hole_cnt is set by ip_reassemble.
12469 			 * ipf_count is updated by ip_reassemble.
12470 			 * No need to check for return value here
12471 			 * as we don't expect reassembly to complete
12472 			 * or fail for the first fragment itself.
12473 			 */
12474 			(void) ip_reassemble(mp, ipf,
12475 			    (frag_offset_flags & IPH_OFFSET) << 3,
12476 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12477 		}
12478 		/* Update per ipfb and ill byte counts */
12479 		ipfb->ipfb_count += ipf->ipf_count;
12480 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12481 		ill->ill_frag_count += ipf->ipf_count;
12482 		/* If the frag timer wasn't already going, start it. */
12483 		mutex_enter(&ill->ill_lock);
12484 		ill_frag_timer_start(ill);
12485 		mutex_exit(&ill->ill_lock);
12486 		goto reass_done;
12487 	}
12488 
12489 	/*
12490 	 * If the packet's flag has changed (it could be coming up
12491 	 * from an interface different than the previous, therefore
12492 	 * possibly different checksum capability), then forget about
12493 	 * any stored checksum states.  Otherwise add the value to
12494 	 * the existing one stored in the fragment header.
12495 	 */
12496 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12497 		sum_val += ipf->ipf_checksum;
12498 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12499 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12500 		ipf->ipf_checksum = sum_val;
12501 	} else if (ipf->ipf_checksum_flags != 0) {
12502 		/* Forget checksum offload from now on */
12503 		ipf->ipf_checksum_flags = 0;
12504 	}
12505 
12506 	/*
12507 	 * We have a new piece of a datagram which is already being
12508 	 * reassembled.  Update the ECN info if all IP fragments
12509 	 * are ECN capable.  If there is one which is not, clear
12510 	 * all the info.  If there is at least one which has CE
12511 	 * code point, IP needs to report that up to transport.
12512 	 */
12513 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12514 		if (ecn_info == IPH_ECN_CE)
12515 			ipf->ipf_ecn = IPH_ECN_CE;
12516 	} else {
12517 		ipf->ipf_ecn = IPH_ECN_NECT;
12518 	}
12519 	if (offset && ipf->ipf_end == offset) {
12520 		/* The new fragment fits at the end */
12521 		ipf->ipf_tail_mp->b_cont = mp;
12522 		/* Update the byte count */
12523 		ipf->ipf_count += msg_len;
12524 		/* Update per ipfb and ill byte counts */
12525 		ipfb->ipfb_count += msg_len;
12526 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12527 		ill->ill_frag_count += msg_len;
12528 		if (frag_offset_flags & IPH_MF) {
12529 			/* More to come. */
12530 			ipf->ipf_end = end;
12531 			ipf->ipf_tail_mp = tail_mp;
12532 			goto reass_done;
12533 		}
12534 	} else {
12535 		/* Go do the hard cases. */
12536 		int ret;
12537 
12538 		if (offset == 0)
12539 			ipf->ipf_nf_hdr_len = hdr_length;
12540 
12541 		/* Save current byte count */
12542 		count = ipf->ipf_count;
12543 		ret = ip_reassemble(mp, ipf,
12544 		    (frag_offset_flags & IPH_OFFSET) << 3,
12545 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12546 		/* Count of bytes added and subtracted (freeb()ed) */
12547 		count = ipf->ipf_count - count;
12548 		if (count) {
12549 			/* Update per ipfb and ill byte counts */
12550 			ipfb->ipfb_count += count;
12551 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12552 			ill->ill_frag_count += count;
12553 		}
12554 		if (ret == IP_REASS_PARTIAL) {
12555 			goto reass_done;
12556 		} else if (ret == IP_REASS_FAILED) {
12557 			/* Reassembly failed. Free up all resources */
12558 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12559 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12560 				IP_REASS_SET_START(t_mp, 0);
12561 				IP_REASS_SET_END(t_mp, 0);
12562 			}
12563 			freemsg(mp);
12564 			goto reass_done;
12565 		}
12566 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12567 	}
12568 	/*
12569 	 * We have completed reassembly.  Unhook the frag header from
12570 	 * the reassembly list.
12571 	 *
12572 	 * Before we free the frag header, record the ECN info
12573 	 * to report back to the transport.
12574 	 */
12575 	ecn_info = ipf->ipf_ecn;
12576 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12577 	ipfp = ipf->ipf_ptphn;
12578 
12579 	/* We need to supply these to caller */
12580 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12581 		sum_val = ipf->ipf_checksum;
12582 	else
12583 		sum_val = 0;
12584 
12585 	mp1 = ipf->ipf_mp;
12586 	count = ipf->ipf_count;
12587 	ipf = ipf->ipf_hash_next;
12588 	if (ipf != NULL)
12589 		ipf->ipf_ptphn = ipfp;
12590 	ipfp[0] = ipf;
12591 	ill->ill_frag_count -= count;
12592 	ASSERT(ipfb->ipfb_count >= count);
12593 	ipfb->ipfb_count -= count;
12594 	ipfb->ipfb_frag_pkts--;
12595 	mutex_exit(&ipfb->ipfb_lock);
12596 	/* Ditch the frag header. */
12597 	mp = mp1->b_cont;
12598 
12599 	freeb(mp1);
12600 
12601 	/* Restore original IP length in header. */
12602 	packet_size = (uint32_t)msgdsize(mp);
12603 	if (packet_size > IP_MAXPACKET) {
12604 		freemsg(mp);
12605 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12606 		return (B_FALSE);
12607 	}
12608 
12609 	if (DB_REF(mp) > 1) {
12610 		mblk_t *mp2 = copymsg(mp);
12611 
12612 		freemsg(mp);
12613 		if (mp2 == NULL) {
12614 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12615 			return (B_FALSE);
12616 		}
12617 		mp = mp2;
12618 	}
12619 	ipha = (ipha_t *)mp->b_rptr;
12620 
12621 	ipha->ipha_length = htons((uint16_t)packet_size);
12622 	/* We're now complete, zip the frag state */
12623 	ipha->ipha_fragment_offset_and_flags = 0;
12624 	/* Record the ECN info. */
12625 	ipha->ipha_type_of_service &= 0xFC;
12626 	ipha->ipha_type_of_service |= ecn_info;
12627 	*mpp = mp;
12628 
12629 	/* Reassembly is successful; return checksum information if needed */
12630 	if (cksum_val != NULL)
12631 		*cksum_val = sum_val;
12632 	if (cksum_flags != NULL)
12633 		*cksum_flags = sum_flags;
12634 
12635 	return (B_TRUE);
12636 }
12637 
12638 /*
12639  * Perform ip header check sum update local options.
12640  * return B_TRUE if all is well, else return B_FALSE and release
12641  * the mp. caller is responsible for decrementing ire ref cnt.
12642  */
12643 static boolean_t
12644 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12645     ip_stack_t *ipst)
12646 {
12647 	mblk_t		*first_mp;
12648 	boolean_t	mctl_present;
12649 	uint16_t	sum;
12650 
12651 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12652 	/*
12653 	 * Don't do the checksum if it has gone through AH/ESP
12654 	 * processing.
12655 	 */
12656 	if (!mctl_present) {
12657 		sum = ip_csum_hdr(ipha);
12658 		if (sum != 0) {
12659 			if (ill != NULL) {
12660 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12661 			} else {
12662 				BUMP_MIB(&ipst->ips_ip_mib,
12663 				    ipIfStatsInCksumErrs);
12664 			}
12665 			freemsg(first_mp);
12666 			return (B_FALSE);
12667 		}
12668 	}
12669 
12670 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12671 		if (mctl_present)
12672 			freeb(first_mp);
12673 		return (B_FALSE);
12674 	}
12675 
12676 	return (B_TRUE);
12677 }
12678 
12679 /*
12680  * All udp packet are delivered to the local host via this routine.
12681  */
12682 void
12683 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12684     ill_t *recv_ill)
12685 {
12686 	uint32_t	sum;
12687 	uint32_t	u1;
12688 	boolean_t	mctl_present;
12689 	conn_t		*connp;
12690 	mblk_t		*first_mp;
12691 	uint16_t	*up;
12692 	ill_t		*ill = (ill_t *)q->q_ptr;
12693 	uint16_t	reass_hck_flags = 0;
12694 	ip_stack_t	*ipst;
12695 
12696 	ASSERT(recv_ill != NULL);
12697 	ipst = recv_ill->ill_ipst;
12698 
12699 #define	rptr    ((uchar_t *)ipha)
12700 
12701 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12702 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12703 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12704 	ASSERT(ill != NULL);
12705 
12706 	/*
12707 	 * FAST PATH for udp packets
12708 	 */
12709 
12710 	/* u1 is # words of IP options */
12711 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12712 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12713 
12714 	/* IP options present */
12715 	if (u1 != 0)
12716 		goto ipoptions;
12717 
12718 	/* Check the IP header checksum.  */
12719 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12720 		/* Clear the IP header h/w cksum flag */
12721 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12722 	} else if (!mctl_present) {
12723 		/*
12724 		 * Don't verify header checksum if this packet is coming
12725 		 * back from AH/ESP as we already did it.
12726 		 */
12727 #define	uph	((uint16_t *)ipha)
12728 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12729 		    uph[6] + uph[7] + uph[8] + uph[9];
12730 #undef	uph
12731 		/* finish doing IP checksum */
12732 		sum = (sum & 0xFFFF) + (sum >> 16);
12733 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12734 		if (sum != 0 && sum != 0xFFFF) {
12735 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12736 			freemsg(first_mp);
12737 			return;
12738 		}
12739 	}
12740 
12741 	/*
12742 	 * Count for SNMP of inbound packets for ire.
12743 	 * if mctl is present this might be a secure packet and
12744 	 * has already been counted for in ip_proto_input().
12745 	 */
12746 	if (!mctl_present) {
12747 		UPDATE_IB_PKT_COUNT(ire);
12748 		ire->ire_last_used_time = lbolt;
12749 	}
12750 
12751 	/* packet part of fragmented IP packet? */
12752 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12753 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12754 		goto fragmented;
12755 	}
12756 
12757 	/* u1 = IP header length (20 bytes) */
12758 	u1 = IP_SIMPLE_HDR_LENGTH;
12759 
12760 	/* packet does not contain complete IP & UDP headers */
12761 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12762 		goto udppullup;
12763 
12764 	/* up points to UDP header */
12765 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12766 #define	iphs    ((uint16_t *)ipha)
12767 
12768 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12769 	if (up[3] != 0) {
12770 		mblk_t *mp1 = mp->b_cont;
12771 		boolean_t cksum_err;
12772 		uint16_t hck_flags = 0;
12773 
12774 		/* Pseudo-header checksum */
12775 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12776 		    iphs[9] + up[2];
12777 
12778 		/*
12779 		 * Revert to software checksum calculation if the interface
12780 		 * isn't capable of checksum offload or if IPsec is present.
12781 		 */
12782 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12783 			hck_flags = DB_CKSUMFLAGS(mp);
12784 
12785 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12786 			IP_STAT(ipst, ip_in_sw_cksum);
12787 
12788 		IP_CKSUM_RECV(hck_flags, u1,
12789 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12790 		    (int32_t)((uchar_t *)up - rptr),
12791 		    mp, mp1, cksum_err);
12792 
12793 		if (cksum_err) {
12794 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12795 			if (hck_flags & HCK_FULLCKSUM)
12796 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12797 			else if (hck_flags & HCK_PARTIALCKSUM)
12798 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12799 			else
12800 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12801 
12802 			freemsg(first_mp);
12803 			return;
12804 		}
12805 	}
12806 
12807 	/* Non-fragmented broadcast or multicast packet? */
12808 	if (ire->ire_type == IRE_BROADCAST)
12809 		goto udpslowpath;
12810 
12811 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12812 	    ire->ire_zoneid, ipst)) != NULL) {
12813 		ASSERT(connp->conn_upq != NULL);
12814 		IP_STAT(ipst, ip_udp_fast_path);
12815 
12816 		if (CONN_UDP_FLOWCTLD(connp)) {
12817 			freemsg(mp);
12818 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
12819 		} else {
12820 			if (!mctl_present) {
12821 				BUMP_MIB(ill->ill_ip_mib,
12822 				    ipIfStatsHCInDelivers);
12823 			}
12824 			/*
12825 			 * mp and first_mp can change.
12826 			 */
12827 			if (ip_udp_check(q, connp, recv_ill,
12828 			    ipha, &mp, &first_mp, mctl_present, ire)) {
12829 				/* Send it upstream */
12830 				(connp->conn_recv)(connp, mp, NULL);
12831 			}
12832 		}
12833 		/*
12834 		 * freeb() cannot deal with null mblk being passed
12835 		 * in and first_mp can be set to null in the call
12836 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12837 		 */
12838 		if (mctl_present && first_mp != NULL) {
12839 			freeb(first_mp);
12840 		}
12841 		CONN_DEC_REF(connp);
12842 		return;
12843 	}
12844 
12845 	/*
12846 	 * if we got here we know the packet is not fragmented and
12847 	 * has no options. The classifier could not find a conn_t and
12848 	 * most likely its an icmp packet so send it through slow path.
12849 	 */
12850 
12851 	goto udpslowpath;
12852 
12853 ipoptions:
12854 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
12855 		goto slow_done;
12856 	}
12857 
12858 	UPDATE_IB_PKT_COUNT(ire);
12859 	ire->ire_last_used_time = lbolt;
12860 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12861 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12862 fragmented:
12863 		/*
12864 		 * "sum" and "reass_hck_flags" are non-zero if the
12865 		 * reassembled packet has a valid hardware computed
12866 		 * checksum information associated with it.
12867 		 */
12868 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
12869 			goto slow_done;
12870 		/*
12871 		 * Make sure that first_mp points back to mp as
12872 		 * the mp we came in with could have changed in
12873 		 * ip_rput_fragment().
12874 		 */
12875 		ASSERT(!mctl_present);
12876 		ipha = (ipha_t *)mp->b_rptr;
12877 		first_mp = mp;
12878 	}
12879 
12880 	/* Now we have a complete datagram, destined for this machine. */
12881 	u1 = IPH_HDR_LENGTH(ipha);
12882 	/* Pull up the UDP header, if necessary. */
12883 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12884 udppullup:
12885 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12886 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12887 			freemsg(first_mp);
12888 			goto slow_done;
12889 		}
12890 		ipha = (ipha_t *)mp->b_rptr;
12891 	}
12892 
12893 	/*
12894 	 * Validate the checksum for the reassembled packet; for the
12895 	 * pullup case we calculate the payload checksum in software.
12896 	 */
12897 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12898 	if (up[3] != 0) {
12899 		boolean_t cksum_err;
12900 
12901 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12902 			IP_STAT(ipst, ip_in_sw_cksum);
12903 
12904 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12905 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12906 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12907 		    iphs[9] + up[2], sum, cksum_err);
12908 
12909 		if (cksum_err) {
12910 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12911 
12912 			if (reass_hck_flags & HCK_FULLCKSUM)
12913 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12914 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12915 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12916 			else
12917 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12918 
12919 			freemsg(first_mp);
12920 			goto slow_done;
12921 		}
12922 	}
12923 udpslowpath:
12924 
12925 	/* Clear hardware checksum flag to be safe */
12926 	DB_CKSUMFLAGS(mp) = 0;
12927 
12928 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12929 	    (ire->ire_type == IRE_BROADCAST),
12930 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
12931 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12932 
12933 slow_done:
12934 	IP_STAT(ipst, ip_udp_slow_path);
12935 	return;
12936 
12937 #undef  iphs
12938 #undef  rptr
12939 }
12940 
12941 /* ARGSUSED */
12942 static mblk_t *
12943 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12944     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12945     ill_rx_ring_t *ill_ring)
12946 {
12947 	conn_t		*connp;
12948 	uint32_t	sum;
12949 	uint32_t	u1;
12950 	uint16_t	*up;
12951 	int		offset;
12952 	ssize_t		len;
12953 	mblk_t		*mp1;
12954 	boolean_t	syn_present = B_FALSE;
12955 	tcph_t		*tcph;
12956 	uint_t		ip_hdr_len;
12957 	ill_t		*ill = (ill_t *)q->q_ptr;
12958 	zoneid_t	zoneid = ire->ire_zoneid;
12959 	boolean_t	cksum_err;
12960 	uint16_t	hck_flags = 0;
12961 	ip_stack_t	*ipst = recv_ill->ill_ipst;
12962 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12963 
12964 #define	rptr	((uchar_t *)ipha)
12965 
12966 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12967 	ASSERT(ill != NULL);
12968 
12969 	/*
12970 	 * FAST PATH for tcp packets
12971 	 */
12972 
12973 	/* u1 is # words of IP options */
12974 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12975 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12976 
12977 	/* IP options present */
12978 	if (u1) {
12979 		goto ipoptions;
12980 	} else if (!mctl_present) {
12981 		/* Check the IP header checksum.  */
12982 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12983 			/* Clear the IP header h/w cksum flag */
12984 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12985 		} else if (!mctl_present) {
12986 			/*
12987 			 * Don't verify header checksum if this packet
12988 			 * is coming back from AH/ESP as we already did it.
12989 			 */
12990 #define	uph	((uint16_t *)ipha)
12991 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12992 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12993 #undef	uph
12994 			/* finish doing IP checksum */
12995 			sum = (sum & 0xFFFF) + (sum >> 16);
12996 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12997 			if (sum != 0 && sum != 0xFFFF) {
12998 				BUMP_MIB(ill->ill_ip_mib,
12999 				    ipIfStatsInCksumErrs);
13000 				goto error;
13001 			}
13002 		}
13003 	}
13004 
13005 	if (!mctl_present) {
13006 		UPDATE_IB_PKT_COUNT(ire);
13007 		ire->ire_last_used_time = lbolt;
13008 	}
13009 
13010 	/* packet part of fragmented IP packet? */
13011 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13012 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13013 		goto fragmented;
13014 	}
13015 
13016 	/* u1 = IP header length (20 bytes) */
13017 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
13018 
13019 	/* does packet contain IP+TCP headers? */
13020 	len = mp->b_wptr - rptr;
13021 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
13022 		IP_STAT(ipst, ip_tcppullup);
13023 		goto tcppullup;
13024 	}
13025 
13026 	/* TCP options present? */
13027 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
13028 
13029 	/*
13030 	 * If options need to be pulled up, then goto tcpoptions.
13031 	 * otherwise we are still in the fast path
13032 	 */
13033 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
13034 		IP_STAT(ipst, ip_tcpoptions);
13035 		goto tcpoptions;
13036 	}
13037 
13038 	/* multiple mblks of tcp data? */
13039 	if ((mp1 = mp->b_cont) != NULL) {
13040 		/* more then two? */
13041 		if (mp1->b_cont != NULL) {
13042 			IP_STAT(ipst, ip_multipkttcp);
13043 			goto multipkttcp;
13044 		}
13045 		len += mp1->b_wptr - mp1->b_rptr;
13046 	}
13047 
13048 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
13049 
13050 	/* part of pseudo checksum */
13051 
13052 	/* TCP datagram length */
13053 	u1 = len - IP_SIMPLE_HDR_LENGTH;
13054 
13055 #define	iphs    ((uint16_t *)ipha)
13056 
13057 #ifdef	_BIG_ENDIAN
13058 	u1 += IPPROTO_TCP;
13059 #else
13060 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13061 #endif
13062 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13063 
13064 	/*
13065 	 * Revert to software checksum calculation if the interface
13066 	 * isn't capable of checksum offload or if IPsec is present.
13067 	 */
13068 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
13069 		hck_flags = DB_CKSUMFLAGS(mp);
13070 
13071 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13072 		IP_STAT(ipst, ip_in_sw_cksum);
13073 
13074 	IP_CKSUM_RECV(hck_flags, u1,
13075 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
13076 	    (int32_t)((uchar_t *)up - rptr),
13077 	    mp, mp1, cksum_err);
13078 
13079 	if (cksum_err) {
13080 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13081 
13082 		if (hck_flags & HCK_FULLCKSUM)
13083 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
13084 		else if (hck_flags & HCK_PARTIALCKSUM)
13085 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
13086 		else
13087 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
13088 
13089 		goto error;
13090 	}
13091 
13092 try_again:
13093 
13094 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
13095 	    zoneid, ipst)) == NULL) {
13096 		/* Send the TH_RST */
13097 		goto no_conn;
13098 	}
13099 
13100 	/*
13101 	 * TCP FAST PATH for AF_INET socket.
13102 	 *
13103 	 * TCP fast path to avoid extra work. An AF_INET socket type
13104 	 * does not have facility to receive extra information via
13105 	 * ip_process or ip_add_info. Also, when the connection was
13106 	 * established, we made a check if this connection is impacted
13107 	 * by any global IPsec policy or per connection policy (a
13108 	 * policy that comes in effect later will not apply to this
13109 	 * connection). Since all this can be determined at the
13110 	 * connection establishment time, a quick check of flags
13111 	 * can avoid extra work.
13112 	 */
13113 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13114 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13115 		ASSERT(first_mp == mp);
13116 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13117 		SET_SQUEUE(mp, tcp_rput_data, connp);
13118 		return (mp);
13119 	}
13120 
13121 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
13122 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
13123 		if (IPCL_IS_TCP(connp)) {
13124 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13125 			DB_CKSUMSTART(mp) =
13126 			    (intptr_t)ip_squeue_get(ill_ring);
13127 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13128 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13129 				BUMP_MIB(ill->ill_ip_mib,
13130 				    ipIfStatsHCInDelivers);
13131 				SET_SQUEUE(mp, connp->conn_recv, connp);
13132 				return (mp);
13133 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13134 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13135 				BUMP_MIB(ill->ill_ip_mib,
13136 				    ipIfStatsHCInDelivers);
13137 				ip_squeue_enter_unbound++;
13138 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13139 				    connp);
13140 				return (mp);
13141 			}
13142 			syn_present = B_TRUE;
13143 		}
13144 
13145 	}
13146 
13147 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13148 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13149 
13150 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13151 		/* No need to send this packet to TCP */
13152 		if ((flags & TH_RST) || (flags & TH_URG)) {
13153 			CONN_DEC_REF(connp);
13154 			freemsg(first_mp);
13155 			return (NULL);
13156 		}
13157 		if (flags & TH_ACK) {
13158 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
13159 			    ipst->ips_netstack->netstack_tcp, connp);
13160 			CONN_DEC_REF(connp);
13161 			return (NULL);
13162 		}
13163 
13164 		CONN_DEC_REF(connp);
13165 		freemsg(first_mp);
13166 		return (NULL);
13167 	}
13168 
13169 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13170 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13171 		    ipha, NULL, mctl_present);
13172 		if (first_mp == NULL) {
13173 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13174 			CONN_DEC_REF(connp);
13175 			return (NULL);
13176 		}
13177 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13178 			ASSERT(syn_present);
13179 			if (mctl_present) {
13180 				ASSERT(first_mp != mp);
13181 				first_mp->b_datap->db_struioflag |=
13182 				    STRUIO_POLICY;
13183 			} else {
13184 				ASSERT(first_mp == mp);
13185 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13186 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13187 			}
13188 		} else {
13189 			/*
13190 			 * Discard first_mp early since we're dealing with a
13191 			 * fully-connected conn_t and tcp doesn't do policy in
13192 			 * this case.
13193 			 */
13194 			if (mctl_present) {
13195 				freeb(first_mp);
13196 				mctl_present = B_FALSE;
13197 			}
13198 			first_mp = mp;
13199 		}
13200 	}
13201 
13202 	/* Initiate IPPF processing for fastpath */
13203 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13204 		uint32_t	ill_index;
13205 
13206 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13207 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13208 		if (mp == NULL) {
13209 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13210 			    "deferred/dropped during IPPF processing\n"));
13211 			CONN_DEC_REF(connp);
13212 			if (mctl_present)
13213 				freeb(first_mp);
13214 			return (NULL);
13215 		} else if (mctl_present) {
13216 			/*
13217 			 * ip_process might return a new mp.
13218 			 */
13219 			ASSERT(first_mp != mp);
13220 			first_mp->b_cont = mp;
13221 		} else {
13222 			first_mp = mp;
13223 		}
13224 
13225 	}
13226 
13227 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13228 		/*
13229 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13230 		 * make sure IPF_RECVIF is passed to ip_add_info.
13231 		 */
13232 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13233 		    IPCL_ZONEID(connp), ipst);
13234 		if (mp == NULL) {
13235 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13236 			CONN_DEC_REF(connp);
13237 			if (mctl_present)
13238 				freeb(first_mp);
13239 			return (NULL);
13240 		} else if (mctl_present) {
13241 			/*
13242 			 * ip_add_info might return a new mp.
13243 			 */
13244 			ASSERT(first_mp != mp);
13245 			first_mp->b_cont = mp;
13246 		} else {
13247 			first_mp = mp;
13248 		}
13249 	}
13250 
13251 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13252 	if (IPCL_IS_TCP(connp)) {
13253 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13254 		return (first_mp);
13255 	} else {
13256 		/* SOCK_RAW, IPPROTO_TCP case */
13257 		(connp->conn_recv)(connp, first_mp, NULL);
13258 		CONN_DEC_REF(connp);
13259 		return (NULL);
13260 	}
13261 
13262 no_conn:
13263 	/* Initiate IPPf processing, if needed. */
13264 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13265 		uint32_t ill_index;
13266 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13267 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13268 		if (first_mp == NULL) {
13269 			return (NULL);
13270 		}
13271 	}
13272 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13273 
13274 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13275 	    ipst->ips_netstack->netstack_tcp, NULL);
13276 	return (NULL);
13277 ipoptions:
13278 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13279 		goto slow_done;
13280 	}
13281 
13282 	UPDATE_IB_PKT_COUNT(ire);
13283 	ire->ire_last_used_time = lbolt;
13284 
13285 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13286 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13287 fragmented:
13288 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
13289 			if (mctl_present)
13290 				freeb(first_mp);
13291 			goto slow_done;
13292 		}
13293 		/*
13294 		 * Make sure that first_mp points back to mp as
13295 		 * the mp we came in with could have changed in
13296 		 * ip_rput_fragment().
13297 		 */
13298 		ASSERT(!mctl_present);
13299 		ipha = (ipha_t *)mp->b_rptr;
13300 		first_mp = mp;
13301 	}
13302 
13303 	/* Now we have a complete datagram, destined for this machine. */
13304 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13305 
13306 	len = mp->b_wptr - mp->b_rptr;
13307 	/* Pull up a minimal TCP header, if necessary. */
13308 	if (len < (u1 + 20)) {
13309 tcppullup:
13310 		if (!pullupmsg(mp, u1 + 20)) {
13311 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13312 			goto error;
13313 		}
13314 		ipha = (ipha_t *)mp->b_rptr;
13315 		len = mp->b_wptr - mp->b_rptr;
13316 	}
13317 
13318 	/*
13319 	 * Extract the offset field from the TCP header.  As usual, we
13320 	 * try to help the compiler more than the reader.
13321 	 */
13322 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13323 	if (offset != 5) {
13324 tcpoptions:
13325 		if (offset < 5) {
13326 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13327 			goto error;
13328 		}
13329 		/*
13330 		 * There must be TCP options.
13331 		 * Make sure we can grab them.
13332 		 */
13333 		offset <<= 2;
13334 		offset += u1;
13335 		if (len < offset) {
13336 			if (!pullupmsg(mp, offset)) {
13337 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13338 				goto error;
13339 			}
13340 			ipha = (ipha_t *)mp->b_rptr;
13341 			len = mp->b_wptr - rptr;
13342 		}
13343 	}
13344 
13345 	/* Get the total packet length in len, including headers. */
13346 	if (mp->b_cont) {
13347 multipkttcp:
13348 		len = msgdsize(mp);
13349 	}
13350 
13351 	/*
13352 	 * Check the TCP checksum by pulling together the pseudo-
13353 	 * header checksum, and passing it to ip_csum to be added in
13354 	 * with the TCP datagram.
13355 	 *
13356 	 * Since we are not using the hwcksum if available we must
13357 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13358 	 * If either of these fails along the way the mblk is freed.
13359 	 * If this logic ever changes and mblk is reused to say send
13360 	 * ICMP's back, then this flag may need to be cleared in
13361 	 * other places as well.
13362 	 */
13363 	DB_CKSUMFLAGS(mp) = 0;
13364 
13365 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13366 
13367 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13368 #ifdef	_BIG_ENDIAN
13369 	u1 += IPPROTO_TCP;
13370 #else
13371 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13372 #endif
13373 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13374 	/*
13375 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13376 	 */
13377 	IP_STAT(ipst, ip_in_sw_cksum);
13378 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13379 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13380 		goto error;
13381 	}
13382 
13383 	IP_STAT(ipst, ip_tcp_slow_path);
13384 	goto try_again;
13385 #undef  iphs
13386 #undef  rptr
13387 
13388 error:
13389 	freemsg(first_mp);
13390 slow_done:
13391 	return (NULL);
13392 }
13393 
13394 /* ARGSUSED */
13395 static void
13396 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13397     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13398 {
13399 	conn_t		*connp;
13400 	uint32_t	sum;
13401 	uint32_t	u1;
13402 	ssize_t		len;
13403 	sctp_hdr_t	*sctph;
13404 	zoneid_t	zoneid = ire->ire_zoneid;
13405 	uint32_t	pktsum;
13406 	uint32_t	calcsum;
13407 	uint32_t	ports;
13408 	in6_addr_t	map_src, map_dst;
13409 	ill_t		*ill = (ill_t *)q->q_ptr;
13410 	ip_stack_t	*ipst;
13411 	sctp_stack_t	*sctps;
13412 
13413 	ASSERT(recv_ill != NULL);
13414 	ipst = recv_ill->ill_ipst;
13415 	sctps = ipst->ips_netstack->netstack_sctp;
13416 
13417 #define	rptr	((uchar_t *)ipha)
13418 
13419 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13420 	ASSERT(ill != NULL);
13421 
13422 	/* u1 is # words of IP options */
13423 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13424 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13425 
13426 	/* IP options present */
13427 	if (u1 > 0) {
13428 		goto ipoptions;
13429 	} else {
13430 		/* Check the IP header checksum.  */
13431 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill) &&
13432 		    !mctl_present) {
13433 #define	uph	((uint16_t *)ipha)
13434 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13435 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13436 #undef	uph
13437 			/* finish doing IP checksum */
13438 			sum = (sum & 0xFFFF) + (sum >> 16);
13439 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13440 			/*
13441 			 * Don't verify header checksum if this packet
13442 			 * is coming back from AH/ESP as we already did it.
13443 			 */
13444 			if (sum != 0 && sum != 0xFFFF) {
13445 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13446 				goto error;
13447 			}
13448 		}
13449 		/*
13450 		 * Since there is no SCTP h/w cksum support yet, just
13451 		 * clear the flag.
13452 		 */
13453 		DB_CKSUMFLAGS(mp) = 0;
13454 	}
13455 
13456 	/*
13457 	 * Don't verify header checksum if this packet is coming
13458 	 * back from AH/ESP as we already did it.
13459 	 */
13460 	if (!mctl_present) {
13461 		UPDATE_IB_PKT_COUNT(ire);
13462 		ire->ire_last_used_time = lbolt;
13463 	}
13464 
13465 	/* packet part of fragmented IP packet? */
13466 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13467 	if (u1 & (IPH_MF | IPH_OFFSET))
13468 		goto fragmented;
13469 
13470 	/* u1 = IP header length (20 bytes) */
13471 	u1 = IP_SIMPLE_HDR_LENGTH;
13472 
13473 find_sctp_client:
13474 	/* Pullup if we don't have the sctp common header. */
13475 	len = MBLKL(mp);
13476 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13477 		if (mp->b_cont == NULL ||
13478 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13479 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13480 			goto error;
13481 		}
13482 		ipha = (ipha_t *)mp->b_rptr;
13483 		len = MBLKL(mp);
13484 	}
13485 
13486 	sctph = (sctp_hdr_t *)(rptr + u1);
13487 #ifdef	DEBUG
13488 	if (!skip_sctp_cksum) {
13489 #endif
13490 		pktsum = sctph->sh_chksum;
13491 		sctph->sh_chksum = 0;
13492 		calcsum = sctp_cksum(mp, u1);
13493 		if (calcsum != pktsum) {
13494 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
13495 			goto error;
13496 		}
13497 		sctph->sh_chksum = pktsum;
13498 #ifdef	DEBUG	/* skip_sctp_cksum */
13499 	}
13500 #endif
13501 	/* get the ports */
13502 	ports = *(uint32_t *)&sctph->sh_sport;
13503 
13504 	IRE_REFRELE(ire);
13505 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13506 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13507 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13508 	    sctps)) == NULL) {
13509 		/* Check for raw socket or OOTB handling */
13510 		goto no_conn;
13511 	}
13512 
13513 	/* Found a client; up it goes */
13514 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13515 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13516 	return;
13517 
13518 no_conn:
13519 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13520 	    ports, mctl_present, flags, B_TRUE, zoneid);
13521 	return;
13522 
13523 ipoptions:
13524 	DB_CKSUMFLAGS(mp) = 0;
13525 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13526 		goto slow_done;
13527 
13528 	UPDATE_IB_PKT_COUNT(ire);
13529 	ire->ire_last_used_time = lbolt;
13530 
13531 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13532 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13533 fragmented:
13534 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
13535 			goto slow_done;
13536 		/*
13537 		 * Make sure that first_mp points back to mp as
13538 		 * the mp we came in with could have changed in
13539 		 * ip_rput_fragment().
13540 		 */
13541 		ASSERT(!mctl_present);
13542 		ipha = (ipha_t *)mp->b_rptr;
13543 		first_mp = mp;
13544 	}
13545 
13546 	/* Now we have a complete datagram, destined for this machine. */
13547 	u1 = IPH_HDR_LENGTH(ipha);
13548 	goto find_sctp_client;
13549 #undef  iphs
13550 #undef  rptr
13551 
13552 error:
13553 	freemsg(first_mp);
13554 slow_done:
13555 	IRE_REFRELE(ire);
13556 }
13557 
13558 #define	VER_BITS	0xF0
13559 #define	VERSION_6	0x60
13560 
13561 static boolean_t
13562 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13563     ipaddr_t *dstp, ip_stack_t *ipst)
13564 {
13565 	uint_t	opt_len;
13566 	ipha_t *ipha;
13567 	ssize_t len;
13568 	uint_t	pkt_len;
13569 
13570 	ASSERT(ill != NULL);
13571 	IP_STAT(ipst, ip_ipoptions);
13572 	ipha = *iphapp;
13573 
13574 #define	rptr    ((uchar_t *)ipha)
13575 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13576 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13577 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13578 		freemsg(mp);
13579 		return (B_FALSE);
13580 	}
13581 
13582 	/* multiple mblk or too short */
13583 	pkt_len = ntohs(ipha->ipha_length);
13584 
13585 	/* Get the number of words of IP options in the IP header. */
13586 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13587 	if (opt_len) {
13588 		/* IP Options present!  Validate and process. */
13589 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13590 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13591 			goto done;
13592 		}
13593 		/*
13594 		 * Recompute complete header length and make sure we
13595 		 * have access to all of it.
13596 		 */
13597 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13598 		if (len > (mp->b_wptr - rptr)) {
13599 			if (len > pkt_len) {
13600 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13601 				goto done;
13602 			}
13603 			if (!pullupmsg(mp, len)) {
13604 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13605 				goto done;
13606 			}
13607 			ipha = (ipha_t *)mp->b_rptr;
13608 		}
13609 		/*
13610 		 * Go off to ip_rput_options which returns the next hop
13611 		 * destination address, which may have been affected
13612 		 * by source routing.
13613 		 */
13614 		IP_STAT(ipst, ip_opt);
13615 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13616 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13617 			return (B_FALSE);
13618 		}
13619 	}
13620 	*iphapp = ipha;
13621 	return (B_TRUE);
13622 done:
13623 	/* clear b_prev - used by ip_mroute_decap */
13624 	mp->b_prev = NULL;
13625 	freemsg(mp);
13626 	return (B_FALSE);
13627 #undef  rptr
13628 }
13629 
13630 /*
13631  * Deal with the fact that there is no ire for the destination.
13632  */
13633 static ire_t *
13634 ip_rput_noire(queue_t *q, mblk_t *mp, int ll_multicast, ipaddr_t dst)
13635 {
13636 	ipha_t	*ipha;
13637 	ill_t	*ill;
13638 	ire_t	*ire;
13639 	boolean_t	check_multirt = B_FALSE;
13640 	ip_stack_t *ipst;
13641 
13642 	ipha = (ipha_t *)mp->b_rptr;
13643 	ill = (ill_t *)q->q_ptr;
13644 
13645 	ASSERT(ill != NULL);
13646 	ipst = ill->ill_ipst;
13647 
13648 	/*
13649 	 * No IRE for this destination, so it can't be for us.
13650 	 * Unless we are forwarding, drop the packet.
13651 	 * We have to let source routed packets through
13652 	 * since we don't yet know if they are 'ping -l'
13653 	 * packets i.e. if they will go out over the
13654 	 * same interface as they came in on.
13655 	 */
13656 	if (ll_multicast) {
13657 		freemsg(mp);
13658 		return (NULL);
13659 	}
13660 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13661 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13662 		freemsg(mp);
13663 		return (NULL);
13664 	}
13665 
13666 	/*
13667 	 * Mark this packet as having originated externally.
13668 	 *
13669 	 * For non-forwarding code path, ire_send later double
13670 	 * checks this interface to see if it is still exists
13671 	 * post-ARP resolution.
13672 	 *
13673 	 * Also, IPQOS uses this to differentiate between
13674 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13675 	 * QOS packet processing in ip_wput_attach_llhdr().
13676 	 * The QoS module can mark the b_band for a fastpath message
13677 	 * or the dl_priority field in a unitdata_req header for
13678 	 * CoS marking. This info can only be found in
13679 	 * ip_wput_attach_llhdr().
13680 	 */
13681 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13682 	/*
13683 	 * Clear the indication that this may have a hardware checksum
13684 	 * as we are not using it
13685 	 */
13686 	DB_CKSUMFLAGS(mp) = 0;
13687 
13688 	ire = ire_forward(dst, &check_multirt, NULL, NULL,
13689 	    MBLK_GETLABEL(mp), ipst);
13690 
13691 	if (ire == NULL && check_multirt) {
13692 		/* Let ip_newroute handle CGTP  */
13693 		ip_newroute(q, mp, dst, NULL, GLOBAL_ZONEID, ipst);
13694 		return (NULL);
13695 	}
13696 
13697 	if (ire != NULL)
13698 		return (ire);
13699 
13700 	mp->b_prev = mp->b_next = 0;
13701 	/* send icmp unreachable */
13702 	q = WR(q);
13703 	/* Sent by forwarding path, and router is global zone */
13704 	if (ip_source_routed(ipha, ipst)) {
13705 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13706 		    GLOBAL_ZONEID, ipst);
13707 	} else {
13708 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13709 		    ipst);
13710 	}
13711 
13712 	return (NULL);
13713 
13714 }
13715 
13716 /*
13717  * check ip header length and align it.
13718  */
13719 static boolean_t
13720 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13721 {
13722 	ssize_t len;
13723 	ill_t *ill;
13724 	ipha_t	*ipha;
13725 
13726 	len = MBLKL(mp);
13727 
13728 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13729 		ill = (ill_t *)q->q_ptr;
13730 
13731 		if (!OK_32PTR(mp->b_rptr))
13732 			IP_STAT(ipst, ip_notaligned1);
13733 		else
13734 			IP_STAT(ipst, ip_notaligned2);
13735 		/* Guard against bogus device drivers */
13736 		if (len < 0) {
13737 			/* clear b_prev - used by ip_mroute_decap */
13738 			mp->b_prev = NULL;
13739 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13740 			freemsg(mp);
13741 			return (B_FALSE);
13742 		}
13743 
13744 		if (ip_rput_pullups++ == 0) {
13745 			ipha = (ipha_t *)mp->b_rptr;
13746 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13747 			    "ip_check_and_align_header: %s forced us to "
13748 			    " pullup pkt, hdr len %ld, hdr addr %p",
13749 			    ill->ill_name, len, ipha);
13750 		}
13751 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13752 			/* clear b_prev - used by ip_mroute_decap */
13753 			mp->b_prev = NULL;
13754 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13755 			freemsg(mp);
13756 			return (B_FALSE);
13757 		}
13758 	}
13759 	return (B_TRUE);
13760 }
13761 
13762 ire_t *
13763 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13764 {
13765 	ire_t		*new_ire;
13766 	ill_t		*ire_ill;
13767 	uint_t		ifindex;
13768 	ip_stack_t	*ipst = ill->ill_ipst;
13769 	boolean_t	strict_check = B_FALSE;
13770 
13771 	/*
13772 	 * This packet came in on an interface other than the one associated
13773 	 * with the first ire we found for the destination address. We do
13774 	 * another ire lookup here, using the ingress ill, to see if the
13775 	 * interface is in an interface group.
13776 	 * As long as the ills belong to the same group, we don't consider
13777 	 * them to be arriving on the wrong interface. Thus, if the switch
13778 	 * is doing inbound load spreading, we won't drop packets when the
13779 	 * ip*_strict_dst_multihoming switch is on. Note, the same holds true
13780 	 * for 'usesrc groups' where the destination address may belong to
13781 	 * another interface to allow multipathing to happen.
13782 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
13783 	 * where the local address may not be unique. In this case we were
13784 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
13785 	 * actually returned. The new lookup, which is more specific, should
13786 	 * only find the IRE_LOCAL associated with the ingress ill if one
13787 	 * exists.
13788 	 */
13789 
13790 	if (ire->ire_ipversion == IPV4_VERSION) {
13791 		if (ipst->ips_ip_strict_dst_multihoming)
13792 			strict_check = B_TRUE;
13793 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
13794 		    ill->ill_ipif, ALL_ZONES, NULL,
13795 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13796 	} else {
13797 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
13798 		if (ipst->ips_ipv6_strict_dst_multihoming)
13799 			strict_check = B_TRUE;
13800 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
13801 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
13802 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13803 	}
13804 	/*
13805 	 * If the same ire that was returned in ip_input() is found then this
13806 	 * is an indication that interface groups are in use. The packet
13807 	 * arrived on a different ill in the group than the one associated with
13808 	 * the destination address.  If a different ire was found then the same
13809 	 * IP address must be hosted on multiple ills. This is possible with
13810 	 * unnumbered point2point interfaces. We switch to use this new ire in
13811 	 * order to have accurate interface statistics.
13812 	 */
13813 	if (new_ire != NULL) {
13814 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
13815 			ire_refrele(ire);
13816 			ire = new_ire;
13817 		} else {
13818 			ire_refrele(new_ire);
13819 		}
13820 		return (ire);
13821 	} else if ((ire->ire_rfq == NULL) &&
13822 	    (ire->ire_ipversion == IPV4_VERSION)) {
13823 		/*
13824 		 * The best match could have been the original ire which
13825 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
13826 		 * the strict multihoming checks are irrelevant as we consider
13827 		 * local addresses hosted on lo0 to be interface agnostic. We
13828 		 * only expect a null ire_rfq on IREs which are associated with
13829 		 * lo0 hence we can return now.
13830 		 */
13831 		return (ire);
13832 	}
13833 
13834 	/*
13835 	 * Chase pointers once and store locally.
13836 	 */
13837 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
13838 	    (ill_t *)(ire->ire_rfq->q_ptr);
13839 	ifindex = ill->ill_usesrc_ifindex;
13840 
13841 	/*
13842 	 * Check if it's a legal address on the 'usesrc' interface.
13843 	 */
13844 	if ((ifindex != 0) && (ire_ill != NULL) &&
13845 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
13846 		return (ire);
13847 	}
13848 
13849 	/*
13850 	 * If the ip*_strict_dst_multihoming switch is on then we can
13851 	 * only accept this packet if the interface is marked as routing.
13852 	 */
13853 	if (!(strict_check))
13854 		return (ire);
13855 
13856 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
13857 	    ILLF_ROUTER) != 0) {
13858 		return (ire);
13859 	}
13860 
13861 	ire_refrele(ire);
13862 	return (NULL);
13863 }
13864 
13865 ire_t *
13866 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13867 {
13868 	ipha_t	*ipha;
13869 	ipaddr_t ip_dst, ip_src;
13870 	ire_t	*src_ire = NULL;
13871 	ill_t	*stq_ill;
13872 	uint_t	hlen;
13873 	uint_t	pkt_len;
13874 	uint32_t sum;
13875 	queue_t	*dev_q;
13876 	boolean_t check_multirt = B_FALSE;
13877 	ip_stack_t *ipst = ill->ill_ipst;
13878 
13879 	ipha = (ipha_t *)mp->b_rptr;
13880 
13881 	/*
13882 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13883 	 * The loopback address check for both src and dst has already
13884 	 * been checked in ip_input
13885 	 */
13886 	ip_dst = ntohl(dst);
13887 	ip_src = ntohl(ipha->ipha_src);
13888 
13889 	if (ip_dst == INADDR_ANY || IN_BADCLASS(ip_dst) ||
13890 	    IN_CLASSD(ip_src)) {
13891 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13892 		goto drop;
13893 	}
13894 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13895 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
13896 
13897 	if (src_ire != NULL) {
13898 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13899 		goto drop;
13900 	}
13901 
13902 
13903 	/* No ire cache of nexthop. So first create one  */
13904 	if (ire == NULL) {
13905 		ire = ire_forward(dst, &check_multirt, NULL, NULL, NULL, ipst);
13906 		/*
13907 		 * We only come to ip_fast_forward if ip_cgtp_filter is
13908 		 * is not set. So upon return from ire_forward
13909 		 * check_multirt should remain as false.
13910 		 */
13911 		ASSERT(!check_multirt);
13912 		if (ire == NULL) {
13913 			/* An attempt was made to forward the packet */
13914 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13915 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13916 			mp->b_prev = mp->b_next = 0;
13917 			/* send icmp unreachable */
13918 			/* Sent by forwarding path, and router is global zone */
13919 			if (ip_source_routed(ipha, ipst)) {
13920 				icmp_unreachable(ill->ill_wq, mp,
13921 				    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID,
13922 				    ipst);
13923 			} else {
13924 				icmp_unreachable(ill->ill_wq, mp,
13925 				    ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13926 				    ipst);
13927 			}
13928 			return (ire);
13929 		}
13930 	}
13931 
13932 	/*
13933 	 * Forwarding fastpath exception case:
13934 	 * If either of the follwoing case is true, we take
13935 	 * the slowpath
13936 	 *	o forwarding is not enabled
13937 	 *	o incoming and outgoing interface are the same, or the same
13938 	 *	  IPMP group
13939 	 *	o corresponding ire is in incomplete state
13940 	 *	o packet needs fragmentation
13941 	 *
13942 	 * The codeflow from here on is thus:
13943 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
13944 	 */
13945 	pkt_len = ntohs(ipha->ipha_length);
13946 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
13947 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
13948 	    !(ill->ill_flags & ILLF_ROUTER) ||
13949 	    (ill == stq_ill) ||
13950 	    (ill->ill_group != NULL && ill->ill_group == stq_ill->ill_group) ||
13951 	    (ire->ire_nce == NULL) ||
13952 	    (ire->ire_nce->nce_state != ND_REACHABLE) ||
13953 	    (pkt_len > ire->ire_max_frag) ||
13954 	    ipha->ipha_ttl <= 1) {
13955 		ip_rput_process_forward(ill->ill_rq, mp, ire,
13956 		    ipha, ill, B_FALSE);
13957 		return (ire);
13958 	}
13959 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13960 
13961 	DTRACE_PROBE4(ip4__forwarding__start,
13962 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
13963 
13964 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
13965 	    ipst->ips_ipv4firewall_forwarding,
13966 	    ill, stq_ill, ipha, mp, mp, ipst);
13967 
13968 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
13969 
13970 	if (mp == NULL)
13971 		goto drop;
13972 
13973 	mp->b_datap->db_struioun.cksum.flags = 0;
13974 	/* Adjust the checksum to reflect the ttl decrement. */
13975 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
13976 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
13977 	ipha->ipha_ttl--;
13978 
13979 	dev_q = ire->ire_stq->q_next;
13980 	if ((dev_q->q_next != NULL ||
13981 	    dev_q->q_first != NULL) && !canput(dev_q)) {
13982 		goto indiscard;
13983 	}
13984 
13985 	hlen = ire->ire_nce->nce_fp_mp != NULL ?
13986 	    MBLKL(ire->ire_nce->nce_fp_mp) : 0;
13987 
13988 	if (hlen != 0 || ire->ire_nce->nce_res_mp != NULL) {
13989 		mblk_t *mpip = mp;
13990 
13991 		mp = ip_wput_attach_llhdr(mpip, ire, 0, 0);
13992 		if (mp != NULL) {
13993 			DTRACE_PROBE4(ip4__physical__out__start,
13994 			    ill_t *, NULL, ill_t *, stq_ill,
13995 			    ipha_t *, ipha, mblk_t *, mp);
13996 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
13997 			    ipst->ips_ipv4firewall_physical_out,
13998 			    NULL, stq_ill, ipha, mp, mpip, ipst);
13999 			DTRACE_PROBE1(ip4__physical__out__end, mblk_t *,
14000 			    mp);
14001 			if (mp == NULL)
14002 				goto drop;
14003 
14004 			UPDATE_IB_PKT_COUNT(ire);
14005 			ire->ire_last_used_time = lbolt;
14006 			BUMP_MIB(stq_ill->ill_ip_mib,
14007 			    ipIfStatsHCOutForwDatagrams);
14008 			BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14009 			UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets,
14010 			    pkt_len);
14011 			putnext(ire->ire_stq, mp);
14012 			return (ire);
14013 		}
14014 	}
14015 
14016 indiscard:
14017 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14018 drop:
14019 	if (mp != NULL)
14020 		freemsg(mp);
14021 	if (src_ire != NULL)
14022 		ire_refrele(src_ire);
14023 	return (ire);
14024 
14025 }
14026 
14027 /*
14028  * This function is called in the forwarding slowpath, when
14029  * either the ire lacks the link-layer address, or the packet needs
14030  * further processing(eg. fragmentation), before transmission.
14031  */
14032 
14033 static void
14034 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14035     ill_t *ill, boolean_t ll_multicast)
14036 {
14037 	ill_group_t	*ill_group;
14038 	ill_group_t	*ire_group;
14039 	queue_t		*dev_q;
14040 	ire_t		*src_ire;
14041 	ip_stack_t	*ipst = ill->ill_ipst;
14042 
14043 	ASSERT(ire->ire_stq != NULL);
14044 
14045 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14046 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14047 
14048 	if (ll_multicast != 0) {
14049 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14050 		goto drop_pkt;
14051 	}
14052 
14053 	/*
14054 	 * check if ipha_src is a broadcast address. Note that this
14055 	 * check is redundant when we get here from ip_fast_forward()
14056 	 * which has already done this check. However, since we can
14057 	 * also get here from ip_rput_process_broadcast() or, for
14058 	 * for the slow path through ip_fast_forward(), we perform
14059 	 * the check again for code-reusability
14060 	 */
14061 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14062 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14063 	if (src_ire != NULL || ntohl(ipha->ipha_dst) == INADDR_ANY ||
14064 	    IN_BADCLASS(ntohl(ipha->ipha_dst))) {
14065 		if (src_ire != NULL)
14066 			ire_refrele(src_ire);
14067 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14068 		ip2dbg(("ip_rput_process_forward: Received packet with"
14069 		    " bad src/dst address on %s\n", ill->ill_name));
14070 		goto drop_pkt;
14071 	}
14072 
14073 	ill_group = ill->ill_group;
14074 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
14075 	/*
14076 	 * Check if we want to forward this one at this time.
14077 	 * We allow source routed packets on a host provided that
14078 	 * they go out the same interface or same interface group
14079 	 * as they came in on.
14080 	 *
14081 	 * XXX To be quicker, we may wish to not chase pointers to
14082 	 * get the ILLF_ROUTER flag and instead store the
14083 	 * forwarding policy in the ire.  An unfortunate
14084 	 * side-effect of that would be requiring an ire flush
14085 	 * whenever the ILLF_ROUTER flag changes.
14086 	 */
14087 	if (((ill->ill_flags &
14088 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
14089 	    ILLF_ROUTER) == 0) &&
14090 	    !(ip_source_routed(ipha, ipst) && (ire->ire_rfq == q ||
14091 	    (ill_group != NULL && ill_group == ire_group)))) {
14092 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14093 		if (ip_source_routed(ipha, ipst)) {
14094 			q = WR(q);
14095 			/*
14096 			 * Clear the indication that this may have
14097 			 * hardware checksum as we are not using it.
14098 			 */
14099 			DB_CKSUMFLAGS(mp) = 0;
14100 			/* Sent by forwarding path, and router is global zone */
14101 			icmp_unreachable(q, mp,
14102 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
14103 			return;
14104 		}
14105 		goto drop_pkt;
14106 	}
14107 
14108 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14109 
14110 	/* Packet is being forwarded. Turning off hwcksum flag. */
14111 	DB_CKSUMFLAGS(mp) = 0;
14112 	if (ipst->ips_ip_g_send_redirects) {
14113 		/*
14114 		 * Check whether the incoming interface and outgoing
14115 		 * interface is part of the same group. If so,
14116 		 * send redirects.
14117 		 *
14118 		 * Check the source address to see if it originated
14119 		 * on the same logical subnet it is going back out on.
14120 		 * If so, we should be able to send it a redirect.
14121 		 * Avoid sending a redirect if the destination
14122 		 * is directly connected (i.e., ipha_dst is the same
14123 		 * as ire_gateway_addr or the ire_addr of the
14124 		 * nexthop IRE_CACHE ), or if the packet was source
14125 		 * routed out this interface.
14126 		 */
14127 		ipaddr_t src, nhop;
14128 		mblk_t	*mp1;
14129 		ire_t	*nhop_ire = NULL;
14130 
14131 		/*
14132 		 * Check whether ire_rfq and q are from the same ill
14133 		 * or if they are not same, they at least belong
14134 		 * to the same group. If so, send redirects.
14135 		 */
14136 		if ((ire->ire_rfq == q ||
14137 		    (ill_group != NULL && ill_group == ire_group)) &&
14138 		    !ip_source_routed(ipha, ipst)) {
14139 
14140 			nhop = (ire->ire_gateway_addr != 0 ?
14141 			    ire->ire_gateway_addr : ire->ire_addr);
14142 
14143 			if (ipha->ipha_dst == nhop) {
14144 				/*
14145 				 * We avoid sending a redirect if the
14146 				 * destination is directly connected
14147 				 * because it is possible that multiple
14148 				 * IP subnets may have been configured on
14149 				 * the link, and the source may not
14150 				 * be on the same subnet as ip destination,
14151 				 * even though they are on the same
14152 				 * physical link.
14153 				 */
14154 				goto sendit;
14155 			}
14156 
14157 			src = ipha->ipha_src;
14158 
14159 			/*
14160 			 * We look up the interface ire for the nexthop,
14161 			 * to see if ipha_src is in the same subnet
14162 			 * as the nexthop.
14163 			 *
14164 			 * Note that, if, in the future, IRE_CACHE entries
14165 			 * are obsoleted,  this lookup will not be needed,
14166 			 * as the ire passed to this function will be the
14167 			 * same as the nhop_ire computed below.
14168 			 */
14169 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14170 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14171 			    0, NULL, MATCH_IRE_TYPE, ipst);
14172 
14173 			if (nhop_ire != NULL) {
14174 				if ((src & nhop_ire->ire_mask) ==
14175 				    (nhop & nhop_ire->ire_mask)) {
14176 					/*
14177 					 * The source is directly connected.
14178 					 * Just copy the ip header (which is
14179 					 * in the first mblk)
14180 					 */
14181 					mp1 = copyb(mp);
14182 					if (mp1 != NULL) {
14183 						icmp_send_redirect(WR(q), mp1,
14184 						    nhop, ipst);
14185 					}
14186 				}
14187 				ire_refrele(nhop_ire);
14188 			}
14189 		}
14190 	}
14191 sendit:
14192 	dev_q = ire->ire_stq->q_next;
14193 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
14194 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14195 		freemsg(mp);
14196 		return;
14197 	}
14198 
14199 	ip_rput_forward(ire, ipha, mp, ill);
14200 	return;
14201 
14202 drop_pkt:
14203 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14204 	freemsg(mp);
14205 }
14206 
14207 ire_t *
14208 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14209     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14210 {
14211 	queue_t		*q;
14212 	uint16_t	hcksumflags;
14213 	ip_stack_t	*ipst = ill->ill_ipst;
14214 
14215 	q = *qp;
14216 
14217 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14218 
14219 	/*
14220 	 * Clear the indication that this may have hardware
14221 	 * checksum as we are not using it for forwarding.
14222 	 */
14223 	hcksumflags = DB_CKSUMFLAGS(mp);
14224 	DB_CKSUMFLAGS(mp) = 0;
14225 
14226 	/*
14227 	 * Directed broadcast forwarding: if the packet came in over a
14228 	 * different interface then it is routed out over we can forward it.
14229 	 */
14230 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14231 		ire_refrele(ire);
14232 		freemsg(mp);
14233 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14234 		return (NULL);
14235 	}
14236 	/*
14237 	 * For multicast we have set dst to be INADDR_BROADCAST
14238 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
14239 	 * only for broadcast packets.
14240 	 */
14241 	if (!CLASSD(ipha->ipha_dst)) {
14242 		ire_t *new_ire;
14243 		ipif_t *ipif;
14244 		/*
14245 		 * For ill groups, as the switch duplicates broadcasts
14246 		 * across all the ports, we need to filter out and
14247 		 * send up only one copy. There is one copy for every
14248 		 * broadcast address on each ill. Thus, we look for a
14249 		 * specific IRE on this ill and look at IRE_MARK_NORECV
14250 		 * later to see whether this ill is eligible to receive
14251 		 * them or not. ill_nominate_bcast_rcv() nominates only
14252 		 * one set of IREs for receiving.
14253 		 */
14254 
14255 		ipif = ipif_get_next_ipif(NULL, ill);
14256 		if (ipif == NULL) {
14257 			ire_refrele(ire);
14258 			freemsg(mp);
14259 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14260 			return (NULL);
14261 		}
14262 		new_ire = ire_ctable_lookup(dst, 0, 0,
14263 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14264 		ipif_refrele(ipif);
14265 
14266 		if (new_ire != NULL) {
14267 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
14268 				ire_refrele(ire);
14269 				ire_refrele(new_ire);
14270 				freemsg(mp);
14271 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14272 				return (NULL);
14273 			}
14274 			/*
14275 			 * In the special case of multirouted broadcast
14276 			 * packets, we unconditionally need to "gateway"
14277 			 * them to the appropriate interface here.
14278 			 * In the normal case, this cannot happen, because
14279 			 * there is no broadcast IRE tagged with the
14280 			 * RTF_MULTIRT flag.
14281 			 */
14282 			if (new_ire->ire_flags & RTF_MULTIRT) {
14283 				ire_refrele(new_ire);
14284 				if (ire->ire_rfq != NULL) {
14285 					q = ire->ire_rfq;
14286 					*qp = q;
14287 				}
14288 			} else {
14289 				ire_refrele(ire);
14290 				ire = new_ire;
14291 			}
14292 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14293 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14294 				/*
14295 				 * Free the message if
14296 				 * ip_g_forward_directed_bcast is turned
14297 				 * off for non-local broadcast.
14298 				 */
14299 				ire_refrele(ire);
14300 				freemsg(mp);
14301 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14302 				return (NULL);
14303 			}
14304 		} else {
14305 			/*
14306 			 * This CGTP packet successfully passed the
14307 			 * CGTP filter, but the related CGTP
14308 			 * broadcast IRE has not been found,
14309 			 * meaning that the redundant ipif is
14310 			 * probably down. However, if we discarded
14311 			 * this packet, its duplicate would be
14312 			 * filtered out by the CGTP filter so none
14313 			 * of them would get through. So we keep
14314 			 * going with this one.
14315 			 */
14316 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14317 			if (ire->ire_rfq != NULL) {
14318 				q = ire->ire_rfq;
14319 				*qp = q;
14320 			}
14321 		}
14322 	}
14323 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14324 		/*
14325 		 * Verify that there are not more then one
14326 		 * IRE_BROADCAST with this broadcast address which
14327 		 * has ire_stq set.
14328 		 * TODO: simplify, loop over all IRE's
14329 		 */
14330 		ire_t	*ire1;
14331 		int	num_stq = 0;
14332 		mblk_t	*mp1;
14333 
14334 		/* Find the first one with ire_stq set */
14335 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14336 		for (ire1 = ire; ire1 &&
14337 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14338 		    ire1 = ire1->ire_next)
14339 			;
14340 		if (ire1) {
14341 			ire_refrele(ire);
14342 			ire = ire1;
14343 			IRE_REFHOLD(ire);
14344 		}
14345 
14346 		/* Check if there are additional ones with stq set */
14347 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14348 			if (ire->ire_addr != ire1->ire_addr)
14349 				break;
14350 			if (ire1->ire_stq) {
14351 				num_stq++;
14352 				break;
14353 			}
14354 		}
14355 		rw_exit(&ire->ire_bucket->irb_lock);
14356 		if (num_stq == 1 && ire->ire_stq != NULL) {
14357 			ip1dbg(("ip_rput_process_broadcast: directed "
14358 			    "broadcast to 0x%x\n",
14359 			    ntohl(ire->ire_addr)));
14360 			mp1 = copymsg(mp);
14361 			if (mp1) {
14362 				switch (ipha->ipha_protocol) {
14363 				case IPPROTO_UDP:
14364 					ip_udp_input(q, mp1, ipha, ire, ill);
14365 					break;
14366 				default:
14367 					ip_proto_input(q, mp1, ipha, ire, ill,
14368 					    B_FALSE);
14369 					break;
14370 				}
14371 			}
14372 			/*
14373 			 * Adjust ttl to 2 (1+1 - the forward engine
14374 			 * will decrement it by one.
14375 			 */
14376 			if (ip_csum_hdr(ipha)) {
14377 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14378 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14379 				freemsg(mp);
14380 				ire_refrele(ire);
14381 				return (NULL);
14382 			}
14383 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14384 			ipha->ipha_hdr_checksum = 0;
14385 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14386 			ip_rput_process_forward(q, mp, ire, ipha,
14387 			    ill, ll_multicast);
14388 			ire_refrele(ire);
14389 			return (NULL);
14390 		}
14391 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14392 		    ntohl(ire->ire_addr)));
14393 	}
14394 
14395 
14396 	/* Restore any hardware checksum flags */
14397 	DB_CKSUMFLAGS(mp) = hcksumflags;
14398 	return (ire);
14399 }
14400 
14401 /* ARGSUSED */
14402 static boolean_t
14403 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14404     int *ll_multicast, ipaddr_t *dstp)
14405 {
14406 	ip_stack_t	*ipst = ill->ill_ipst;
14407 
14408 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14409 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14410 	    ntohs(ipha->ipha_length));
14411 
14412 	/*
14413 	 * Forward packets only if we have joined the allmulti
14414 	 * group on this interface.
14415 	 */
14416 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14417 		int retval;
14418 
14419 		/*
14420 		 * Clear the indication that this may have hardware
14421 		 * checksum as we are not using it.
14422 		 */
14423 		DB_CKSUMFLAGS(mp) = 0;
14424 		retval = ip_mforward(ill, ipha, mp);
14425 		/* ip_mforward updates mib variables if needed */
14426 		/* clear b_prev - used by ip_mroute_decap */
14427 		mp->b_prev = NULL;
14428 
14429 		switch (retval) {
14430 		case 0:
14431 			/*
14432 			 * pkt is okay and arrived on phyint.
14433 			 *
14434 			 * If we are running as a multicast router
14435 			 * we need to see all IGMP and/or PIM packets.
14436 			 */
14437 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14438 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14439 				goto done;
14440 			}
14441 			break;
14442 		case -1:
14443 			/* pkt is mal-formed, toss it */
14444 			goto drop_pkt;
14445 		case 1:
14446 			/* pkt is okay and arrived on a tunnel */
14447 			/*
14448 			 * If we are running a multicast router
14449 			 *  we need to see all igmp packets.
14450 			 */
14451 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14452 				*dstp = INADDR_BROADCAST;
14453 				*ll_multicast = 1;
14454 				return (B_FALSE);
14455 			}
14456 
14457 			goto drop_pkt;
14458 		}
14459 	}
14460 
14461 	ILM_WALKER_HOLD(ill);
14462 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14463 		/*
14464 		 * This might just be caused by the fact that
14465 		 * multiple IP Multicast addresses map to the same
14466 		 * link layer multicast - no need to increment counter!
14467 		 */
14468 		ILM_WALKER_RELE(ill);
14469 		freemsg(mp);
14470 		return (B_TRUE);
14471 	}
14472 	ILM_WALKER_RELE(ill);
14473 done:
14474 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14475 	/*
14476 	 * This assumes the we deliver to all streams for multicast
14477 	 * and broadcast packets.
14478 	 */
14479 	*dstp = INADDR_BROADCAST;
14480 	*ll_multicast = 1;
14481 	return (B_FALSE);
14482 drop_pkt:
14483 	ip2dbg(("ip_rput: drop pkt\n"));
14484 	freemsg(mp);
14485 	return (B_TRUE);
14486 }
14487 
14488 static boolean_t
14489 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14490     int *ll_multicast, mblk_t **mpp)
14491 {
14492 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14493 	boolean_t must_copy = B_FALSE;
14494 	struct iocblk   *iocp;
14495 	ipha_t		*ipha;
14496 	ip_stack_t	*ipst = ill->ill_ipst;
14497 
14498 #define	rptr    ((uchar_t *)ipha)
14499 
14500 	first_mp = *first_mpp;
14501 	mp = *mpp;
14502 
14503 	ASSERT(first_mp == mp);
14504 
14505 	/*
14506 	 * if db_ref > 1 then copymsg and free original. Packet may be
14507 	 * changed and do not want other entity who has a reference to this
14508 	 * message to trip over the changes. This is a blind change because
14509 	 * trying to catch all places that might change packet is too
14510 	 * difficult (since it may be a module above this one)
14511 	 *
14512 	 * This corresponds to the non-fast path case. We walk down the full
14513 	 * chain in this case, and check the db_ref count of all the dblks,
14514 	 * and do a copymsg if required. It is possible that the db_ref counts
14515 	 * of the data blocks in the mblk chain can be different.
14516 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14517 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14518 	 * 'snoop' is running.
14519 	 */
14520 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14521 		if (mp1->b_datap->db_ref > 1) {
14522 			must_copy = B_TRUE;
14523 			break;
14524 		}
14525 	}
14526 
14527 	if (must_copy) {
14528 		mp1 = copymsg(mp);
14529 		if (mp1 == NULL) {
14530 			for (mp1 = mp; mp1 != NULL;
14531 			    mp1 = mp1->b_cont) {
14532 				mp1->b_next = NULL;
14533 				mp1->b_prev = NULL;
14534 			}
14535 			freemsg(mp);
14536 			if (ill != NULL) {
14537 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14538 			} else {
14539 				BUMP_MIB(&ipst->ips_ip_mib,
14540 				    ipIfStatsInDiscards);
14541 			}
14542 			return (B_TRUE);
14543 		}
14544 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14545 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14546 			/* Copy b_prev - used by ip_mroute_decap */
14547 			to_mp->b_prev = from_mp->b_prev;
14548 			from_mp->b_prev = NULL;
14549 		}
14550 		*first_mpp = first_mp = mp1;
14551 		freemsg(mp);
14552 		mp = mp1;
14553 		*mpp = mp1;
14554 	}
14555 
14556 	ipha = (ipha_t *)mp->b_rptr;
14557 
14558 	/*
14559 	 * previous code has a case for M_DATA.
14560 	 * We want to check how that happens.
14561 	 */
14562 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14563 	switch (first_mp->b_datap->db_type) {
14564 	case M_PROTO:
14565 	case M_PCPROTO:
14566 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14567 		    DL_UNITDATA_IND) {
14568 			/* Go handle anything other than data elsewhere. */
14569 			ip_rput_dlpi(q, mp);
14570 			return (B_TRUE);
14571 		}
14572 		*ll_multicast = ((dl_unitdata_ind_t *)rptr)->dl_group_address;
14573 		/* Ditch the DLPI header. */
14574 		mp1 = mp->b_cont;
14575 		ASSERT(first_mp == mp);
14576 		*first_mpp = mp1;
14577 		freeb(mp);
14578 		*mpp = mp1;
14579 		return (B_FALSE);
14580 	case M_IOCACK:
14581 		ip1dbg(("got iocack "));
14582 		iocp = (struct iocblk *)mp->b_rptr;
14583 		switch (iocp->ioc_cmd) {
14584 		case DL_IOC_HDR_INFO:
14585 			ill = (ill_t *)q->q_ptr;
14586 			ill_fastpath_ack(ill, mp);
14587 			return (B_TRUE);
14588 		case SIOCSTUNPARAM:
14589 		case OSIOCSTUNPARAM:
14590 			/* Go through qwriter_ip */
14591 			break;
14592 		case SIOCGTUNPARAM:
14593 		case OSIOCGTUNPARAM:
14594 			ip_rput_other(NULL, q, mp, NULL);
14595 			return (B_TRUE);
14596 		default:
14597 			putnext(q, mp);
14598 			return (B_TRUE);
14599 		}
14600 		/* FALLTHRU */
14601 	case M_ERROR:
14602 	case M_HANGUP:
14603 		/*
14604 		 * Since this is on the ill stream we unconditionally
14605 		 * bump up the refcount
14606 		 */
14607 		ill_refhold(ill);
14608 		qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14609 		return (B_TRUE);
14610 	case M_CTL:
14611 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14612 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14613 		    IPHADA_M_CTL)) {
14614 			/*
14615 			 * It's an IPsec accelerated packet.
14616 			 * Make sure that the ill from which we received the
14617 			 * packet has enabled IPsec hardware acceleration.
14618 			 */
14619 			if (!(ill->ill_capabilities &
14620 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14621 				/* IPsec kstats: bean counter */
14622 				freemsg(mp);
14623 				return (B_TRUE);
14624 			}
14625 
14626 			/*
14627 			 * Make mp point to the mblk following the M_CTL,
14628 			 * then process according to type of mp.
14629 			 * After this processing, first_mp will point to
14630 			 * the data-attributes and mp to the pkt following
14631 			 * the M_CTL.
14632 			 */
14633 			mp = first_mp->b_cont;
14634 			if (mp == NULL) {
14635 				freemsg(first_mp);
14636 				return (B_TRUE);
14637 			}
14638 			/*
14639 			 * A Hardware Accelerated packet can only be M_DATA
14640 			 * ESP or AH packet.
14641 			 */
14642 			if (mp->b_datap->db_type != M_DATA) {
14643 				/* non-M_DATA IPsec accelerated packet */
14644 				IPSECHW_DEBUG(IPSECHW_PKT,
14645 				    ("non-M_DATA IPsec accelerated pkt\n"));
14646 				freemsg(first_mp);
14647 				return (B_TRUE);
14648 			}
14649 			ipha = (ipha_t *)mp->b_rptr;
14650 			if (ipha->ipha_protocol != IPPROTO_AH &&
14651 			    ipha->ipha_protocol != IPPROTO_ESP) {
14652 				IPSECHW_DEBUG(IPSECHW_PKT,
14653 				    ("non-M_DATA IPsec accelerated pkt\n"));
14654 				freemsg(first_mp);
14655 				return (B_TRUE);
14656 			}
14657 			*mpp = mp;
14658 			return (B_FALSE);
14659 		}
14660 		putnext(q, mp);
14661 		return (B_TRUE);
14662 	case M_IOCNAK:
14663 		ip1dbg(("got iocnak "));
14664 		iocp = (struct iocblk *)mp->b_rptr;
14665 		switch (iocp->ioc_cmd) {
14666 		case SIOCSTUNPARAM:
14667 		case OSIOCSTUNPARAM:
14668 			/*
14669 			 * Since this is on the ill stream we unconditionally
14670 			 * bump up the refcount
14671 			 */
14672 			ill_refhold(ill);
14673 			qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14674 			return (B_TRUE);
14675 		case DL_IOC_HDR_INFO:
14676 		case SIOCGTUNPARAM:
14677 		case OSIOCGTUNPARAM:
14678 			ip_rput_other(NULL, q, mp, NULL);
14679 			return (B_TRUE);
14680 		default:
14681 			break;
14682 		}
14683 		/* FALLTHRU */
14684 	default:
14685 		putnext(q, mp);
14686 		return (B_TRUE);
14687 	}
14688 }
14689 
14690 /* Read side put procedure.  Packets coming from the wire arrive here. */
14691 void
14692 ip_rput(queue_t *q, mblk_t *mp)
14693 {
14694 	ill_t	*ill;
14695 	union DL_primitives *dl;
14696 
14697 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14698 
14699 	ill = (ill_t *)q->q_ptr;
14700 
14701 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14702 		/*
14703 		 * If things are opening or closing, only accept high-priority
14704 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
14705 		 * created; on close, things hanging off the ill may have been
14706 		 * freed already.)
14707 		 */
14708 		dl = (union DL_primitives *)mp->b_rptr;
14709 		if (DB_TYPE(mp) != M_PCPROTO ||
14710 		    dl->dl_primitive == DL_UNITDATA_IND) {
14711 			/*
14712 			 * SIOC[GS]TUNPARAM ioctls can come here.
14713 			 */
14714 			inet_freemsg(mp);
14715 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14716 			    "ip_rput_end: q %p (%S)", q, "uninit");
14717 			return;
14718 		}
14719 	}
14720 
14721 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14722 	    "ip_rput_end: q %p (%S)", q, "end");
14723 
14724 	ip_input(ill, NULL, mp, NULL);
14725 }
14726 
14727 static mblk_t *
14728 ip_fix_dbref(ill_t *ill, mblk_t *mp)
14729 {
14730 	mblk_t *mp1;
14731 	boolean_t adjusted = B_FALSE;
14732 	ip_stack_t *ipst = ill->ill_ipst;
14733 
14734 	IP_STAT(ipst, ip_db_ref);
14735 	/*
14736 	 * The IP_RECVSLLA option depends on having the
14737 	 * link layer header. First check that:
14738 	 * a> the underlying device is of type ether,
14739 	 * since this option is currently supported only
14740 	 * over ethernet.
14741 	 * b> there is enough room to copy over the link
14742 	 * layer header.
14743 	 *
14744 	 * Once the checks are done, adjust rptr so that
14745 	 * the link layer header will be copied via
14746 	 * copymsg. Note that, IFT_ETHER may be returned
14747 	 * by some non-ethernet drivers but in this case
14748 	 * the second check will fail.
14749 	 */
14750 	if (ill->ill_type == IFT_ETHER &&
14751 	    (mp->b_rptr - mp->b_datap->db_base) >=
14752 	    sizeof (struct ether_header)) {
14753 		mp->b_rptr -= sizeof (struct ether_header);
14754 		adjusted = B_TRUE;
14755 	}
14756 	mp1 = copymsg(mp);
14757 
14758 	if (mp1 == NULL) {
14759 		mp->b_next = NULL;
14760 		/* clear b_prev - used by ip_mroute_decap */
14761 		mp->b_prev = NULL;
14762 		freemsg(mp);
14763 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14764 		return (NULL);
14765 	}
14766 
14767 	if (adjusted) {
14768 		/*
14769 		 * Copy is done. Restore the pointer in
14770 		 * the _new_ mblk
14771 		 */
14772 		mp1->b_rptr += sizeof (struct ether_header);
14773 	}
14774 
14775 	/* Copy b_prev - used by ip_mroute_decap */
14776 	mp1->b_prev = mp->b_prev;
14777 	mp->b_prev = NULL;
14778 
14779 	/* preserve the hardware checksum flags and data, if present */
14780 	if (DB_CKSUMFLAGS(mp) != 0) {
14781 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
14782 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
14783 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
14784 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
14785 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
14786 	}
14787 
14788 	freemsg(mp);
14789 	return (mp1);
14790 }
14791 
14792 /*
14793  * Direct read side procedure capable of dealing with chains. GLDv3 based
14794  * drivers call this function directly with mblk chains while STREAMS
14795  * read side procedure ip_rput() calls this for single packet with ip_ring
14796  * set to NULL to process one packet at a time.
14797  *
14798  * The ill will always be valid if this function is called directly from
14799  * the driver.
14800  *
14801  * If ip_input() is called from GLDv3:
14802  *
14803  *   - This must be a non-VLAN IP stream.
14804  *   - 'mp' is either an untagged or a special priority-tagged packet.
14805  *   - Any VLAN tag that was in the MAC header has been stripped.
14806  *
14807  * If the IP header in packet is not 32-bit aligned, every message in the
14808  * chain will be aligned before further operations. This is required on SPARC
14809  * platform.
14810  */
14811 /* ARGSUSED */
14812 void
14813 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14814     struct mac_header_info_s *mhip)
14815 {
14816 	ipaddr_t		dst = NULL;
14817 	ipaddr_t		prev_dst;
14818 	ire_t			*ire = NULL;
14819 	ipha_t			*ipha;
14820 	uint_t			pkt_len;
14821 	ssize_t			len;
14822 	uint_t			opt_len;
14823 	int			ll_multicast;
14824 	int			cgtp_flt_pkt;
14825 	queue_t			*q = ill->ill_rq;
14826 	squeue_t		*curr_sqp = NULL;
14827 	mblk_t 			*head = NULL;
14828 	mblk_t			*tail = NULL;
14829 	mblk_t			*first_mp;
14830 	mblk_t 			*mp;
14831 	mblk_t			*dmp;
14832 	int			cnt = 0;
14833 	ip_stack_t		*ipst = ill->ill_ipst;
14834 
14835 	ASSERT(mp_chain != NULL);
14836 	ASSERT(ill != NULL);
14837 
14838 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14839 
14840 #define	rptr	((uchar_t *)ipha)
14841 
14842 	while (mp_chain != NULL) {
14843 		first_mp = mp = mp_chain;
14844 		mp_chain = mp_chain->b_next;
14845 		mp->b_next = NULL;
14846 		ll_multicast = 0;
14847 
14848 		/*
14849 		 * We do ire caching from one iteration to
14850 		 * another. In the event the packet chain contains
14851 		 * all packets from the same dst, this caching saves
14852 		 * an ire_cache_lookup for each of the succeeding
14853 		 * packets in a packet chain.
14854 		 */
14855 		prev_dst = dst;
14856 
14857 		/*
14858 		 * if db_ref > 1 then copymsg and free original. Packet
14859 		 * may be changed and we do not want the other entity
14860 		 * who has a reference to this message to trip over the
14861 		 * changes. This is a blind change because trying to
14862 		 * catch all places that might change the packet is too
14863 		 * difficult.
14864 		 *
14865 		 * This corresponds to the fast path case, where we have
14866 		 * a chain of M_DATA mblks.  We check the db_ref count
14867 		 * of only the 1st data block in the mblk chain. There
14868 		 * doesn't seem to be a reason why a device driver would
14869 		 * send up data with varying db_ref counts in the mblk
14870 		 * chain. In any case the Fast path is a private
14871 		 * interface, and our drivers don't do such a thing.
14872 		 * Given the above assumption, there is no need to walk
14873 		 * down the entire mblk chain (which could have a
14874 		 * potential performance problem)
14875 		 */
14876 
14877 		if (DB_REF(mp) > 1) {
14878 			if ((mp = ip_fix_dbref(ill, mp)) == NULL)
14879 				continue;
14880 		}
14881 
14882 		/*
14883 		 * Check and align the IP header.
14884 		 */
14885 		first_mp = mp;
14886 		if (DB_TYPE(mp) == M_DATA) {
14887 			dmp = mp;
14888 		} else if (DB_TYPE(mp) == M_PROTO &&
14889 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14890 			dmp = mp->b_cont;
14891 		} else {
14892 			dmp = NULL;
14893 		}
14894 		if (dmp != NULL) {
14895 			/*
14896 			 * IP header ptr not aligned?
14897 			 * OR IP header not complete in first mblk
14898 			 */
14899 			if (!OK_32PTR(dmp->b_rptr) ||
14900 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
14901 				if (!ip_check_and_align_header(q, dmp, ipst))
14902 					continue;
14903 			}
14904 		}
14905 
14906 		/*
14907 		 * ip_input fast path
14908 		 */
14909 
14910 		/* mblk type is not M_DATA */
14911 		if (DB_TYPE(mp) != M_DATA) {
14912 			if (ip_rput_process_notdata(q, &first_mp, ill,
14913 			    &ll_multicast, &mp))
14914 				continue;
14915 		}
14916 
14917 		/* Make sure its an M_DATA and that its aligned */
14918 		ASSERT(DB_TYPE(mp) == M_DATA);
14919 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
14920 
14921 		ipha = (ipha_t *)mp->b_rptr;
14922 		len = mp->b_wptr - rptr;
14923 		pkt_len = ntohs(ipha->ipha_length);
14924 
14925 		/*
14926 		 * We must count all incoming packets, even if they end
14927 		 * up being dropped later on.
14928 		 */
14929 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
14930 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
14931 
14932 		/* multiple mblk or too short */
14933 		len -= pkt_len;
14934 		if (len != 0) {
14935 			/*
14936 			 * Make sure we have data length consistent
14937 			 * with the IP header.
14938 			 */
14939 			if (mp->b_cont == NULL) {
14940 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14941 					BUMP_MIB(ill->ill_ip_mib,
14942 					    ipIfStatsInHdrErrors);
14943 					ip2dbg(("ip_input: drop pkt\n"));
14944 					freemsg(mp);
14945 					continue;
14946 				}
14947 				mp->b_wptr = rptr + pkt_len;
14948 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
14949 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14950 					BUMP_MIB(ill->ill_ip_mib,
14951 					    ipIfStatsInHdrErrors);
14952 					ip2dbg(("ip_input: drop pkt\n"));
14953 					freemsg(mp);
14954 					continue;
14955 				}
14956 				(void) adjmsg(mp, -len);
14957 				IP_STAT(ipst, ip_multimblk3);
14958 			}
14959 		}
14960 
14961 		/* Obtain the dst of the current packet */
14962 		dst = ipha->ipha_dst;
14963 
14964 		if (IP_LOOPBACK_ADDR(dst) ||
14965 		    IP_LOOPBACK_ADDR(ipha->ipha_src)) {
14966 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
14967 			cmn_err(CE_CONT, "dst %X src %X\n",
14968 			    dst, ipha->ipha_src);
14969 			freemsg(mp);
14970 			continue;
14971 		}
14972 
14973 		/*
14974 		 * The event for packets being received from a 'physical'
14975 		 * interface is placed after validation of the source and/or
14976 		 * destination address as being local so that packets can be
14977 		 * redirected to loopback addresses using ipnat.
14978 		 */
14979 		DTRACE_PROBE4(ip4__physical__in__start,
14980 		    ill_t *, ill, ill_t *, NULL,
14981 		    ipha_t *, ipha, mblk_t *, first_mp);
14982 
14983 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
14984 		    ipst->ips_ipv4firewall_physical_in,
14985 		    ill, NULL, ipha, first_mp, mp, ipst);
14986 
14987 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
14988 
14989 		if (first_mp == NULL) {
14990 			continue;
14991 		}
14992 		dst = ipha->ipha_dst;
14993 
14994 		/*
14995 		 * Attach any necessary label information to
14996 		 * this packet
14997 		 */
14998 		if (is_system_labeled() &&
14999 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
15000 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
15001 			freemsg(mp);
15002 			continue;
15003 		}
15004 
15005 		/*
15006 		 * Reuse the cached ire only if the ipha_dst of the previous
15007 		 * packet is the same as the current packet AND it is not
15008 		 * INADDR_ANY.
15009 		 */
15010 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15011 		    (ire != NULL)) {
15012 			ire_refrele(ire);
15013 			ire = NULL;
15014 		}
15015 		opt_len = ipha->ipha_version_and_hdr_length -
15016 		    IP_SIMPLE_HDR_VERSION;
15017 
15018 		/*
15019 		 * Check to see if we can take the fastpath.
15020 		 * That is possible if the following conditions are met
15021 		 *	o Tsol disabled
15022 		 *	o CGTP disabled
15023 		 *	o ipp_action_count is 0
15024 		 *	o no options in the packet
15025 		 *	o not a RSVP packet
15026 		 * 	o not a multicast packet
15027 		 *	o ill not in IP_DHCPINIT_IF mode
15028 		 */
15029 		if (!is_system_labeled() &&
15030 		    !ipst->ips_ip_cgtp_filter && ipp_action_count == 0 &&
15031 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
15032 		    !ll_multicast && !CLASSD(dst) && ill->ill_dhcpinit == 0) {
15033 			if (ire == NULL)
15034 				ire = ire_cache_lookup(dst, ALL_ZONES, NULL,
15035 				    ipst);
15036 
15037 			/* incoming packet is for forwarding */
15038 			if (ire == NULL || (ire->ire_type & IRE_CACHE)) {
15039 				ire = ip_fast_forward(ire, dst, ill, mp);
15040 				continue;
15041 			}
15042 			/* incoming packet is for local consumption */
15043 			if (ire->ire_type & IRE_LOCAL)
15044 				goto local;
15045 		}
15046 
15047 		/*
15048 		 * Disable ire caching for anything more complex
15049 		 * than the simple fast path case we checked for above.
15050 		 */
15051 		if (ire != NULL) {
15052 			ire_refrele(ire);
15053 			ire = NULL;
15054 		}
15055 
15056 		/*
15057 		 * Brutal hack for DHCPv4 unicast: RFC2131 allows a DHCP
15058 		 * server to unicast DHCP packets to a DHCP client using the
15059 		 * IP address it is offering to the client.  This can be
15060 		 * disabled through the "broadcast bit", but not all DHCP
15061 		 * servers honor that bit.  Therefore, to interoperate with as
15062 		 * many DHCP servers as possible, the DHCP client allows the
15063 		 * server to unicast, but we treat those packets as broadcast
15064 		 * here.  Note that we don't rewrite the packet itself since
15065 		 * (a) that would mess up the checksums and (b) the DHCP
15066 		 * client conn is bound to INADDR_ANY so ip_fanout_udp() will
15067 		 * hand it the packet regardless.
15068 		 */
15069 		if (ill->ill_dhcpinit != 0 &&
15070 		    IS_SIMPLE_IPH(ipha) && ipha->ipha_protocol == IPPROTO_UDP &&
15071 		    pullupmsg(mp, sizeof (ipha_t) + sizeof (udpha_t)) == 1) {
15072 			udpha_t *udpha;
15073 
15074 			/*
15075 			 * Reload ipha since pullupmsg() can change b_rptr.
15076 			 */
15077 			ipha = (ipha_t *)mp->b_rptr;
15078 			udpha = (udpha_t *)&ipha[1];
15079 
15080 			if (ntohs(udpha->uha_dst_port) == IPPORT_BOOTPC) {
15081 				DTRACE_PROBE2(ip4__dhcpinit__pkt, ill_t *, ill,
15082 				    mblk_t *, mp);
15083 				dst = INADDR_BROADCAST;
15084 			}
15085 		}
15086 
15087 		/* Full-blown slow path */
15088 		if (opt_len != 0) {
15089 			if (len != 0)
15090 				IP_STAT(ipst, ip_multimblk4);
15091 			else
15092 				IP_STAT(ipst, ip_ipoptions);
15093 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15094 			    &dst, ipst))
15095 				continue;
15096 		}
15097 
15098 		/*
15099 		 * Invoke the CGTP (multirouting) filtering module to process
15100 		 * the incoming packet. Packets identified as duplicates
15101 		 * must be discarded. Filtering is active only if the
15102 		 * the ip_cgtp_filter ndd variable is non-zero.
15103 		 */
15104 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15105 		if (ipst->ips_ip_cgtp_filter &&
15106 		    ipst->ips_ip_cgtp_filter_ops != NULL) {
15107 			netstackid_t stackid;
15108 
15109 			stackid = ipst->ips_netstack->netstack_stackid;
15110 			cgtp_flt_pkt =
15111 			    ipst->ips_ip_cgtp_filter_ops->cfo_filter(stackid,
15112 			    ill->ill_phyint->phyint_ifindex, mp);
15113 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15114 				freemsg(first_mp);
15115 				continue;
15116 			}
15117 		}
15118 
15119 		/*
15120 		 * If rsvpd is running, let RSVP daemon handle its processing
15121 		 * and forwarding of RSVP multicast/unicast packets.
15122 		 * If rsvpd is not running but mrouted is running, RSVP
15123 		 * multicast packets are forwarded as multicast traffic
15124 		 * and RSVP unicast packets are forwarded by unicast router.
15125 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15126 		 * packets are not forwarded, but the unicast packets are
15127 		 * forwarded like unicast traffic.
15128 		 */
15129 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15130 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15131 		    NULL) {
15132 			/* RSVP packet and rsvpd running. Treat as ours */
15133 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15134 			/*
15135 			 * This assumes that we deliver to all streams for
15136 			 * multicast and broadcast packets.
15137 			 * We have to force ll_multicast to 1 to handle the
15138 			 * M_DATA messages passed in from ip_mroute_decap.
15139 			 */
15140 			dst = INADDR_BROADCAST;
15141 			ll_multicast = 1;
15142 		} else if (CLASSD(dst)) {
15143 			/* packet is multicast */
15144 			mp->b_next = NULL;
15145 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15146 			    &ll_multicast, &dst))
15147 				continue;
15148 		}
15149 
15150 		if (ire == NULL) {
15151 			ire = ire_cache_lookup(dst, ALL_ZONES,
15152 			    MBLK_GETLABEL(mp), ipst);
15153 		}
15154 
15155 		if (ire == NULL) {
15156 			/*
15157 			 * No IRE for this destination, so it can't be for us.
15158 			 * Unless we are forwarding, drop the packet.
15159 			 * We have to let source routed packets through
15160 			 * since we don't yet know if they are 'ping -l'
15161 			 * packets i.e. if they will go out over the
15162 			 * same interface as they came in on.
15163 			 */
15164 			ire = ip_rput_noire(q, mp, ll_multicast, dst);
15165 			if (ire == NULL)
15166 				continue;
15167 		}
15168 
15169 		/*
15170 		 * Broadcast IRE may indicate either broadcast or
15171 		 * multicast packet
15172 		 */
15173 		if (ire->ire_type == IRE_BROADCAST) {
15174 			/*
15175 			 * Skip broadcast checks if packet is UDP multicast;
15176 			 * we'd rather not enter ip_rput_process_broadcast()
15177 			 * unless the packet is broadcast for real, since
15178 			 * that routine is a no-op for multicast.
15179 			 */
15180 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15181 			    !CLASSD(ipha->ipha_dst)) {
15182 				ire = ip_rput_process_broadcast(&q, mp,
15183 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15184 				    ll_multicast);
15185 				if (ire == NULL)
15186 					continue;
15187 			}
15188 		} else if (ire->ire_stq != NULL) {
15189 			/* fowarding? */
15190 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15191 			    ll_multicast);
15192 			/* ip_rput_process_forward consumed the packet */
15193 			continue;
15194 		}
15195 
15196 local:
15197 		/*
15198 		 * If the queue in the ire is different to the ingress queue
15199 		 * then we need to check to see if we can accept the packet.
15200 		 * Note that for multicast packets and broadcast packets sent
15201 		 * to a broadcast address which is shared between multiple
15202 		 * interfaces we should not do this since we just got a random
15203 		 * broadcast ire.
15204 		 */
15205 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15206 			if ((ire = ip_check_multihome(&ipha->ipha_dst, ire,
15207 			    ill)) == NULL) {
15208 				/* Drop packet */
15209 				BUMP_MIB(ill->ill_ip_mib,
15210 				    ipIfStatsForwProhibits);
15211 				freemsg(mp);
15212 				continue;
15213 			}
15214 			if (ire->ire_rfq != NULL)
15215 				q = ire->ire_rfq;
15216 		}
15217 
15218 		switch (ipha->ipha_protocol) {
15219 		case IPPROTO_TCP:
15220 			ASSERT(first_mp == mp);
15221 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15222 			    mp, 0, q, ip_ring)) != NULL) {
15223 				if (curr_sqp == NULL) {
15224 					curr_sqp = GET_SQUEUE(mp);
15225 					ASSERT(cnt == 0);
15226 					cnt++;
15227 					head = tail = mp;
15228 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15229 					ASSERT(tail != NULL);
15230 					cnt++;
15231 					tail->b_next = mp;
15232 					tail = mp;
15233 				} else {
15234 					/*
15235 					 * A different squeue. Send the
15236 					 * chain for the previous squeue on
15237 					 * its way. This shouldn't happen
15238 					 * often unless interrupt binding
15239 					 * changes.
15240 					 */
15241 					IP_STAT(ipst, ip_input_multi_squeue);
15242 					squeue_enter_chain(curr_sqp, head,
15243 					    tail, cnt, SQTAG_IP_INPUT);
15244 					curr_sqp = GET_SQUEUE(mp);
15245 					head = mp;
15246 					tail = mp;
15247 					cnt = 1;
15248 				}
15249 			}
15250 			continue;
15251 		case IPPROTO_UDP:
15252 			ASSERT(first_mp == mp);
15253 			ip_udp_input(q, mp, ipha, ire, ill);
15254 			continue;
15255 		case IPPROTO_SCTP:
15256 			ASSERT(first_mp == mp);
15257 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15258 			    q, dst);
15259 			/* ire has been released by ip_sctp_input */
15260 			ire = NULL;
15261 			continue;
15262 		default:
15263 			ip_proto_input(q, first_mp, ipha, ire, ill, B_FALSE);
15264 			continue;
15265 		}
15266 	}
15267 
15268 	if (ire != NULL)
15269 		ire_refrele(ire);
15270 
15271 	if (head != NULL)
15272 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
15273 
15274 	/*
15275 	 * This code is there just to make netperf/ttcp look good.
15276 	 *
15277 	 * Its possible that after being in polling mode (and having cleared
15278 	 * the backlog), squeues have turned the interrupt frequency higher
15279 	 * to improve latency at the expense of more CPU utilization (less
15280 	 * packets per interrupts or more number of interrupts). Workloads
15281 	 * like ttcp/netperf do manage to tickle polling once in a while
15282 	 * but for the remaining time, stay in higher interrupt mode since
15283 	 * their packet arrival rate is pretty uniform and this shows up
15284 	 * as higher CPU utilization. Since people care about CPU utilization
15285 	 * while running netperf/ttcp, turn the interrupt frequency back to
15286 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
15287 	 */
15288 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
15289 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
15290 			ip_ring->rr_poll_state &= ~ILL_POLLING;
15291 			ip_ring->rr_blank(ip_ring->rr_handle,
15292 			    ip_ring->rr_normal_blank_time,
15293 			    ip_ring->rr_normal_pkt_cnt);
15294 		}
15295 		}
15296 
15297 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15298 	    "ip_input_end: q %p (%S)", q, "end");
15299 #undef  rptr
15300 }
15301 
15302 static void
15303 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15304     t_uscalar_t err)
15305 {
15306 	if (dl_err == DL_SYSERR) {
15307 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15308 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15309 		    ill->ill_name, dlpi_prim_str(prim), err);
15310 		return;
15311 	}
15312 
15313 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15314 	    "%s: %s failed: %s\n", ill->ill_name, dlpi_prim_str(prim),
15315 	    dlpi_err_str(dl_err));
15316 }
15317 
15318 /*
15319  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15320  * than DL_UNITDATA_IND messages. If we need to process this message
15321  * exclusively, we call qwriter_ip, in which case we also need to call
15322  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15323  */
15324 void
15325 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15326 {
15327 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15328 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15329 	ill_t		*ill = (ill_t *)q->q_ptr;
15330 	boolean_t	pending;
15331 
15332 	ip1dbg(("ip_rput_dlpi"));
15333 	if (dloa->dl_primitive == DL_ERROR_ACK) {
15334 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
15335 		    "%s (0x%x), unix %u\n", ill->ill_name,
15336 		    dlpi_prim_str(dlea->dl_error_primitive),
15337 		    dlea->dl_error_primitive,
15338 		    dlpi_err_str(dlea->dl_errno),
15339 		    dlea->dl_errno,
15340 		    dlea->dl_unix_errno));
15341 	}
15342 
15343 	/*
15344 	 * If we received an ACK but didn't send a request for it, then it
15345 	 * can't be part of any pending operation; discard up-front.
15346 	 */
15347 	switch (dloa->dl_primitive) {
15348 	case DL_NOTIFY_IND:
15349 		pending = B_TRUE;
15350 		break;
15351 	case DL_ERROR_ACK:
15352 		pending = ill_dlpi_pending(ill, dlea->dl_error_primitive);
15353 		break;
15354 	case DL_OK_ACK:
15355 		pending = ill_dlpi_pending(ill, dloa->dl_correct_primitive);
15356 		break;
15357 	case DL_INFO_ACK:
15358 		pending = ill_dlpi_pending(ill, DL_INFO_REQ);
15359 		break;
15360 	case DL_BIND_ACK:
15361 		pending = ill_dlpi_pending(ill, DL_BIND_REQ);
15362 		break;
15363 	case DL_PHYS_ADDR_ACK:
15364 		pending = ill_dlpi_pending(ill, DL_PHYS_ADDR_REQ);
15365 		break;
15366 	case DL_NOTIFY_ACK:
15367 		pending = ill_dlpi_pending(ill, DL_NOTIFY_REQ);
15368 		break;
15369 	case DL_CONTROL_ACK:
15370 		pending = ill_dlpi_pending(ill, DL_CONTROL_REQ);
15371 		break;
15372 	case DL_CAPABILITY_ACK:
15373 		pending = ill_dlpi_pending(ill, DL_CAPABILITY_REQ);
15374 		break;
15375 	default:
15376 		/* Not a DLPI message we support or were expecting */
15377 		freemsg(mp);
15378 		return;
15379 	}
15380 
15381 	if (!pending) {
15382 		freemsg(mp);
15383 		return;
15384 	}
15385 
15386 	switch (dloa->dl_primitive) {
15387 	case DL_ERROR_ACK:
15388 		if (dlea->dl_error_primitive == DL_UNBIND_REQ) {
15389 			mutex_enter(&ill->ill_lock);
15390 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15391 			cv_signal(&ill->ill_cv);
15392 			mutex_exit(&ill->ill_lock);
15393 		}
15394 		break;
15395 
15396 	case DL_OK_ACK:
15397 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
15398 		    dlpi_prim_str((int)dloa->dl_correct_primitive)));
15399 		switch (dloa->dl_correct_primitive) {
15400 		case DL_UNBIND_REQ:
15401 			mutex_enter(&ill->ill_lock);
15402 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15403 			cv_signal(&ill->ill_cv);
15404 			mutex_exit(&ill->ill_lock);
15405 			break;
15406 
15407 		case DL_ENABMULTI_REQ:
15408 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15409 				ill->ill_dlpi_multicast_state = IDS_OK;
15410 			break;
15411 		}
15412 		break;
15413 	default:
15414 		break;
15415 	}
15416 
15417 	/*
15418 	 * We know the message is one we're waiting for (or DL_NOTIFY_IND),
15419 	 * and we need to become writer to continue to process it. If it's not
15420 	 * a DL_NOTIFY_IND, we assume we're in the middle of an exclusive
15421 	 * operation and pass CUR_OP.  If this isn't true, we'll end up doing
15422 	 * some work as part of the current exclusive operation that actually
15423 	 * is not part of it -- which is wrong, but better than the
15424 	 * alternative of deadlock (if NEW_OP is always used).  Someday, we
15425 	 * should track which DLPI requests have ACKs that we wait on
15426 	 * synchronously so we can know whether to use CUR_OP or NEW_OP.
15427 	 *
15428 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
15429 	 * Since this is on the ill stream we unconditionally bump up the
15430 	 * refcount without doing ILL_CAN_LOOKUP().
15431 	 */
15432 	ill_refhold(ill);
15433 	if (dloa->dl_primitive == DL_NOTIFY_IND)
15434 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
15435 	else
15436 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
15437 }
15438 
15439 /*
15440  * Handling of DLPI messages that require exclusive access to the ipsq.
15441  *
15442  * Need to do ill_pending_mp_release on ioctl completion, which could
15443  * happen here. (along with mi_copy_done)
15444  */
15445 /* ARGSUSED */
15446 static void
15447 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15448 {
15449 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15450 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15451 	int		err = 0;
15452 	ill_t		*ill;
15453 	ipif_t		*ipif = NULL;
15454 	mblk_t		*mp1 = NULL;
15455 	conn_t		*connp = NULL;
15456 	t_uscalar_t	paddrreq;
15457 	mblk_t		*mp_hw;
15458 	boolean_t	success;
15459 	boolean_t	ioctl_aborted = B_FALSE;
15460 	boolean_t	log = B_TRUE;
15461 	hook_nic_event_t	*info;
15462 	ip_stack_t		*ipst;
15463 
15464 	ip1dbg(("ip_rput_dlpi_writer .."));
15465 	ill = (ill_t *)q->q_ptr;
15466 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15467 
15468 	ASSERT(IAM_WRITER_ILL(ill));
15469 
15470 	ipst = ill->ill_ipst;
15471 
15472 	/*
15473 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
15474 	 * both are null or non-null. However we can assert that only
15475 	 * after grabbing the ipsq_lock. So we don't make any assertion
15476 	 * here and in other places in the code.
15477 	 */
15478 	ipif = ipsq->ipsq_pending_ipif;
15479 	/*
15480 	 * The current ioctl could have been aborted by the user and a new
15481 	 * ioctl to bring up another ill could have started. We could still
15482 	 * get a response from the driver later.
15483 	 */
15484 	if (ipif != NULL && ipif->ipif_ill != ill)
15485 		ioctl_aborted = B_TRUE;
15486 
15487 	switch (dloa->dl_primitive) {
15488 	case DL_ERROR_ACK:
15489 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
15490 		    dlpi_prim_str(dlea->dl_error_primitive)));
15491 
15492 		switch (dlea->dl_error_primitive) {
15493 		case DL_PROMISCON_REQ:
15494 		case DL_PROMISCOFF_REQ:
15495 		case DL_DISABMULTI_REQ:
15496 		case DL_UNBIND_REQ:
15497 		case DL_ATTACH_REQ:
15498 		case DL_INFO_REQ:
15499 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15500 			break;
15501 		case DL_NOTIFY_REQ:
15502 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15503 			log = B_FALSE;
15504 			break;
15505 		case DL_PHYS_ADDR_REQ:
15506 			/*
15507 			 * For IPv6 only, there are two additional
15508 			 * phys_addr_req's sent to the driver to get the
15509 			 * IPv6 token and lla. This allows IP to acquire
15510 			 * the hardware address format for a given interface
15511 			 * without having built in knowledge of the hardware
15512 			 * address. ill_phys_addr_pend keeps track of the last
15513 			 * DL_PAR sent so we know which response we are
15514 			 * dealing with. ill_dlpi_done will update
15515 			 * ill_phys_addr_pend when it sends the next req.
15516 			 * We don't complete the IOCTL until all three DL_PARs
15517 			 * have been attempted, so set *_len to 0 and break.
15518 			 */
15519 			paddrreq = ill->ill_phys_addr_pend;
15520 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15521 			if (paddrreq == DL_IPV6_TOKEN) {
15522 				ill->ill_token_length = 0;
15523 				log = B_FALSE;
15524 				break;
15525 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15526 				ill->ill_nd_lla_len = 0;
15527 				log = B_FALSE;
15528 				break;
15529 			}
15530 			/*
15531 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15532 			 * We presumably have an IOCTL hanging out waiting
15533 			 * for completion. Find it and complete the IOCTL
15534 			 * with the error noted.
15535 			 * However, ill_dl_phys was called on an ill queue
15536 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15537 			 * set. But the ioctl is known to be pending on ill_wq.
15538 			 */
15539 			if (!ill->ill_ifname_pending)
15540 				break;
15541 			ill->ill_ifname_pending = 0;
15542 			if (!ioctl_aborted)
15543 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15544 			if (mp1 != NULL) {
15545 				/*
15546 				 * This operation (SIOCSLIFNAME) must have
15547 				 * happened on the ill. Assert there is no conn
15548 				 */
15549 				ASSERT(connp == NULL);
15550 				q = ill->ill_wq;
15551 			}
15552 			break;
15553 		case DL_BIND_REQ:
15554 			ill_dlpi_done(ill, DL_BIND_REQ);
15555 			if (ill->ill_ifname_pending)
15556 				break;
15557 			/*
15558 			 * Something went wrong with the bind.  We presumably
15559 			 * have an IOCTL hanging out waiting for completion.
15560 			 * Find it, take down the interface that was coming
15561 			 * up, and complete the IOCTL with the error noted.
15562 			 */
15563 			if (!ioctl_aborted)
15564 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15565 			if (mp1 != NULL) {
15566 				/*
15567 				 * This operation (SIOCSLIFFLAGS) must have
15568 				 * happened from a conn.
15569 				 */
15570 				ASSERT(connp != NULL);
15571 				q = CONNP_TO_WQ(connp);
15572 				if (ill->ill_move_in_progress) {
15573 					ILL_CLEAR_MOVE(ill);
15574 				}
15575 				(void) ipif_down(ipif, NULL, NULL);
15576 				/* error is set below the switch */
15577 			}
15578 			break;
15579 		case DL_ENABMULTI_REQ:
15580 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
15581 
15582 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15583 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15584 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15585 				ipif_t *ipif;
15586 
15587 				printf("ip: joining multicasts failed (%d)"
15588 				    " on %s - will use link layer "
15589 				    "broadcasts for multicast\n",
15590 				    dlea->dl_errno, ill->ill_name);
15591 
15592 				/*
15593 				 * Set up the multicast mapping alone.
15594 				 * writer, so ok to access ill->ill_ipif
15595 				 * without any lock.
15596 				 */
15597 				ipif = ill->ill_ipif;
15598 				mutex_enter(&ill->ill_phyint->phyint_lock);
15599 				ill->ill_phyint->phyint_flags |=
15600 				    PHYI_MULTI_BCAST;
15601 				mutex_exit(&ill->ill_phyint->phyint_lock);
15602 
15603 				if (!ill->ill_isv6) {
15604 					(void) ipif_arp_setup_multicast(ipif,
15605 					    NULL);
15606 				} else {
15607 					(void) ipif_ndp_setup_multicast(ipif,
15608 					    NULL);
15609 				}
15610 			}
15611 			freemsg(mp);	/* Don't want to pass this up */
15612 			return;
15613 
15614 		case DL_CAPABILITY_REQ:
15615 		case DL_CONTROL_REQ:
15616 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15617 			ill->ill_dlpi_capab_state = IDS_FAILED;
15618 			freemsg(mp);
15619 			return;
15620 		}
15621 		/*
15622 		 * Note the error for IOCTL completion (mp1 is set when
15623 		 * ready to complete ioctl). If ill_ifname_pending_err is
15624 		 * set, an error occured during plumbing (ill_ifname_pending),
15625 		 * so we want to report that error.
15626 		 *
15627 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15628 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15629 		 * expected to get errack'd if the driver doesn't support
15630 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15631 		 * if these error conditions are encountered.
15632 		 */
15633 		if (mp1 != NULL) {
15634 			if (ill->ill_ifname_pending_err != 0)  {
15635 				err = ill->ill_ifname_pending_err;
15636 				ill->ill_ifname_pending_err = 0;
15637 			} else {
15638 				err = dlea->dl_unix_errno ?
15639 				    dlea->dl_unix_errno : ENXIO;
15640 			}
15641 		/*
15642 		 * If we're plumbing an interface and an error hasn't already
15643 		 * been saved, set ill_ifname_pending_err to the error passed
15644 		 * up. Ignore the error if log is B_FALSE (see comment above).
15645 		 */
15646 		} else if (log && ill->ill_ifname_pending &&
15647 		    ill->ill_ifname_pending_err == 0) {
15648 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15649 			    dlea->dl_unix_errno : ENXIO;
15650 		}
15651 
15652 		if (log)
15653 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15654 			    dlea->dl_errno, dlea->dl_unix_errno);
15655 		break;
15656 	case DL_CAPABILITY_ACK:
15657 		/* Call a routine to handle this one. */
15658 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
15659 		ill_capability_ack(ill, mp);
15660 
15661 		/*
15662 		 * If the ack is due to renegotiation, we will need to send
15663 		 * a new CAPABILITY_REQ to start the renegotiation.
15664 		 */
15665 		if (ill->ill_capab_reneg) {
15666 			ill->ill_capab_reneg = B_FALSE;
15667 			ill_capability_probe(ill);
15668 		}
15669 		break;
15670 	case DL_CONTROL_ACK:
15671 		/* We treat all of these as "fire and forget" */
15672 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15673 		break;
15674 	case DL_INFO_ACK:
15675 		/* Call a routine to handle this one. */
15676 		ill_dlpi_done(ill, DL_INFO_REQ);
15677 		ip_ll_subnet_defaults(ill, mp);
15678 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15679 		return;
15680 	case DL_BIND_ACK:
15681 		/*
15682 		 * We should have an IOCTL waiting on this unless
15683 		 * sent by ill_dl_phys, in which case just return
15684 		 */
15685 		ill_dlpi_done(ill, DL_BIND_REQ);
15686 		if (ill->ill_ifname_pending)
15687 			break;
15688 
15689 		if (!ioctl_aborted)
15690 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15691 		if (mp1 == NULL)
15692 			break;
15693 		/*
15694 		 * Because mp1 was added by ill_dl_up(), and it always
15695 		 * passes a valid connp, connp must be valid here.
15696 		 */
15697 		ASSERT(connp != NULL);
15698 		q = CONNP_TO_WQ(connp);
15699 
15700 		/*
15701 		 * We are exclusive. So nothing can change even after
15702 		 * we get the pending mp. If need be we can put it back
15703 		 * and restart, as in calling ipif_arp_up()  below.
15704 		 */
15705 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15706 
15707 		mutex_enter(&ill->ill_lock);
15708 
15709 		ill->ill_dl_up = 1;
15710 
15711 		if ((info = ill->ill_nic_event_info) != NULL) {
15712 			ip2dbg(("ip_rput_dlpi_writer: unexpected nic event %d "
15713 			    "attached for %s\n", info->hne_event,
15714 			    ill->ill_name));
15715 			if (info->hne_data != NULL)
15716 				kmem_free(info->hne_data, info->hne_datalen);
15717 			kmem_free(info, sizeof (hook_nic_event_t));
15718 		}
15719 
15720 		info = kmem_alloc(sizeof (hook_nic_event_t), KM_NOSLEEP);
15721 		if (info != NULL) {
15722 			info->hne_nic = ill->ill_phyint->phyint_hook_ifindex;
15723 			info->hne_lif = 0;
15724 			info->hne_event = NE_UP;
15725 			info->hne_data = NULL;
15726 			info->hne_datalen = 0;
15727 			info->hne_family = ill->ill_isv6 ?
15728 			    ipst->ips_ipv6_net_data : ipst->ips_ipv4_net_data;
15729 		} else
15730 			ip2dbg(("ip_rput_dlpi_writer: could not attach UP nic "
15731 			    "event information for %s (ENOMEM)\n",
15732 			    ill->ill_name));
15733 
15734 		ill->ill_nic_event_info = info;
15735 
15736 		mutex_exit(&ill->ill_lock);
15737 
15738 		/*
15739 		 * Now bring up the resolver; when that is complete, we'll
15740 		 * create IREs.  Note that we intentionally mirror what
15741 		 * ipif_up() would have done, because we got here by way of
15742 		 * ill_dl_up(), which stopped ipif_up()'s processing.
15743 		 */
15744 		if (ill->ill_isv6) {
15745 			/*
15746 			 * v6 interfaces.
15747 			 * Unlike ARP which has to do another bind
15748 			 * and attach, once we get here we are
15749 			 * done with NDP. Except in the case of
15750 			 * ILLF_XRESOLV, in which case we send an
15751 			 * AR_INTERFACE_UP to the external resolver.
15752 			 * If all goes well, the ioctl will complete
15753 			 * in ip_rput(). If there's an error, we
15754 			 * complete it here.
15755 			 */
15756 			if ((err = ipif_ndp_up(ipif)) == 0) {
15757 				if (ill->ill_flags & ILLF_XRESOLV) {
15758 					mutex_enter(&connp->conn_lock);
15759 					mutex_enter(&ill->ill_lock);
15760 					success = ipsq_pending_mp_add(
15761 					    connp, ipif, q, mp1, 0);
15762 					mutex_exit(&ill->ill_lock);
15763 					mutex_exit(&connp->conn_lock);
15764 					if (success) {
15765 						err = ipif_resolver_up(ipif,
15766 						    Res_act_initial);
15767 						if (err == EINPROGRESS) {
15768 							freemsg(mp);
15769 							return;
15770 						}
15771 						ASSERT(err != 0);
15772 						mp1 = ipsq_pending_mp_get(ipsq,
15773 						    &connp);
15774 						ASSERT(mp1 != NULL);
15775 					} else {
15776 						/* conn has started closing */
15777 						err = EINTR;
15778 					}
15779 				} else { /* Non XRESOLV interface */
15780 					(void) ipif_resolver_up(ipif,
15781 					    Res_act_initial);
15782 					err = ipif_up_done_v6(ipif);
15783 				}
15784 			}
15785 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
15786 			/*
15787 			 * ARP and other v4 external resolvers.
15788 			 * Leave the pending mblk intact so that
15789 			 * the ioctl completes in ip_rput().
15790 			 */
15791 			mutex_enter(&connp->conn_lock);
15792 			mutex_enter(&ill->ill_lock);
15793 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
15794 			mutex_exit(&ill->ill_lock);
15795 			mutex_exit(&connp->conn_lock);
15796 			if (success) {
15797 				err = ipif_resolver_up(ipif, Res_act_initial);
15798 				if (err == EINPROGRESS) {
15799 					freemsg(mp);
15800 					return;
15801 				}
15802 				ASSERT(err != 0);
15803 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15804 			} else {
15805 				/* The conn has started closing */
15806 				err = EINTR;
15807 			}
15808 		} else {
15809 			/*
15810 			 * This one is complete. Reply to pending ioctl.
15811 			 */
15812 			(void) ipif_resolver_up(ipif, Res_act_initial);
15813 			err = ipif_up_done(ipif);
15814 		}
15815 
15816 		if ((err == 0) && (ill->ill_up_ipifs)) {
15817 			err = ill_up_ipifs(ill, q, mp1);
15818 			if (err == EINPROGRESS) {
15819 				freemsg(mp);
15820 				return;
15821 			}
15822 		}
15823 
15824 		if (ill->ill_up_ipifs) {
15825 			ill_group_cleanup(ill);
15826 		}
15827 
15828 		break;
15829 	case DL_NOTIFY_IND: {
15830 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
15831 		ire_t *ire;
15832 		boolean_t need_ire_walk_v4 = B_FALSE;
15833 		boolean_t need_ire_walk_v6 = B_FALSE;
15834 
15835 		switch (notify->dl_notification) {
15836 		case DL_NOTE_PHYS_ADDR:
15837 			err = ill_set_phys_addr(ill, mp);
15838 			break;
15839 
15840 		case DL_NOTE_FASTPATH_FLUSH:
15841 			ill_fastpath_flush(ill);
15842 			break;
15843 
15844 		case DL_NOTE_SDU_SIZE:
15845 			/*
15846 			 * Change the MTU size of the interface, of all
15847 			 * attached ipif's, and of all relevant ire's.  The
15848 			 * new value's a uint32_t at notify->dl_data.
15849 			 * Mtu change Vs. new ire creation - protocol below.
15850 			 *
15851 			 * a Mark the ipif as IPIF_CHANGING.
15852 			 * b Set the new mtu in the ipif.
15853 			 * c Change the ire_max_frag on all affected ires
15854 			 * d Unmark the IPIF_CHANGING
15855 			 *
15856 			 * To see how the protocol works, assume an interface
15857 			 * route is also being added simultaneously by
15858 			 * ip_rt_add and let 'ipif' be the ipif referenced by
15859 			 * the ire. If the ire is created before step a,
15860 			 * it will be cleaned up by step c. If the ire is
15861 			 * created after step d, it will see the new value of
15862 			 * ipif_mtu. Any attempt to create the ire between
15863 			 * steps a to d will fail because of the IPIF_CHANGING
15864 			 * flag. Note that ire_create() is passed a pointer to
15865 			 * the ipif_mtu, and not the value. During ire_add
15866 			 * under the bucket lock, the ire_max_frag of the
15867 			 * new ire being created is set from the ipif/ire from
15868 			 * which it is being derived.
15869 			 */
15870 			mutex_enter(&ill->ill_lock);
15871 			ill->ill_max_frag = (uint_t)notify->dl_data;
15872 
15873 			/*
15874 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
15875 			 * leave it alone
15876 			 */
15877 			if (ill->ill_mtu_userspecified) {
15878 				mutex_exit(&ill->ill_lock);
15879 				break;
15880 			}
15881 			ill->ill_max_mtu = ill->ill_max_frag;
15882 			if (ill->ill_isv6) {
15883 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
15884 					ill->ill_max_mtu = IPV6_MIN_MTU;
15885 			} else {
15886 				if (ill->ill_max_mtu < IP_MIN_MTU)
15887 					ill->ill_max_mtu = IP_MIN_MTU;
15888 			}
15889 			for (ipif = ill->ill_ipif; ipif != NULL;
15890 			    ipif = ipif->ipif_next) {
15891 				/*
15892 				 * Don't override the mtu if the user
15893 				 * has explicitly set it.
15894 				 */
15895 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
15896 					continue;
15897 				ipif->ipif_mtu = (uint_t)notify->dl_data;
15898 				if (ipif->ipif_isv6)
15899 					ire = ipif_to_ire_v6(ipif);
15900 				else
15901 					ire = ipif_to_ire(ipif);
15902 				if (ire != NULL) {
15903 					ire->ire_max_frag = ipif->ipif_mtu;
15904 					ire_refrele(ire);
15905 				}
15906 				if (ipif->ipif_flags & IPIF_UP) {
15907 					if (ill->ill_isv6)
15908 						need_ire_walk_v6 = B_TRUE;
15909 					else
15910 						need_ire_walk_v4 = B_TRUE;
15911 				}
15912 			}
15913 			mutex_exit(&ill->ill_lock);
15914 			if (need_ire_walk_v4)
15915 				ire_walk_v4(ill_mtu_change, (char *)ill,
15916 				    ALL_ZONES, ipst);
15917 			if (need_ire_walk_v6)
15918 				ire_walk_v6(ill_mtu_change, (char *)ill,
15919 				    ALL_ZONES, ipst);
15920 			break;
15921 		case DL_NOTE_LINK_UP:
15922 		case DL_NOTE_LINK_DOWN: {
15923 			/*
15924 			 * We are writer. ill / phyint / ipsq assocs stable.
15925 			 * The RUNNING flag reflects the state of the link.
15926 			 */
15927 			phyint_t *phyint = ill->ill_phyint;
15928 			uint64_t new_phyint_flags;
15929 			boolean_t changed = B_FALSE;
15930 			boolean_t went_up;
15931 
15932 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
15933 			mutex_enter(&phyint->phyint_lock);
15934 			new_phyint_flags = went_up ?
15935 			    phyint->phyint_flags | PHYI_RUNNING :
15936 			    phyint->phyint_flags & ~PHYI_RUNNING;
15937 			if (new_phyint_flags != phyint->phyint_flags) {
15938 				phyint->phyint_flags = new_phyint_flags;
15939 				changed = B_TRUE;
15940 			}
15941 			mutex_exit(&phyint->phyint_lock);
15942 			/*
15943 			 * ill_restart_dad handles the DAD restart and routing
15944 			 * socket notification logic.
15945 			 */
15946 			if (changed) {
15947 				ill_restart_dad(phyint->phyint_illv4, went_up);
15948 				ill_restart_dad(phyint->phyint_illv6, went_up);
15949 			}
15950 			break;
15951 		}
15952 		case DL_NOTE_PROMISC_ON_PHYS:
15953 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15954 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
15955 			mutex_enter(&ill->ill_lock);
15956 			ill->ill_promisc_on_phys = B_TRUE;
15957 			mutex_exit(&ill->ill_lock);
15958 			break;
15959 		case DL_NOTE_PROMISC_OFF_PHYS:
15960 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15961 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
15962 			mutex_enter(&ill->ill_lock);
15963 			ill->ill_promisc_on_phys = B_FALSE;
15964 			mutex_exit(&ill->ill_lock);
15965 			break;
15966 		case DL_NOTE_CAPAB_RENEG:
15967 			/*
15968 			 * Something changed on the driver side.
15969 			 * It wants us to renegotiate the capabilities
15970 			 * on this ill. One possible cause is the aggregation
15971 			 * interface under us where a port got added or
15972 			 * went away.
15973 			 *
15974 			 * If the capability negotiation is already done
15975 			 * or is in progress, reset the capabilities and
15976 			 * mark the ill's ill_capab_reneg to be B_TRUE,
15977 			 * so that when the ack comes back, we can start
15978 			 * the renegotiation process.
15979 			 *
15980 			 * Note that if ill_capab_reneg is already B_TRUE
15981 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
15982 			 * the capability resetting request has been sent
15983 			 * and the renegotiation has not been started yet;
15984 			 * nothing needs to be done in this case.
15985 			 */
15986 			if (ill->ill_dlpi_capab_state != IDS_UNKNOWN) {
15987 				ill_capability_reset(ill);
15988 				ill->ill_capab_reneg = B_TRUE;
15989 			}
15990 			break;
15991 		default:
15992 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
15993 			    "type 0x%x for DL_NOTIFY_IND\n",
15994 			    notify->dl_notification));
15995 			break;
15996 		}
15997 
15998 		/*
15999 		 * As this is an asynchronous operation, we
16000 		 * should not call ill_dlpi_done
16001 		 */
16002 		break;
16003 	}
16004 	case DL_NOTIFY_ACK: {
16005 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
16006 
16007 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
16008 			ill->ill_note_link = 1;
16009 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
16010 		break;
16011 	}
16012 	case DL_PHYS_ADDR_ACK: {
16013 		/*
16014 		 * As part of plumbing the interface via SIOCSLIFNAME,
16015 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
16016 		 * whose answers we receive here.  As each answer is received,
16017 		 * we call ill_dlpi_done() to dispatch the next request as
16018 		 * we're processing the current one.  Once all answers have
16019 		 * been received, we use ipsq_pending_mp_get() to dequeue the
16020 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
16021 		 * is invoked from an ill queue, conn_oper_pending_ill is not
16022 		 * available, but we know the ioctl is pending on ill_wq.)
16023 		 */
16024 		uint_t paddrlen, paddroff;
16025 
16026 		paddrreq = ill->ill_phys_addr_pend;
16027 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
16028 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
16029 
16030 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
16031 		if (paddrreq == DL_IPV6_TOKEN) {
16032 			/*
16033 			 * bcopy to low-order bits of ill_token
16034 			 *
16035 			 * XXX Temporary hack - currently, all known tokens
16036 			 * are 64 bits, so I'll cheat for the moment.
16037 			 */
16038 			bcopy(mp->b_rptr + paddroff,
16039 			    &ill->ill_token.s6_addr32[2], paddrlen);
16040 			ill->ill_token_length = paddrlen;
16041 			break;
16042 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16043 			ASSERT(ill->ill_nd_lla_mp == NULL);
16044 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
16045 			mp = NULL;
16046 			break;
16047 		}
16048 
16049 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
16050 		ASSERT(ill->ill_phys_addr_mp == NULL);
16051 		if (!ill->ill_ifname_pending)
16052 			break;
16053 		ill->ill_ifname_pending = 0;
16054 		if (!ioctl_aborted)
16055 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16056 		if (mp1 != NULL) {
16057 			ASSERT(connp == NULL);
16058 			q = ill->ill_wq;
16059 		}
16060 		/*
16061 		 * If any error acks received during the plumbing sequence,
16062 		 * ill_ifname_pending_err will be set. Break out and send up
16063 		 * the error to the pending ioctl.
16064 		 */
16065 		if (ill->ill_ifname_pending_err != 0) {
16066 			err = ill->ill_ifname_pending_err;
16067 			ill->ill_ifname_pending_err = 0;
16068 			break;
16069 		}
16070 
16071 		ill->ill_phys_addr_mp = mp;
16072 		ill->ill_phys_addr = mp->b_rptr + paddroff;
16073 		mp = NULL;
16074 
16075 		/*
16076 		 * If paddrlen is zero, the DLPI provider doesn't support
16077 		 * physical addresses.  The other two tests were historical
16078 		 * workarounds for bugs in our former PPP implementation, but
16079 		 * now other things have grown dependencies on them -- e.g.,
16080 		 * the tun module specifies a dl_addr_length of zero in its
16081 		 * DL_BIND_ACK, but then specifies an incorrect value in its
16082 		 * DL_PHYS_ADDR_ACK.  These bogus checks need to be removed,
16083 		 * but only after careful testing ensures that all dependent
16084 		 * broken DLPI providers have been fixed.
16085 		 */
16086 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0 ||
16087 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
16088 			ill->ill_phys_addr = NULL;
16089 		} else if (paddrlen != ill->ill_phys_addr_length) {
16090 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16091 			    paddrlen, ill->ill_phys_addr_length));
16092 			err = EINVAL;
16093 			break;
16094 		}
16095 
16096 		if (ill->ill_nd_lla_mp == NULL) {
16097 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16098 				err = ENOMEM;
16099 				break;
16100 			}
16101 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16102 		}
16103 
16104 		/*
16105 		 * Set the interface token.  If the zeroth interface address
16106 		 * is unspecified, then set it to the link local address.
16107 		 */
16108 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
16109 			(void) ill_setdefaulttoken(ill);
16110 
16111 		ASSERT(ill->ill_ipif->ipif_id == 0);
16112 		if (ipif != NULL &&
16113 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr)) {
16114 			(void) ipif_setlinklocal(ipif);
16115 		}
16116 		break;
16117 	}
16118 	case DL_OK_ACK:
16119 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16120 		    dlpi_prim_str((int)dloa->dl_correct_primitive),
16121 		    dloa->dl_correct_primitive));
16122 		switch (dloa->dl_correct_primitive) {
16123 		case DL_PROMISCON_REQ:
16124 		case DL_PROMISCOFF_REQ:
16125 		case DL_ENABMULTI_REQ:
16126 		case DL_DISABMULTI_REQ:
16127 		case DL_UNBIND_REQ:
16128 		case DL_ATTACH_REQ:
16129 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16130 			break;
16131 		}
16132 		break;
16133 	default:
16134 		break;
16135 	}
16136 
16137 	freemsg(mp);
16138 	if (mp1 != NULL) {
16139 		/*
16140 		 * The operation must complete without EINPROGRESS
16141 		 * since ipsq_pending_mp_get() has removed the mblk
16142 		 * from ipsq_pending_mp.  Otherwise, the operation
16143 		 * will be stuck forever in the ipsq.
16144 		 */
16145 		ASSERT(err != EINPROGRESS);
16146 
16147 		switch (ipsq->ipsq_current_ioctl) {
16148 		case 0:
16149 			ipsq_current_finish(ipsq);
16150 			break;
16151 
16152 		case SIOCLIFADDIF:
16153 		case SIOCSLIFNAME:
16154 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16155 			break;
16156 
16157 		default:
16158 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16159 			break;
16160 		}
16161 	}
16162 }
16163 
16164 /*
16165  * ip_rput_other is called by ip_rput to handle messages modifying the global
16166  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16167  */
16168 /* ARGSUSED */
16169 void
16170 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16171 {
16172 	ill_t		*ill;
16173 	struct iocblk	*iocp;
16174 	mblk_t		*mp1;
16175 	conn_t		*connp = NULL;
16176 
16177 	ip1dbg(("ip_rput_other "));
16178 	ill = (ill_t *)q->q_ptr;
16179 	/*
16180 	 * This routine is not a writer in the case of SIOCGTUNPARAM
16181 	 * in which case ipsq is NULL.
16182 	 */
16183 	if (ipsq != NULL) {
16184 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16185 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
16186 	}
16187 
16188 	switch (mp->b_datap->db_type) {
16189 	case M_ERROR:
16190 	case M_HANGUP:
16191 		/*
16192 		 * The device has a problem.  We force the ILL down.  It can
16193 		 * be brought up again manually using SIOCSIFFLAGS (via
16194 		 * ifconfig or equivalent).
16195 		 */
16196 		ASSERT(ipsq != NULL);
16197 		if (mp->b_rptr < mp->b_wptr)
16198 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16199 		if (ill->ill_error == 0)
16200 			ill->ill_error = ENXIO;
16201 		if (!ill_down_start(q, mp))
16202 			return;
16203 		ipif_all_down_tail(ipsq, q, mp, NULL);
16204 		break;
16205 	case M_IOCACK:
16206 		iocp = (struct iocblk *)mp->b_rptr;
16207 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16208 		switch (iocp->ioc_cmd) {
16209 		case SIOCSTUNPARAM:
16210 		case OSIOCSTUNPARAM:
16211 			ASSERT(ipsq != NULL);
16212 			/*
16213 			 * Finish socket ioctl passed through to tun.
16214 			 * We should have an IOCTL waiting on this.
16215 			 */
16216 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16217 			if (ill->ill_isv6) {
16218 				struct iftun_req *ta;
16219 
16220 				/*
16221 				 * if a source or destination is
16222 				 * being set, try and set the link
16223 				 * local address for the tunnel
16224 				 */
16225 				ta = (struct iftun_req *)mp->b_cont->
16226 				    b_cont->b_rptr;
16227 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16228 					ipif_set_tun_llink(ill, ta);
16229 				}
16230 
16231 			}
16232 			if (mp1 != NULL) {
16233 				/*
16234 				 * Now copy back the b_next/b_prev used by
16235 				 * mi code for the mi_copy* functions.
16236 				 * See ip_sioctl_tunparam() for the reason.
16237 				 * Also protect against missing b_cont.
16238 				 */
16239 				if (mp->b_cont != NULL) {
16240 					mp->b_cont->b_next =
16241 					    mp1->b_cont->b_next;
16242 					mp->b_cont->b_prev =
16243 					    mp1->b_cont->b_prev;
16244 				}
16245 				inet_freemsg(mp1);
16246 				ASSERT(connp != NULL);
16247 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16248 				    iocp->ioc_error, NO_COPYOUT, ipsq);
16249 			} else {
16250 				ASSERT(connp == NULL);
16251 				putnext(q, mp);
16252 			}
16253 			break;
16254 		case SIOCGTUNPARAM:
16255 		case OSIOCGTUNPARAM:
16256 			/*
16257 			 * This is really M_IOCDATA from the tunnel driver.
16258 			 * convert back and complete the ioctl.
16259 			 * We should have an IOCTL waiting on this.
16260 			 */
16261 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16262 			if (mp1) {
16263 				/*
16264 				 * Now copy back the b_next/b_prev used by
16265 				 * mi code for the mi_copy* functions.
16266 				 * See ip_sioctl_tunparam() for the reason.
16267 				 * Also protect against missing b_cont.
16268 				 */
16269 				if (mp->b_cont != NULL) {
16270 					mp->b_cont->b_next =
16271 					    mp1->b_cont->b_next;
16272 					mp->b_cont->b_prev =
16273 					    mp1->b_cont->b_prev;
16274 				}
16275 				inet_freemsg(mp1);
16276 				if (iocp->ioc_error == 0)
16277 					mp->b_datap->db_type = M_IOCDATA;
16278 				ASSERT(connp != NULL);
16279 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16280 				    iocp->ioc_error, COPYOUT, NULL);
16281 			} else {
16282 				ASSERT(connp == NULL);
16283 				putnext(q, mp);
16284 			}
16285 			break;
16286 		default:
16287 			break;
16288 		}
16289 		break;
16290 	case M_IOCNAK:
16291 		iocp = (struct iocblk *)mp->b_rptr;
16292 
16293 		switch (iocp->ioc_cmd) {
16294 		int mode;
16295 
16296 		case DL_IOC_HDR_INFO:
16297 			/*
16298 			 * If this was the first attempt turn of the
16299 			 * fastpath probing.
16300 			 */
16301 			mutex_enter(&ill->ill_lock);
16302 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16303 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16304 				mutex_exit(&ill->ill_lock);
16305 				ill_fastpath_nack(ill);
16306 				ip1dbg(("ip_rput: DLPI fastpath off on "
16307 				    "interface %s\n",
16308 				    ill->ill_name));
16309 			} else {
16310 				mutex_exit(&ill->ill_lock);
16311 			}
16312 			freemsg(mp);
16313 			break;
16314 		case SIOCSTUNPARAM:
16315 		case OSIOCSTUNPARAM:
16316 			ASSERT(ipsq != NULL);
16317 			/*
16318 			 * Finish socket ioctl passed through to tun
16319 			 * We should have an IOCTL waiting on this.
16320 			 */
16321 			/* FALLTHRU */
16322 		case SIOCGTUNPARAM:
16323 		case OSIOCGTUNPARAM:
16324 			/*
16325 			 * This is really M_IOCDATA from the tunnel driver.
16326 			 * convert back and complete the ioctl.
16327 			 * We should have an IOCTL waiting on this.
16328 			 */
16329 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16330 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16331 				mp1 = ill_pending_mp_get(ill, &connp,
16332 				    iocp->ioc_id);
16333 				mode = COPYOUT;
16334 				ipsq = NULL;
16335 			} else {
16336 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16337 				mode = NO_COPYOUT;
16338 			}
16339 			if (mp1 != NULL) {
16340 				/*
16341 				 * Now copy back the b_next/b_prev used by
16342 				 * mi code for the mi_copy* functions.
16343 				 * See ip_sioctl_tunparam() for the reason.
16344 				 * Also protect against missing b_cont.
16345 				 */
16346 				if (mp->b_cont != NULL) {
16347 					mp->b_cont->b_next =
16348 					    mp1->b_cont->b_next;
16349 					mp->b_cont->b_prev =
16350 					    mp1->b_cont->b_prev;
16351 				}
16352 				inet_freemsg(mp1);
16353 				if (iocp->ioc_error == 0)
16354 					iocp->ioc_error = EINVAL;
16355 				ASSERT(connp != NULL);
16356 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16357 				    iocp->ioc_error, mode, ipsq);
16358 			} else {
16359 				ASSERT(connp == NULL);
16360 				putnext(q, mp);
16361 			}
16362 			break;
16363 		default:
16364 			break;
16365 		}
16366 	default:
16367 		break;
16368 	}
16369 }
16370 
16371 /*
16372  * NOTE : This function does not ire_refrele the ire argument passed in.
16373  *
16374  * IPQoS notes
16375  * IP policy is invoked twice for a forwarded packet, once on the read side
16376  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16377  * enabled. An additional parameter, in_ill, has been added for this purpose.
16378  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16379  * because ip_mroute drops this information.
16380  *
16381  */
16382 void
16383 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16384 {
16385 	uint32_t	old_pkt_len;
16386 	uint32_t	pkt_len;
16387 	queue_t	*q;
16388 	uint32_t	sum;
16389 #define	rptr	((uchar_t *)ipha)
16390 	uint32_t	max_frag;
16391 	uint32_t	ill_index;
16392 	ill_t		*out_ill;
16393 	mib2_ipIfStatsEntry_t *mibptr;
16394 	ip_stack_t	*ipst = ((ill_t *)(ire->ire_stq->q_ptr))->ill_ipst;
16395 
16396 	/* Get the ill_index of the incoming ILL */
16397 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16398 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16399 
16400 	/* Initiate Read side IPPF processing */
16401 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16402 		ip_process(IPP_FWD_IN, &mp, ill_index);
16403 		if (mp == NULL) {
16404 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16405 			    "during IPPF processing\n"));
16406 			return;
16407 		}
16408 	}
16409 
16410 	/* Adjust the checksum to reflect the ttl decrement. */
16411 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16412 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16413 
16414 	if (ipha->ipha_ttl-- <= 1) {
16415 		if (ip_csum_hdr(ipha)) {
16416 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16417 			goto drop_pkt;
16418 		}
16419 		/*
16420 		 * Note: ire_stq this will be NULL for multicast
16421 		 * datagrams using the long path through arp (the IRE
16422 		 * is not an IRE_CACHE). This should not cause
16423 		 * problems since we don't generate ICMP errors for
16424 		 * multicast packets.
16425 		 */
16426 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16427 		q = ire->ire_stq;
16428 		if (q != NULL) {
16429 			/* Sent by forwarding path, and router is global zone */
16430 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16431 			    GLOBAL_ZONEID, ipst);
16432 		} else
16433 			freemsg(mp);
16434 		return;
16435 	}
16436 
16437 	/*
16438 	 * Don't forward if the interface is down
16439 	 */
16440 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16441 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16442 		ip2dbg(("ip_rput_forward:interface is down\n"));
16443 		goto drop_pkt;
16444 	}
16445 
16446 	/* Get the ill_index of the outgoing ILL */
16447 	out_ill = ire_to_ill(ire);
16448 	ill_index = out_ill->ill_phyint->phyint_ifindex;
16449 
16450 	DTRACE_PROBE4(ip4__forwarding__start,
16451 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16452 
16453 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16454 	    ipst->ips_ipv4firewall_forwarding,
16455 	    in_ill, out_ill, ipha, mp, mp, ipst);
16456 
16457 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16458 
16459 	if (mp == NULL)
16460 		return;
16461 	old_pkt_len = pkt_len = ntohs(ipha->ipha_length);
16462 
16463 	if (is_system_labeled()) {
16464 		mblk_t *mp1;
16465 
16466 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16467 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16468 			goto drop_pkt;
16469 		}
16470 		/* Size may have changed */
16471 		mp = mp1;
16472 		ipha = (ipha_t *)mp->b_rptr;
16473 		pkt_len = ntohs(ipha->ipha_length);
16474 	}
16475 
16476 	/* Check if there are options to update */
16477 	if (!IS_SIMPLE_IPH(ipha)) {
16478 		if (ip_csum_hdr(ipha)) {
16479 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16480 			goto drop_pkt;
16481 		}
16482 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16483 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16484 			return;
16485 		}
16486 
16487 		ipha->ipha_hdr_checksum = 0;
16488 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16489 	}
16490 	max_frag = ire->ire_max_frag;
16491 	if (pkt_len > max_frag) {
16492 		/*
16493 		 * It needs fragging on its way out.  We haven't
16494 		 * verified the header checksum yet.  Since we
16495 		 * are going to put a surely good checksum in the
16496 		 * outgoing header, we have to make sure that it
16497 		 * was good coming in.
16498 		 */
16499 		if (ip_csum_hdr(ipha)) {
16500 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16501 			goto drop_pkt;
16502 		}
16503 		/* Initiate Write side IPPF processing */
16504 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16505 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16506 			if (mp == NULL) {
16507 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16508 				    " during IPPF processing\n"));
16509 				return;
16510 			}
16511 		}
16512 		/*
16513 		 * Handle labeled packet resizing.
16514 		 *
16515 		 * If we have added a label, inform ip_wput_frag() of its
16516 		 * effect on the MTU for ICMP messages.
16517 		 */
16518 		if (pkt_len > old_pkt_len) {
16519 			uint32_t secopt_size;
16520 
16521 			secopt_size = pkt_len - old_pkt_len;
16522 			if (secopt_size < max_frag)
16523 				max_frag -= secopt_size;
16524 		}
16525 
16526 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID, ipst);
16527 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16528 		return;
16529 	}
16530 
16531 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16532 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16533 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16534 	    ipst->ips_ipv4firewall_physical_out,
16535 	    NULL, out_ill, ipha, mp, mp, ipst);
16536 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16537 	if (mp == NULL)
16538 		return;
16539 
16540 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16541 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16542 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE);
16543 	/* ip_xmit_v4 always consumes the packet */
16544 	return;
16545 
16546 drop_pkt:;
16547 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16548 	freemsg(mp);
16549 #undef	rptr
16550 }
16551 
16552 void
16553 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16554 {
16555 	ire_t	*ire;
16556 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
16557 
16558 	ASSERT(!ipif->ipif_isv6);
16559 	/*
16560 	 * Find an IRE which matches the destination and the outgoing
16561 	 * queue in the cache table. All we need is an IRE_CACHE which
16562 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
16563 	 * then it is enough to have some IRE_CACHE in the group.
16564 	 */
16565 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16566 		dst = ipif->ipif_pp_dst_addr;
16567 
16568 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
16569 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR, ipst);
16570 	if (ire == NULL) {
16571 		/*
16572 		 * Mark this packet to make it be delivered to
16573 		 * ip_rput_forward after the new ire has been
16574 		 * created.
16575 		 */
16576 		mp->b_prev = NULL;
16577 		mp->b_next = mp;
16578 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16579 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
16580 	} else {
16581 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16582 		IRE_REFRELE(ire);
16583 	}
16584 }
16585 
16586 /* Update any source route, record route or timestamp options */
16587 static int
16588 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
16589 {
16590 	ipoptp_t	opts;
16591 	uchar_t		*opt;
16592 	uint8_t		optval;
16593 	uint8_t		optlen;
16594 	ipaddr_t	dst;
16595 	uint32_t	ts;
16596 	ire_t		*dst_ire = NULL;
16597 	ire_t		*tmp_ire = NULL;
16598 	timestruc_t	now;
16599 
16600 	ip2dbg(("ip_rput_forward_options\n"));
16601 	dst = ipha->ipha_dst;
16602 	for (optval = ipoptp_first(&opts, ipha);
16603 	    optval != IPOPT_EOL;
16604 	    optval = ipoptp_next(&opts)) {
16605 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16606 		opt = opts.ipoptp_cur;
16607 		optlen = opts.ipoptp_len;
16608 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16609 		    optval, opts.ipoptp_len));
16610 		switch (optval) {
16611 			uint32_t off;
16612 		case IPOPT_SSRR:
16613 		case IPOPT_LSRR:
16614 			/* Check if adminstratively disabled */
16615 			if (!ipst->ips_ip_forward_src_routed) {
16616 				if (ire->ire_stq != NULL) {
16617 					/*
16618 					 * Sent by forwarding path, and router
16619 					 * is global zone
16620 					 */
16621 					icmp_unreachable(ire->ire_stq, mp,
16622 					    ICMP_SOURCE_ROUTE_FAILED,
16623 					    GLOBAL_ZONEID, ipst);
16624 				} else {
16625 					ip0dbg(("ip_rput_forward_options: "
16626 					    "unable to send unreach\n"));
16627 					freemsg(mp);
16628 				}
16629 				return (-1);
16630 			}
16631 
16632 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16633 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16634 			if (dst_ire == NULL) {
16635 				/*
16636 				 * Must be partial since ip_rput_options
16637 				 * checked for strict.
16638 				 */
16639 				break;
16640 			}
16641 			off = opt[IPOPT_OFFSET];
16642 			off--;
16643 		redo_srr:
16644 			if (optlen < IP_ADDR_LEN ||
16645 			    off > optlen - IP_ADDR_LEN) {
16646 				/* End of source route */
16647 				ip1dbg((
16648 				    "ip_rput_forward_options: end of SR\n"));
16649 				ire_refrele(dst_ire);
16650 				break;
16651 			}
16652 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16653 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16654 			    IP_ADDR_LEN);
16655 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16656 			    ntohl(dst)));
16657 
16658 			/*
16659 			 * Check if our address is present more than
16660 			 * once as consecutive hops in source route.
16661 			 */
16662 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16663 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16664 			if (tmp_ire != NULL) {
16665 				ire_refrele(tmp_ire);
16666 				off += IP_ADDR_LEN;
16667 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16668 				goto redo_srr;
16669 			}
16670 			ipha->ipha_dst = dst;
16671 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16672 			ire_refrele(dst_ire);
16673 			break;
16674 		case IPOPT_RR:
16675 			off = opt[IPOPT_OFFSET];
16676 			off--;
16677 			if (optlen < IP_ADDR_LEN ||
16678 			    off > optlen - IP_ADDR_LEN) {
16679 				/* No more room - ignore */
16680 				ip1dbg((
16681 				    "ip_rput_forward_options: end of RR\n"));
16682 				break;
16683 			}
16684 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16685 			    IP_ADDR_LEN);
16686 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16687 			break;
16688 		case IPOPT_TS:
16689 			/* Insert timestamp if there is room */
16690 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16691 			case IPOPT_TS_TSONLY:
16692 				off = IPOPT_TS_TIMELEN;
16693 				break;
16694 			case IPOPT_TS_PRESPEC:
16695 			case IPOPT_TS_PRESPEC_RFC791:
16696 				/* Verify that the address matched */
16697 				off = opt[IPOPT_OFFSET] - 1;
16698 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16699 				dst_ire = ire_ctable_lookup(dst, 0,
16700 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16701 				    MATCH_IRE_TYPE, ipst);
16702 				if (dst_ire == NULL) {
16703 					/* Not for us */
16704 					break;
16705 				}
16706 				ire_refrele(dst_ire);
16707 				/* FALLTHRU */
16708 			case IPOPT_TS_TSANDADDR:
16709 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16710 				break;
16711 			default:
16712 				/*
16713 				 * ip_*put_options should have already
16714 				 * dropped this packet.
16715 				 */
16716 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16717 				    "unknown IT - bug in ip_rput_options?\n");
16718 				return (0);	/* Keep "lint" happy */
16719 			}
16720 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16721 				/* Increase overflow counter */
16722 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16723 				opt[IPOPT_POS_OV_FLG] =
16724 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16725 				    (off << 4));
16726 				break;
16727 			}
16728 			off = opt[IPOPT_OFFSET] - 1;
16729 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16730 			case IPOPT_TS_PRESPEC:
16731 			case IPOPT_TS_PRESPEC_RFC791:
16732 			case IPOPT_TS_TSANDADDR:
16733 				bcopy(&ire->ire_src_addr,
16734 				    (char *)opt + off, IP_ADDR_LEN);
16735 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16736 				/* FALLTHRU */
16737 			case IPOPT_TS_TSONLY:
16738 				off = opt[IPOPT_OFFSET] - 1;
16739 				/* Compute # of milliseconds since midnight */
16740 				gethrestime(&now);
16741 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16742 				    now.tv_nsec / (NANOSEC / MILLISEC);
16743 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16744 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16745 				break;
16746 			}
16747 			break;
16748 		}
16749 	}
16750 	return (0);
16751 }
16752 
16753 /*
16754  * This is called after processing at least one of AH/ESP headers.
16755  *
16756  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16757  * the actual, physical interface on which the packet was received,
16758  * but, when ip_strict_dst_multihoming is set to 1, could be the
16759  * interface which had the ipha_dst configured when the packet went
16760  * through ip_rput. The ill_index corresponding to the recv_ill
16761  * is saved in ipsec_in_rill_index
16762  *
16763  * NOTE2: The "ire" argument is only used in IPv4 cases.  This function
16764  * cannot assume "ire" points to valid data for any IPv6 cases.
16765  */
16766 void
16767 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
16768 {
16769 	mblk_t *mp;
16770 	ipaddr_t dst;
16771 	in6_addr_t *v6dstp;
16772 	ipha_t *ipha;
16773 	ip6_t *ip6h;
16774 	ipsec_in_t *ii;
16775 	boolean_t ill_need_rele = B_FALSE;
16776 	boolean_t rill_need_rele = B_FALSE;
16777 	boolean_t ire_need_rele = B_FALSE;
16778 	netstack_t	*ns;
16779 	ip_stack_t	*ipst;
16780 
16781 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
16782 	ASSERT(ii->ipsec_in_ill_index != 0);
16783 	ns = ii->ipsec_in_ns;
16784 	ASSERT(ii->ipsec_in_ns != NULL);
16785 	ipst = ns->netstack_ip;
16786 
16787 	mp = ipsec_mp->b_cont;
16788 	ASSERT(mp != NULL);
16789 
16790 
16791 	if (ill == NULL) {
16792 		ASSERT(recv_ill == NULL);
16793 		/*
16794 		 * We need to get the original queue on which ip_rput_local
16795 		 * or ip_rput_data_v6 was called.
16796 		 */
16797 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
16798 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
16799 		ill_need_rele = B_TRUE;
16800 
16801 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
16802 			recv_ill = ill_lookup_on_ifindex(
16803 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
16804 			    NULL, NULL, NULL, NULL, ipst);
16805 			rill_need_rele = B_TRUE;
16806 		} else {
16807 			recv_ill = ill;
16808 		}
16809 
16810 		if ((ill == NULL) || (recv_ill == NULL)) {
16811 			ip0dbg(("ip_fanout_proto_again: interface "
16812 			    "disappeared\n"));
16813 			if (ill != NULL)
16814 				ill_refrele(ill);
16815 			if (recv_ill != NULL)
16816 				ill_refrele(recv_ill);
16817 			freemsg(ipsec_mp);
16818 			return;
16819 		}
16820 	}
16821 
16822 	ASSERT(ill != NULL && recv_ill != NULL);
16823 
16824 	if (mp->b_datap->db_type == M_CTL) {
16825 		/*
16826 		 * AH/ESP is returning the ICMP message after
16827 		 * removing their headers. Fanout again till
16828 		 * it gets to the right protocol.
16829 		 */
16830 		if (ii->ipsec_in_v4) {
16831 			icmph_t *icmph;
16832 			int iph_hdr_length;
16833 			int hdr_length;
16834 
16835 			ipha = (ipha_t *)mp->b_rptr;
16836 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
16837 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
16838 			ipha = (ipha_t *)&icmph[1];
16839 			hdr_length = IPH_HDR_LENGTH(ipha);
16840 			/*
16841 			 * icmp_inbound_error_fanout may need to do pullupmsg.
16842 			 * Reset the type to M_DATA.
16843 			 */
16844 			mp->b_datap->db_type = M_DATA;
16845 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
16846 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
16847 			    B_FALSE, ill, ii->ipsec_in_zoneid);
16848 		} else {
16849 			icmp6_t *icmp6;
16850 			int hdr_length;
16851 
16852 			ip6h = (ip6_t *)mp->b_rptr;
16853 			/* Don't call hdr_length_v6() unless you have to. */
16854 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
16855 				hdr_length = ip_hdr_length_v6(mp, ip6h);
16856 			else
16857 				hdr_length = IPV6_HDR_LEN;
16858 
16859 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
16860 			/*
16861 			 * icmp_inbound_error_fanout_v6 may need to do
16862 			 * pullupmsg.  Reset the type to M_DATA.
16863 			 */
16864 			mp->b_datap->db_type = M_DATA;
16865 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
16866 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
16867 		}
16868 		if (ill_need_rele)
16869 			ill_refrele(ill);
16870 		if (rill_need_rele)
16871 			ill_refrele(recv_ill);
16872 		return;
16873 	}
16874 
16875 	if (ii->ipsec_in_v4) {
16876 		ipha = (ipha_t *)mp->b_rptr;
16877 		dst = ipha->ipha_dst;
16878 		if (CLASSD(dst)) {
16879 			/*
16880 			 * Multicast has to be delivered to all streams.
16881 			 */
16882 			dst = INADDR_BROADCAST;
16883 		}
16884 
16885 		if (ire == NULL) {
16886 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
16887 			    MBLK_GETLABEL(mp), ipst);
16888 			if (ire == NULL) {
16889 				if (ill_need_rele)
16890 					ill_refrele(ill);
16891 				if (rill_need_rele)
16892 					ill_refrele(recv_ill);
16893 				ip1dbg(("ip_fanout_proto_again: "
16894 				    "IRE not found"));
16895 				freemsg(ipsec_mp);
16896 				return;
16897 			}
16898 			ire_need_rele = B_TRUE;
16899 		}
16900 
16901 		switch (ipha->ipha_protocol) {
16902 			case IPPROTO_UDP:
16903 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
16904 				    recv_ill);
16905 				if (ire_need_rele)
16906 					ire_refrele(ire);
16907 				break;
16908 			case IPPROTO_TCP:
16909 				if (!ire_need_rele)
16910 					IRE_REFHOLD(ire);
16911 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
16912 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
16913 				IRE_REFRELE(ire);
16914 				if (mp != NULL)
16915 					squeue_enter_chain(GET_SQUEUE(mp), mp,
16916 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
16917 				break;
16918 			case IPPROTO_SCTP:
16919 				if (!ire_need_rele)
16920 					IRE_REFHOLD(ire);
16921 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
16922 				    ipsec_mp, 0, ill->ill_rq, dst);
16923 				break;
16924 			default:
16925 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
16926 				    recv_ill, B_FALSE);
16927 				if (ire_need_rele)
16928 					ire_refrele(ire);
16929 				break;
16930 		}
16931 	} else {
16932 		uint32_t rput_flags = 0;
16933 
16934 		ip6h = (ip6_t *)mp->b_rptr;
16935 		v6dstp = &ip6h->ip6_dst;
16936 		/*
16937 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
16938 		 * address.
16939 		 *
16940 		 * Currently, we don't store that state in the IPSEC_IN
16941 		 * message, and we may need to.
16942 		 */
16943 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
16944 		    IP6_IN_LLMCAST : 0);
16945 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
16946 		    NULL, NULL);
16947 	}
16948 	if (ill_need_rele)
16949 		ill_refrele(ill);
16950 	if (rill_need_rele)
16951 		ill_refrele(recv_ill);
16952 }
16953 
16954 /*
16955  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
16956  * returns 'true' if there are still fragments left on the queue, in
16957  * which case we restart the timer.
16958  */
16959 void
16960 ill_frag_timer(void *arg)
16961 {
16962 	ill_t	*ill = (ill_t *)arg;
16963 	boolean_t frag_pending;
16964 	ip_stack_t	*ipst = ill->ill_ipst;
16965 
16966 	mutex_enter(&ill->ill_lock);
16967 	ASSERT(!ill->ill_fragtimer_executing);
16968 	if (ill->ill_state_flags & ILL_CONDEMNED) {
16969 		ill->ill_frag_timer_id = 0;
16970 		mutex_exit(&ill->ill_lock);
16971 		return;
16972 	}
16973 	ill->ill_fragtimer_executing = 1;
16974 	mutex_exit(&ill->ill_lock);
16975 
16976 	frag_pending = ill_frag_timeout(ill, ipst->ips_ip_g_frag_timeout);
16977 
16978 	/*
16979 	 * Restart the timer, if we have fragments pending or if someone
16980 	 * wanted us to be scheduled again.
16981 	 */
16982 	mutex_enter(&ill->ill_lock);
16983 	ill->ill_fragtimer_executing = 0;
16984 	ill->ill_frag_timer_id = 0;
16985 	if (frag_pending || ill->ill_fragtimer_needrestart)
16986 		ill_frag_timer_start(ill);
16987 	mutex_exit(&ill->ill_lock);
16988 }
16989 
16990 void
16991 ill_frag_timer_start(ill_t *ill)
16992 {
16993 	ip_stack_t	*ipst = ill->ill_ipst;
16994 
16995 	ASSERT(MUTEX_HELD(&ill->ill_lock));
16996 
16997 	/* If the ill is closing or opening don't proceed */
16998 	if (ill->ill_state_flags & ILL_CONDEMNED)
16999 		return;
17000 
17001 	if (ill->ill_fragtimer_executing) {
17002 		/*
17003 		 * ill_frag_timer is currently executing. Just record the
17004 		 * the fact that we want the timer to be restarted.
17005 		 * ill_frag_timer will post a timeout before it returns,
17006 		 * ensuring it will be called again.
17007 		 */
17008 		ill->ill_fragtimer_needrestart = 1;
17009 		return;
17010 	}
17011 
17012 	if (ill->ill_frag_timer_id == 0) {
17013 		/*
17014 		 * The timer is neither running nor is the timeout handler
17015 		 * executing. Post a timeout so that ill_frag_timer will be
17016 		 * called
17017 		 */
17018 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
17019 		    MSEC_TO_TICK(ipst->ips_ip_g_frag_timo_ms >> 1));
17020 		ill->ill_fragtimer_needrestart = 0;
17021 	}
17022 }
17023 
17024 /*
17025  * This routine is needed for loopback when forwarding multicasts.
17026  *
17027  * IPQoS Notes:
17028  * IPPF processing is done in fanout routines.
17029  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
17030  * processing for IPsec packets is done when it comes back in clear.
17031  * NOTE : The callers of this function need to do the ire_refrele for the
17032  *	  ire that is being passed in.
17033  */
17034 void
17035 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17036     ill_t *recv_ill, boolean_t esp_in_udp_packet)
17037 {
17038 	ill_t	*ill = (ill_t *)q->q_ptr;
17039 	uint32_t	sum;
17040 	uint32_t	u1;
17041 	uint32_t	u2;
17042 	int		hdr_length;
17043 	boolean_t	mctl_present;
17044 	mblk_t		*first_mp = mp;
17045 	mblk_t		*hada_mp = NULL;
17046 	ipha_t		*inner_ipha;
17047 	ip_stack_t	*ipst;
17048 
17049 	ASSERT(recv_ill != NULL);
17050 	ipst = recv_ill->ill_ipst;
17051 
17052 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17053 	    "ip_rput_locl_start: q %p", q);
17054 
17055 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17056 	ASSERT(ill != NULL);
17057 
17058 
17059 #define	rptr	((uchar_t *)ipha)
17060 #define	iphs	((uint16_t *)ipha)
17061 
17062 	/*
17063 	 * no UDP or TCP packet should come here anymore.
17064 	 */
17065 	ASSERT(ipha->ipha_protocol != IPPROTO_TCP &&
17066 	    ipha->ipha_protocol != IPPROTO_UDP);
17067 
17068 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17069 	if (mctl_present &&
17070 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17071 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17072 
17073 		/*
17074 		 * It's an IPsec accelerated packet.
17075 		 * Keep a pointer to the data attributes around until
17076 		 * we allocate the ipsec_info_t.
17077 		 */
17078 		IPSECHW_DEBUG(IPSECHW_PKT,
17079 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17080 		hada_mp = first_mp;
17081 		hada_mp->b_cont = NULL;
17082 		/*
17083 		 * Since it is accelerated, it comes directly from
17084 		 * the ill and the data attributes is followed by
17085 		 * the packet data.
17086 		 */
17087 		ASSERT(mp->b_datap->db_type != M_CTL);
17088 		first_mp = mp;
17089 		mctl_present = B_FALSE;
17090 	}
17091 
17092 	/*
17093 	 * IF M_CTL is not present, then ipsec_in_is_secure
17094 	 * should return B_TRUE. There is a case where loopback
17095 	 * packets has an M_CTL in the front with all the
17096 	 * IPsec options set to IPSEC_PREF_NEVER - which means
17097 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17098 	 * packets never comes here, it is safe to ASSERT the
17099 	 * following.
17100 	 */
17101 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17102 
17103 	/*
17104 	 * Also, we should never have an mctl_present if this is an
17105 	 * ESP-in-UDP packet.
17106 	 */
17107 	ASSERT(!mctl_present || !esp_in_udp_packet);
17108 
17109 
17110 	/* u1 is # words of IP options */
17111 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
17112 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17113 
17114 	if (u1 || (!esp_in_udp_packet && !mctl_present)) {
17115 		if (u1) {
17116 			if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17117 				if (hada_mp != NULL)
17118 					freemsg(hada_mp);
17119 				return;
17120 			}
17121 		} else {
17122 			/* Check the IP header checksum.  */
17123 #define	uph	((uint16_t *)ipha)
17124 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
17125 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
17126 #undef  uph
17127 			/* finish doing IP checksum */
17128 			sum = (sum & 0xFFFF) + (sum >> 16);
17129 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
17130 			if (sum && sum != 0xFFFF) {
17131 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17132 				goto drop_pkt;
17133 			}
17134 		}
17135 	}
17136 
17137 	/*
17138 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17139 	 * might be called more than once for secure packets, count only
17140 	 * the first time.
17141 	 */
17142 	if (!mctl_present) {
17143 		UPDATE_IB_PKT_COUNT(ire);
17144 		ire->ire_last_used_time = lbolt;
17145 	}
17146 
17147 	/* Check for fragmentation offset. */
17148 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17149 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17150 	if (u1) {
17151 		/*
17152 		 * We re-assemble fragments before we do the AH/ESP
17153 		 * processing. Thus, M_CTL should not be present
17154 		 * while we are re-assembling.
17155 		 */
17156 		ASSERT(!mctl_present);
17157 		ASSERT(first_mp == mp);
17158 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
17159 			return;
17160 		}
17161 		/*
17162 		 * Make sure that first_mp points back to mp as
17163 		 * the mp we came in with could have changed in
17164 		 * ip_rput_fragment().
17165 		 */
17166 		ipha = (ipha_t *)mp->b_rptr;
17167 		first_mp = mp;
17168 	}
17169 
17170 	/*
17171 	 * Clear hardware checksumming flag as it is currently only
17172 	 * used by TCP and UDP.
17173 	 */
17174 	DB_CKSUMFLAGS(mp) = 0;
17175 
17176 	/* Now we have a complete datagram, destined for this machine. */
17177 	u1 = IPH_HDR_LENGTH(ipha);
17178 	switch (ipha->ipha_protocol) {
17179 	case IPPROTO_ICMP: {
17180 		ire_t		*ire_zone;
17181 		ilm_t		*ilm;
17182 		mblk_t		*mp1;
17183 		zoneid_t	last_zoneid;
17184 
17185 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(recv_ill)) {
17186 			ASSERT(ire->ire_type == IRE_BROADCAST);
17187 			/*
17188 			 * In the multicast case, applications may have joined
17189 			 * the group from different zones, so we need to deliver
17190 			 * the packet to each of them. Loop through the
17191 			 * multicast memberships structures (ilm) on the receive
17192 			 * ill and send a copy of the packet up each matching
17193 			 * one. However, we don't do this for multicasts sent on
17194 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17195 			 * they must stay in the sender's zone.
17196 			 *
17197 			 * ilm_add_v6() ensures that ilms in the same zone are
17198 			 * contiguous in the ill_ilm list. We use this property
17199 			 * to avoid sending duplicates needed when two
17200 			 * applications in the same zone join the same group on
17201 			 * different logical interfaces: we ignore the ilm if
17202 			 * its zoneid is the same as the last matching one.
17203 			 * In addition, the sending of the packet for
17204 			 * ire_zoneid is delayed until all of the other ilms
17205 			 * have been exhausted.
17206 			 */
17207 			last_zoneid = -1;
17208 			ILM_WALKER_HOLD(recv_ill);
17209 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
17210 			    ilm = ilm->ilm_next) {
17211 				if ((ilm->ilm_flags & ILM_DELETED) ||
17212 				    ipha->ipha_dst != ilm->ilm_addr ||
17213 				    ilm->ilm_zoneid == last_zoneid ||
17214 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17215 				    ilm->ilm_zoneid == ALL_ZONES ||
17216 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17217 					continue;
17218 				mp1 = ip_copymsg(first_mp);
17219 				if (mp1 == NULL)
17220 					continue;
17221 				icmp_inbound(q, mp1, B_TRUE, ill,
17222 				    0, sum, mctl_present, B_TRUE,
17223 				    recv_ill, ilm->ilm_zoneid);
17224 				last_zoneid = ilm->ilm_zoneid;
17225 			}
17226 			ILM_WALKER_RELE(recv_ill);
17227 		} else if (ire->ire_type == IRE_BROADCAST) {
17228 			/*
17229 			 * In the broadcast case, there may be many zones
17230 			 * which need a copy of the packet delivered to them.
17231 			 * There is one IRE_BROADCAST per broadcast address
17232 			 * and per zone; we walk those using a helper function.
17233 			 * In addition, the sending of the packet for ire is
17234 			 * delayed until all of the other ires have been
17235 			 * processed.
17236 			 */
17237 			IRB_REFHOLD(ire->ire_bucket);
17238 			ire_zone = NULL;
17239 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17240 			    ire)) != NULL) {
17241 				mp1 = ip_copymsg(first_mp);
17242 				if (mp1 == NULL)
17243 					continue;
17244 
17245 				UPDATE_IB_PKT_COUNT(ire_zone);
17246 				ire_zone->ire_last_used_time = lbolt;
17247 				icmp_inbound(q, mp1, B_TRUE, ill,
17248 				    0, sum, mctl_present, B_TRUE,
17249 				    recv_ill, ire_zone->ire_zoneid);
17250 			}
17251 			IRB_REFRELE(ire->ire_bucket);
17252 		}
17253 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17254 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17255 		    ire->ire_zoneid);
17256 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17257 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17258 		return;
17259 	}
17260 	case IPPROTO_IGMP:
17261 		/*
17262 		 * If we are not willing to accept IGMP packets in clear,
17263 		 * then check with global policy.
17264 		 */
17265 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17266 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17267 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17268 			if (first_mp == NULL)
17269 				return;
17270 		}
17271 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17272 			freemsg(first_mp);
17273 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17274 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17275 			return;
17276 		}
17277 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17278 			/* Bad packet - discarded by igmp_input */
17279 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17280 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17281 			if (mctl_present)
17282 				freeb(first_mp);
17283 			return;
17284 		}
17285 		/*
17286 		 * igmp_input() may have returned the pulled up message.
17287 		 * So first_mp and ipha need to be reinitialized.
17288 		 */
17289 		ipha = (ipha_t *)mp->b_rptr;
17290 		if (mctl_present)
17291 			first_mp->b_cont = mp;
17292 		else
17293 			first_mp = mp;
17294 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17295 		    connf_head != NULL) {
17296 			/* No user-level listener for IGMP packets */
17297 			goto drop_pkt;
17298 		}
17299 		/* deliver to local raw users */
17300 		break;
17301 	case IPPROTO_PIM:
17302 		/*
17303 		 * If we are not willing to accept PIM packets in clear,
17304 		 * then check with global policy.
17305 		 */
17306 		if (ipst->ips_pim_accept_clear_messages == 0) {
17307 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17308 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17309 			if (first_mp == NULL)
17310 				return;
17311 		}
17312 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17313 			freemsg(first_mp);
17314 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17315 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17316 			return;
17317 		}
17318 		if (pim_input(q, mp, ill) != 0) {
17319 			/* Bad packet - discarded by pim_input */
17320 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17321 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17322 			if (mctl_present)
17323 				freeb(first_mp);
17324 			return;
17325 		}
17326 
17327 		/*
17328 		 * pim_input() may have pulled up the message so ipha needs to
17329 		 * be reinitialized.
17330 		 */
17331 		ipha = (ipha_t *)mp->b_rptr;
17332 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17333 		    connf_head != NULL) {
17334 			/* No user-level listener for PIM packets */
17335 			goto drop_pkt;
17336 		}
17337 		/* deliver to local raw users */
17338 		break;
17339 	case IPPROTO_ENCAP:
17340 		/*
17341 		 * Handle self-encapsulated packets (IP-in-IP where
17342 		 * the inner addresses == the outer addresses).
17343 		 */
17344 		hdr_length = IPH_HDR_LENGTH(ipha);
17345 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17346 		    mp->b_wptr) {
17347 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17348 			    sizeof (ipha_t) - mp->b_rptr)) {
17349 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17350 				freemsg(first_mp);
17351 				return;
17352 			}
17353 			ipha = (ipha_t *)mp->b_rptr;
17354 		}
17355 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17356 		/*
17357 		 * Check the sanity of the inner IP header.
17358 		 */
17359 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17360 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17361 			freemsg(first_mp);
17362 			return;
17363 		}
17364 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17365 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17366 			freemsg(first_mp);
17367 			return;
17368 		}
17369 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17370 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17371 			ipsec_in_t *ii;
17372 
17373 			/*
17374 			 * Self-encapsulated tunnel packet. Remove
17375 			 * the outer IP header and fanout again.
17376 			 * We also need to make sure that the inner
17377 			 * header is pulled up until options.
17378 			 */
17379 			mp->b_rptr = (uchar_t *)inner_ipha;
17380 			ipha = inner_ipha;
17381 			hdr_length = IPH_HDR_LENGTH(ipha);
17382 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17383 				if (!pullupmsg(mp, (uchar_t *)ipha +
17384 				    + hdr_length - mp->b_rptr)) {
17385 					freemsg(first_mp);
17386 					return;
17387 				}
17388 				ipha = (ipha_t *)mp->b_rptr;
17389 			}
17390 			if (!mctl_present) {
17391 				ASSERT(first_mp == mp);
17392 				/*
17393 				 * This means that somebody is sending
17394 				 * Self-encapsualted packets without AH/ESP.
17395 				 * If AH/ESP was present, we would have already
17396 				 * allocated the first_mp.
17397 				 */
17398 				first_mp = ipsec_in_alloc(B_TRUE,
17399 				    ipst->ips_netstack);
17400 				if (first_mp == NULL) {
17401 					ip1dbg(("ip_proto_input: IPSEC_IN "
17402 					    "allocation failure.\n"));
17403 					BUMP_MIB(ill->ill_ip_mib,
17404 					    ipIfStatsInDiscards);
17405 					freemsg(mp);
17406 					return;
17407 				}
17408 				first_mp->b_cont = mp;
17409 			}
17410 			/*
17411 			 * We generally store the ill_index if we need to
17412 			 * do IPsec processing as we lose the ill queue when
17413 			 * we come back. But in this case, we never should
17414 			 * have to store the ill_index here as it should have
17415 			 * been stored previously when we processed the
17416 			 * AH/ESP header in this routine or for non-ipsec
17417 			 * cases, we still have the queue. But for some bad
17418 			 * packets from the wire, we can get to IPsec after
17419 			 * this and we better store the index for that case.
17420 			 */
17421 			ill = (ill_t *)q->q_ptr;
17422 			ii = (ipsec_in_t *)first_mp->b_rptr;
17423 			ii->ipsec_in_ill_index =
17424 			    ill->ill_phyint->phyint_ifindex;
17425 			ii->ipsec_in_rill_index =
17426 			    recv_ill->ill_phyint->phyint_ifindex;
17427 			if (ii->ipsec_in_decaps) {
17428 				/*
17429 				 * This packet is self-encapsulated multiple
17430 				 * times. We don't want to recurse infinitely.
17431 				 * To keep it simple, drop the packet.
17432 				 */
17433 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17434 				freemsg(first_mp);
17435 				return;
17436 			}
17437 			ii->ipsec_in_decaps = B_TRUE;
17438 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17439 			    ire);
17440 			return;
17441 		}
17442 		break;
17443 	case IPPROTO_AH:
17444 	case IPPROTO_ESP: {
17445 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17446 
17447 		/*
17448 		 * Fast path for AH/ESP. If this is the first time
17449 		 * we are sending a datagram to AH/ESP, allocate
17450 		 * a IPSEC_IN message and prepend it. Otherwise,
17451 		 * just fanout.
17452 		 */
17453 
17454 		int ipsec_rc;
17455 		ipsec_in_t *ii;
17456 		netstack_t *ns = ipst->ips_netstack;
17457 
17458 		IP_STAT(ipst, ipsec_proto_ahesp);
17459 		if (!mctl_present) {
17460 			ASSERT(first_mp == mp);
17461 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17462 			if (first_mp == NULL) {
17463 				ip1dbg(("ip_proto_input: IPSEC_IN "
17464 				    "allocation failure.\n"));
17465 				freemsg(hada_mp); /* okay ifnull */
17466 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17467 				freemsg(mp);
17468 				return;
17469 			}
17470 			/*
17471 			 * Store the ill_index so that when we come back
17472 			 * from IPsec we ride on the same queue.
17473 			 */
17474 			ill = (ill_t *)q->q_ptr;
17475 			ii = (ipsec_in_t *)first_mp->b_rptr;
17476 			ii->ipsec_in_ill_index =
17477 			    ill->ill_phyint->phyint_ifindex;
17478 			ii->ipsec_in_rill_index =
17479 			    recv_ill->ill_phyint->phyint_ifindex;
17480 			first_mp->b_cont = mp;
17481 			/*
17482 			 * Cache hardware acceleration info.
17483 			 */
17484 			if (hada_mp != NULL) {
17485 				IPSECHW_DEBUG(IPSECHW_PKT,
17486 				    ("ip_rput_local: caching data attr.\n"));
17487 				ii->ipsec_in_accelerated = B_TRUE;
17488 				ii->ipsec_in_da = hada_mp;
17489 				hada_mp = NULL;
17490 			}
17491 		} else {
17492 			ii = (ipsec_in_t *)first_mp->b_rptr;
17493 		}
17494 
17495 		if (!ipsec_loaded(ipss)) {
17496 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17497 			    ire->ire_zoneid, ipst);
17498 			return;
17499 		}
17500 
17501 		ns = ipst->ips_netstack;
17502 		/* select inbound SA and have IPsec process the pkt */
17503 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17504 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17505 			boolean_t esp_in_udp_sa;
17506 			if (esph == NULL)
17507 				return;
17508 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17509 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17510 			esp_in_udp_sa = ((ii->ipsec_in_esp_sa->ipsa_flags &
17511 			    IPSA_F_NATT) != 0);
17512 			/*
17513 			 * The following is a fancy, but quick, way of saying:
17514 			 * ESP-in-UDP SA and Raw ESP packet --> drop
17515 			 *    OR
17516 			 * ESP SA and ESP-in-UDP packet --> drop
17517 			 */
17518 			if (esp_in_udp_sa != esp_in_udp_packet) {
17519 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17520 				ip_drop_packet(first_mp, B_TRUE, ill, NULL,
17521 				    DROPPER(ns->netstack_ipsec, ipds_esp_no_sa),
17522 				    &ns->netstack_ipsec->ipsec_dropper);
17523 				return;
17524 			}
17525 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17526 			    first_mp, esph);
17527 		} else {
17528 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
17529 			if (ah == NULL)
17530 				return;
17531 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17532 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17533 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17534 			    first_mp, ah);
17535 		}
17536 
17537 		switch (ipsec_rc) {
17538 		case IPSEC_STATUS_SUCCESS:
17539 			break;
17540 		case IPSEC_STATUS_FAILED:
17541 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17542 			/* FALLTHRU */
17543 		case IPSEC_STATUS_PENDING:
17544 			return;
17545 		}
17546 		/* we're done with IPsec processing, send it up */
17547 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17548 		return;
17549 	}
17550 	default:
17551 		break;
17552 	}
17553 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17554 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17555 		    ire->ire_zoneid));
17556 		goto drop_pkt;
17557 	}
17558 	/*
17559 	 * Handle protocols with which IP is less intimate.  There
17560 	 * can be more than one stream bound to a particular
17561 	 * protocol.  When this is the case, each one gets a copy
17562 	 * of any incoming packets.
17563 	 */
17564 	ip_fanout_proto(q, first_mp, ill, ipha,
17565 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17566 	    B_TRUE, recv_ill, ire->ire_zoneid);
17567 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17568 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17569 	return;
17570 
17571 drop_pkt:
17572 	freemsg(first_mp);
17573 	if (hada_mp != NULL)
17574 		freeb(hada_mp);
17575 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17576 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17577 #undef	rptr
17578 #undef  iphs
17579 
17580 }
17581 
17582 /*
17583  * Update any source route, record route or timestamp options.
17584  * Check that we are at end of strict source route.
17585  * The options have already been checked for sanity in ip_rput_options().
17586  */
17587 static boolean_t
17588 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17589     ip_stack_t *ipst)
17590 {
17591 	ipoptp_t	opts;
17592 	uchar_t		*opt;
17593 	uint8_t		optval;
17594 	uint8_t		optlen;
17595 	ipaddr_t	dst;
17596 	uint32_t	ts;
17597 	ire_t		*dst_ire;
17598 	timestruc_t	now;
17599 	zoneid_t	zoneid;
17600 	ill_t		*ill;
17601 
17602 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17603 
17604 	ip2dbg(("ip_rput_local_options\n"));
17605 
17606 	for (optval = ipoptp_first(&opts, ipha);
17607 	    optval != IPOPT_EOL;
17608 	    optval = ipoptp_next(&opts)) {
17609 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17610 		opt = opts.ipoptp_cur;
17611 		optlen = opts.ipoptp_len;
17612 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17613 		    optval, optlen));
17614 		switch (optval) {
17615 			uint32_t off;
17616 		case IPOPT_SSRR:
17617 		case IPOPT_LSRR:
17618 			off = opt[IPOPT_OFFSET];
17619 			off--;
17620 			if (optlen < IP_ADDR_LEN ||
17621 			    off > optlen - IP_ADDR_LEN) {
17622 				/* End of source route */
17623 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17624 				break;
17625 			}
17626 			/*
17627 			 * This will only happen if two consecutive entries
17628 			 * in the source route contains our address or if
17629 			 * it is a packet with a loose source route which
17630 			 * reaches us before consuming the whole source route
17631 			 */
17632 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17633 			if (optval == IPOPT_SSRR) {
17634 				goto bad_src_route;
17635 			}
17636 			/*
17637 			 * Hack: instead of dropping the packet truncate the
17638 			 * source route to what has been used by filling the
17639 			 * rest with IPOPT_NOP.
17640 			 */
17641 			opt[IPOPT_OLEN] = (uint8_t)off;
17642 			while (off < optlen) {
17643 				opt[off++] = IPOPT_NOP;
17644 			}
17645 			break;
17646 		case IPOPT_RR:
17647 			off = opt[IPOPT_OFFSET];
17648 			off--;
17649 			if (optlen < IP_ADDR_LEN ||
17650 			    off > optlen - IP_ADDR_LEN) {
17651 				/* No more room - ignore */
17652 				ip1dbg((
17653 				    "ip_rput_local_options: end of RR\n"));
17654 				break;
17655 			}
17656 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17657 			    IP_ADDR_LEN);
17658 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17659 			break;
17660 		case IPOPT_TS:
17661 			/* Insert timestamp if there is romm */
17662 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17663 			case IPOPT_TS_TSONLY:
17664 				off = IPOPT_TS_TIMELEN;
17665 				break;
17666 			case IPOPT_TS_PRESPEC:
17667 			case IPOPT_TS_PRESPEC_RFC791:
17668 				/* Verify that the address matched */
17669 				off = opt[IPOPT_OFFSET] - 1;
17670 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17671 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17672 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
17673 				    ipst);
17674 				if (dst_ire == NULL) {
17675 					/* Not for us */
17676 					break;
17677 				}
17678 				ire_refrele(dst_ire);
17679 				/* FALLTHRU */
17680 			case IPOPT_TS_TSANDADDR:
17681 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17682 				break;
17683 			default:
17684 				/*
17685 				 * ip_*put_options should have already
17686 				 * dropped this packet.
17687 				 */
17688 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17689 				    "unknown IT - bug in ip_rput_options?\n");
17690 				return (B_TRUE);	/* Keep "lint" happy */
17691 			}
17692 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17693 				/* Increase overflow counter */
17694 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17695 				opt[IPOPT_POS_OV_FLG] =
17696 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17697 				    (off << 4));
17698 				break;
17699 			}
17700 			off = opt[IPOPT_OFFSET] - 1;
17701 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17702 			case IPOPT_TS_PRESPEC:
17703 			case IPOPT_TS_PRESPEC_RFC791:
17704 			case IPOPT_TS_TSANDADDR:
17705 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17706 				    IP_ADDR_LEN);
17707 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17708 				/* FALLTHRU */
17709 			case IPOPT_TS_TSONLY:
17710 				off = opt[IPOPT_OFFSET] - 1;
17711 				/* Compute # of milliseconds since midnight */
17712 				gethrestime(&now);
17713 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17714 				    now.tv_nsec / (NANOSEC / MILLISEC);
17715 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17716 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17717 				break;
17718 			}
17719 			break;
17720 		}
17721 	}
17722 	return (B_TRUE);
17723 
17724 bad_src_route:
17725 	q = WR(q);
17726 	if (q->q_next != NULL)
17727 		ill = q->q_ptr;
17728 	else
17729 		ill = NULL;
17730 
17731 	/* make sure we clear any indication of a hardware checksum */
17732 	DB_CKSUMFLAGS(mp) = 0;
17733 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
17734 	if (zoneid == ALL_ZONES)
17735 		freemsg(mp);
17736 	else
17737 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17738 	return (B_FALSE);
17739 
17740 }
17741 
17742 /*
17743  * Process IP options in an inbound packet.  If an option affects the
17744  * effective destination address, return the next hop address via dstp.
17745  * Returns -1 if something fails in which case an ICMP error has been sent
17746  * and mp freed.
17747  */
17748 static int
17749 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
17750     ip_stack_t *ipst)
17751 {
17752 	ipoptp_t	opts;
17753 	uchar_t		*opt;
17754 	uint8_t		optval;
17755 	uint8_t		optlen;
17756 	ipaddr_t	dst;
17757 	intptr_t	code = 0;
17758 	ire_t		*ire = NULL;
17759 	zoneid_t	zoneid;
17760 	ill_t		*ill;
17761 
17762 	ip2dbg(("ip_rput_options\n"));
17763 	dst = ipha->ipha_dst;
17764 	for (optval = ipoptp_first(&opts, ipha);
17765 	    optval != IPOPT_EOL;
17766 	    optval = ipoptp_next(&opts)) {
17767 		opt = opts.ipoptp_cur;
17768 		optlen = opts.ipoptp_len;
17769 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17770 		    optval, optlen));
17771 		/*
17772 		 * Note: we need to verify the checksum before we
17773 		 * modify anything thus this routine only extracts the next
17774 		 * hop dst from any source route.
17775 		 */
17776 		switch (optval) {
17777 			uint32_t off;
17778 		case IPOPT_SSRR:
17779 		case IPOPT_LSRR:
17780 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17781 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17782 			if (ire == NULL) {
17783 				if (optval == IPOPT_SSRR) {
17784 					ip1dbg(("ip_rput_options: not next"
17785 					    " strict source route 0x%x\n",
17786 					    ntohl(dst)));
17787 					code = (char *)&ipha->ipha_dst -
17788 					    (char *)ipha;
17789 					goto param_prob; /* RouterReq's */
17790 				}
17791 				ip2dbg(("ip_rput_options: "
17792 				    "not next source route 0x%x\n",
17793 				    ntohl(dst)));
17794 				break;
17795 			}
17796 			ire_refrele(ire);
17797 
17798 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17799 				ip1dbg((
17800 				    "ip_rput_options: bad option offset\n"));
17801 				code = (char *)&opt[IPOPT_OLEN] -
17802 				    (char *)ipha;
17803 				goto param_prob;
17804 			}
17805 			off = opt[IPOPT_OFFSET];
17806 			off--;
17807 		redo_srr:
17808 			if (optlen < IP_ADDR_LEN ||
17809 			    off > optlen - IP_ADDR_LEN) {
17810 				/* End of source route */
17811 				ip1dbg(("ip_rput_options: end of SR\n"));
17812 				break;
17813 			}
17814 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17815 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
17816 			    ntohl(dst)));
17817 
17818 			/*
17819 			 * Check if our address is present more than
17820 			 * once as consecutive hops in source route.
17821 			 * XXX verify per-interface ip_forwarding
17822 			 * for source route?
17823 			 */
17824 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17825 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17826 
17827 			if (ire != NULL) {
17828 				ire_refrele(ire);
17829 				off += IP_ADDR_LEN;
17830 				goto redo_srr;
17831 			}
17832 
17833 			if (dst == htonl(INADDR_LOOPBACK)) {
17834 				ip1dbg(("ip_rput_options: loopback addr in "
17835 				    "source route!\n"));
17836 				goto bad_src_route;
17837 			}
17838 			/*
17839 			 * For strict: verify that dst is directly
17840 			 * reachable.
17841 			 */
17842 			if (optval == IPOPT_SSRR) {
17843 				ire = ire_ftable_lookup(dst, 0, 0,
17844 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
17845 				    MBLK_GETLABEL(mp),
17846 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
17847 				if (ire == NULL) {
17848 					ip1dbg(("ip_rput_options: SSRR not "
17849 					    "directly reachable: 0x%x\n",
17850 					    ntohl(dst)));
17851 					goto bad_src_route;
17852 				}
17853 				ire_refrele(ire);
17854 			}
17855 			/*
17856 			 * Defer update of the offset and the record route
17857 			 * until the packet is forwarded.
17858 			 */
17859 			break;
17860 		case IPOPT_RR:
17861 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17862 				ip1dbg((
17863 				    "ip_rput_options: bad option offset\n"));
17864 				code = (char *)&opt[IPOPT_OLEN] -
17865 				    (char *)ipha;
17866 				goto param_prob;
17867 			}
17868 			break;
17869 		case IPOPT_TS:
17870 			/*
17871 			 * Verify that length >= 5 and that there is either
17872 			 * room for another timestamp or that the overflow
17873 			 * counter is not maxed out.
17874 			 */
17875 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
17876 			if (optlen < IPOPT_MINLEN_IT) {
17877 				goto param_prob;
17878 			}
17879 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17880 				ip1dbg((
17881 				    "ip_rput_options: bad option offset\n"));
17882 				code = (char *)&opt[IPOPT_OFFSET] -
17883 				    (char *)ipha;
17884 				goto param_prob;
17885 			}
17886 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17887 			case IPOPT_TS_TSONLY:
17888 				off = IPOPT_TS_TIMELEN;
17889 				break;
17890 			case IPOPT_TS_TSANDADDR:
17891 			case IPOPT_TS_PRESPEC:
17892 			case IPOPT_TS_PRESPEC_RFC791:
17893 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17894 				break;
17895 			default:
17896 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
17897 				    (char *)ipha;
17898 				goto param_prob;
17899 			}
17900 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
17901 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
17902 				/*
17903 				 * No room and the overflow counter is 15
17904 				 * already.
17905 				 */
17906 				goto param_prob;
17907 			}
17908 			break;
17909 		}
17910 	}
17911 
17912 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
17913 		*dstp = dst;
17914 		return (0);
17915 	}
17916 
17917 	ip1dbg(("ip_rput_options: error processing IP options."));
17918 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
17919 
17920 param_prob:
17921 	q = WR(q);
17922 	if (q->q_next != NULL)
17923 		ill = q->q_ptr;
17924 	else
17925 		ill = NULL;
17926 
17927 	/* make sure we clear any indication of a hardware checksum */
17928 	DB_CKSUMFLAGS(mp) = 0;
17929 	/* Don't know whether this is for non-global or global/forwarding */
17930 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
17931 	if (zoneid == ALL_ZONES)
17932 		freemsg(mp);
17933 	else
17934 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
17935 	return (-1);
17936 
17937 bad_src_route:
17938 	q = WR(q);
17939 	if (q->q_next != NULL)
17940 		ill = q->q_ptr;
17941 	else
17942 		ill = NULL;
17943 
17944 	/* make sure we clear any indication of a hardware checksum */
17945 	DB_CKSUMFLAGS(mp) = 0;
17946 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
17947 	if (zoneid == ALL_ZONES)
17948 		freemsg(mp);
17949 	else
17950 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17951 	return (-1);
17952 }
17953 
17954 /*
17955  * IP & ICMP info in >=14 msg's ...
17956  *  - ip fixed part (mib2_ip_t)
17957  *  - icmp fixed part (mib2_icmp_t)
17958  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
17959  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
17960  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
17961  *  - ipRouteAttributeTable (ip 102)	labeled routes
17962  *  - ip multicast membership (ip_member_t)
17963  *  - ip multicast source filtering (ip_grpsrc_t)
17964  *  - igmp fixed part (struct igmpstat)
17965  *  - multicast routing stats (struct mrtstat)
17966  *  - multicast routing vifs (array of struct vifctl)
17967  *  - multicast routing routes (array of struct mfcctl)
17968  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
17969  *					One per ill plus one generic
17970  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
17971  *					One per ill plus one generic
17972  *  - ipv6RouteEntry			all IPv6 IREs
17973  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
17974  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
17975  *  - ipv6AddrEntry			all IPv6 ipifs
17976  *  - ipv6 multicast membership (ipv6_member_t)
17977  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
17978  *
17979  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
17980  *
17981  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
17982  * already filled in by the caller.
17983  * Return value of 0 indicates that no messages were sent and caller
17984  * should free mpctl.
17985  */
17986 int
17987 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level)
17988 {
17989 	ip_stack_t *ipst;
17990 	sctp_stack_t *sctps;
17991 
17992 	if (q->q_next != NULL) {
17993 		ipst = ILLQ_TO_IPST(q);
17994 	} else {
17995 		ipst = CONNQ_TO_IPST(q);
17996 	}
17997 	ASSERT(ipst != NULL);
17998 	sctps = ipst->ips_netstack->netstack_sctp;
17999 
18000 	if (mpctl == NULL || mpctl->b_cont == NULL) {
18001 		return (0);
18002 	}
18003 
18004 	/*
18005 	 * For the purposes of the (broken) packet shell use
18006 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
18007 	 * to make TCP and UDP appear first in the list of mib items.
18008 	 * TBD: We could expand this and use it in netstat so that
18009 	 * the kernel doesn't have to produce large tables (connections,
18010 	 * routes, etc) when netstat only wants the statistics or a particular
18011 	 * table.
18012 	 */
18013 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
18014 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
18015 			return (1);
18016 		}
18017 	}
18018 
18019 	if (level != MIB2_TCP) {
18020 		if ((mpctl = udp_snmp_get(q, mpctl)) == NULL) {
18021 			return (1);
18022 		}
18023 	}
18024 
18025 	if (level != MIB2_UDP) {
18026 		if ((mpctl = tcp_snmp_get(q, mpctl)) == NULL) {
18027 			return (1);
18028 		}
18029 	}
18030 
18031 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
18032 	    ipst)) == NULL) {
18033 		return (1);
18034 	}
18035 
18036 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
18037 		return (1);
18038 	}
18039 
18040 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
18041 		return (1);
18042 	}
18043 
18044 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
18045 		return (1);
18046 	}
18047 
18048 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
18049 		return (1);
18050 	}
18051 
18052 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
18053 		return (1);
18054 	}
18055 
18056 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
18057 		return (1);
18058 	}
18059 
18060 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
18061 		return (1);
18062 	}
18063 
18064 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
18065 		return (1);
18066 	}
18067 
18068 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18069 		return (1);
18070 	}
18071 
18072 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18073 		return (1);
18074 	}
18075 
18076 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18077 		return (1);
18078 	}
18079 
18080 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18081 		return (1);
18082 	}
18083 
18084 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18085 		return (1);
18086 	}
18087 
18088 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, ipst)) == NULL) {
18089 		return (1);
18090 	}
18091 
18092 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, ipst);
18093 	if (mpctl == NULL) {
18094 		return (1);
18095 	}
18096 
18097 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18098 		return (1);
18099 	}
18100 	freemsg(mpctl);
18101 	return (1);
18102 }
18103 
18104 
18105 /* Get global (legacy) IPv4 statistics */
18106 static mblk_t *
18107 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18108     ip_stack_t *ipst)
18109 {
18110 	mib2_ip_t		old_ip_mib;
18111 	struct opthdr		*optp;
18112 	mblk_t			*mp2ctl;
18113 
18114 	/*
18115 	 * make a copy of the original message
18116 	 */
18117 	mp2ctl = copymsg(mpctl);
18118 
18119 	/* fixed length IP structure... */
18120 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18121 	optp->level = MIB2_IP;
18122 	optp->name = 0;
18123 	SET_MIB(old_ip_mib.ipForwarding,
18124 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18125 	SET_MIB(old_ip_mib.ipDefaultTTL,
18126 	    (uint32_t)ipst->ips_ip_def_ttl);
18127 	SET_MIB(old_ip_mib.ipReasmTimeout,
18128 	    ipst->ips_ip_g_frag_timeout);
18129 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18130 	    sizeof (mib2_ipAddrEntry_t));
18131 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18132 	    sizeof (mib2_ipRouteEntry_t));
18133 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18134 	    sizeof (mib2_ipNetToMediaEntry_t));
18135 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18136 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18137 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18138 	    sizeof (mib2_ipAttributeEntry_t));
18139 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18140 
18141 	/*
18142 	 * Grab the statistics from the new IP MIB
18143 	 */
18144 	SET_MIB(old_ip_mib.ipInReceives,
18145 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18146 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18147 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18148 	SET_MIB(old_ip_mib.ipForwDatagrams,
18149 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18150 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18151 	    ipmib->ipIfStatsInUnknownProtos);
18152 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18153 	SET_MIB(old_ip_mib.ipInDelivers,
18154 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18155 	SET_MIB(old_ip_mib.ipOutRequests,
18156 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18157 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18158 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18159 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18160 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18161 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18162 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18163 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18164 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18165 
18166 	/* ipRoutingDiscards is not being used */
18167 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18168 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18169 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18170 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18171 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18172 	    ipmib->ipIfStatsReasmDuplicates);
18173 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18174 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18175 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18176 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18177 	SET_MIB(old_ip_mib.rawipInOverflows,
18178 	    ipmib->rawipIfStatsInOverflows);
18179 
18180 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18181 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18182 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18183 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18184 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18185 	    ipmib->ipIfStatsOutSwitchIPVersion);
18186 
18187 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18188 	    (int)sizeof (old_ip_mib))) {
18189 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18190 		    (uint_t)sizeof (old_ip_mib)));
18191 	}
18192 
18193 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18194 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18195 	    (int)optp->level, (int)optp->name, (int)optp->len));
18196 	qreply(q, mpctl);
18197 	return (mp2ctl);
18198 }
18199 
18200 /* Per interface IPv4 statistics */
18201 static mblk_t *
18202 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18203 {
18204 	struct opthdr		*optp;
18205 	mblk_t			*mp2ctl;
18206 	ill_t			*ill;
18207 	ill_walk_context_t	ctx;
18208 	mblk_t			*mp_tail = NULL;
18209 	mib2_ipIfStatsEntry_t	global_ip_mib;
18210 
18211 	/*
18212 	 * Make a copy of the original message
18213 	 */
18214 	mp2ctl = copymsg(mpctl);
18215 
18216 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18217 	optp->level = MIB2_IP;
18218 	optp->name = MIB2_IP_TRAFFIC_STATS;
18219 	/* Include "unknown interface" ip_mib */
18220 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18221 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18222 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18223 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18224 	    (ipst->ips_ip_g_forward ? 1 : 2));
18225 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18226 	    (uint32_t)ipst->ips_ip_def_ttl);
18227 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18228 	    sizeof (mib2_ipIfStatsEntry_t));
18229 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18230 	    sizeof (mib2_ipAddrEntry_t));
18231 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18232 	    sizeof (mib2_ipRouteEntry_t));
18233 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18234 	    sizeof (mib2_ipNetToMediaEntry_t));
18235 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18236 	    sizeof (ip_member_t));
18237 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18238 	    sizeof (ip_grpsrc_t));
18239 
18240 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18241 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18242 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18243 		    "failed to allocate %u bytes\n",
18244 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18245 	}
18246 
18247 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18248 
18249 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18250 	ill = ILL_START_WALK_V4(&ctx, ipst);
18251 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18252 		ill->ill_ip_mib->ipIfStatsIfIndex =
18253 		    ill->ill_phyint->phyint_ifindex;
18254 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18255 		    (ipst->ips_ip_g_forward ? 1 : 2));
18256 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18257 		    (uint32_t)ipst->ips_ip_def_ttl);
18258 
18259 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18260 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18261 		    (char *)ill->ill_ip_mib,
18262 		    (int)sizeof (*ill->ill_ip_mib))) {
18263 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18264 			    "failed to allocate %u bytes\n",
18265 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18266 		}
18267 	}
18268 	rw_exit(&ipst->ips_ill_g_lock);
18269 
18270 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18271 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18272 	    "level %d, name %d, len %d\n",
18273 	    (int)optp->level, (int)optp->name, (int)optp->len));
18274 	qreply(q, mpctl);
18275 
18276 	if (mp2ctl == NULL)
18277 		return (NULL);
18278 
18279 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18280 }
18281 
18282 /* Global IPv4 ICMP statistics */
18283 static mblk_t *
18284 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18285 {
18286 	struct opthdr		*optp;
18287 	mblk_t			*mp2ctl;
18288 
18289 	/*
18290 	 * Make a copy of the original message
18291 	 */
18292 	mp2ctl = copymsg(mpctl);
18293 
18294 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18295 	optp->level = MIB2_ICMP;
18296 	optp->name = 0;
18297 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18298 	    (int)sizeof (ipst->ips_icmp_mib))) {
18299 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18300 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18301 	}
18302 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18303 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18304 	    (int)optp->level, (int)optp->name, (int)optp->len));
18305 	qreply(q, mpctl);
18306 	return (mp2ctl);
18307 }
18308 
18309 /* Global IPv4 IGMP statistics */
18310 static mblk_t *
18311 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18312 {
18313 	struct opthdr		*optp;
18314 	mblk_t			*mp2ctl;
18315 
18316 	/*
18317 	 * make a copy of the original message
18318 	 */
18319 	mp2ctl = copymsg(mpctl);
18320 
18321 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18322 	optp->level = EXPER_IGMP;
18323 	optp->name = 0;
18324 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18325 	    (int)sizeof (ipst->ips_igmpstat))) {
18326 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18327 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18328 	}
18329 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18330 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18331 	    (int)optp->level, (int)optp->name, (int)optp->len));
18332 	qreply(q, mpctl);
18333 	return (mp2ctl);
18334 }
18335 
18336 /* Global IPv4 Multicast Routing statistics */
18337 static mblk_t *
18338 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18339 {
18340 	struct opthdr		*optp;
18341 	mblk_t			*mp2ctl;
18342 
18343 	/*
18344 	 * make a copy of the original message
18345 	 */
18346 	mp2ctl = copymsg(mpctl);
18347 
18348 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18349 	optp->level = EXPER_DVMRP;
18350 	optp->name = 0;
18351 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18352 		ip0dbg(("ip_mroute_stats: failed\n"));
18353 	}
18354 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18355 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18356 	    (int)optp->level, (int)optp->name, (int)optp->len));
18357 	qreply(q, mpctl);
18358 	return (mp2ctl);
18359 }
18360 
18361 /* IPv4 address information */
18362 static mblk_t *
18363 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18364 {
18365 	struct opthdr		*optp;
18366 	mblk_t			*mp2ctl;
18367 	mblk_t			*mp_tail = NULL;
18368 	ill_t			*ill;
18369 	ipif_t			*ipif;
18370 	uint_t			bitval;
18371 	mib2_ipAddrEntry_t	mae;
18372 	zoneid_t		zoneid;
18373 	ill_walk_context_t ctx;
18374 
18375 	/*
18376 	 * make a copy of the original message
18377 	 */
18378 	mp2ctl = copymsg(mpctl);
18379 
18380 	/* ipAddrEntryTable */
18381 
18382 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18383 	optp->level = MIB2_IP;
18384 	optp->name = MIB2_IP_ADDR;
18385 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18386 
18387 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18388 	ill = ILL_START_WALK_V4(&ctx, ipst);
18389 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18390 		for (ipif = ill->ill_ipif; ipif != NULL;
18391 		    ipif = ipif->ipif_next) {
18392 			if (ipif->ipif_zoneid != zoneid &&
18393 			    ipif->ipif_zoneid != ALL_ZONES)
18394 				continue;
18395 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18396 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18397 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18398 
18399 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
18400 			    OCTET_LENGTH);
18401 			mae.ipAdEntIfIndex.o_length =
18402 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18403 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18404 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18405 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18406 			mae.ipAdEntInfo.ae_subnet_len =
18407 			    ip_mask_to_plen(ipif->ipif_net_mask);
18408 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18409 			for (bitval = 1;
18410 			    bitval &&
18411 			    !(bitval & ipif->ipif_brd_addr);
18412 			    bitval <<= 1)
18413 				noop;
18414 			mae.ipAdEntBcastAddr = bitval;
18415 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18416 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18417 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18418 			mae.ipAdEntInfo.ae_broadcast_addr =
18419 			    ipif->ipif_brd_addr;
18420 			mae.ipAdEntInfo.ae_pp_dst_addr =
18421 			    ipif->ipif_pp_dst_addr;
18422 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18423 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18424 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18425 
18426 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18427 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18428 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18429 				    "allocate %u bytes\n",
18430 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18431 			}
18432 		}
18433 	}
18434 	rw_exit(&ipst->ips_ill_g_lock);
18435 
18436 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18437 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18438 	    (int)optp->level, (int)optp->name, (int)optp->len));
18439 	qreply(q, mpctl);
18440 	return (mp2ctl);
18441 }
18442 
18443 /* IPv6 address information */
18444 static mblk_t *
18445 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18446 {
18447 	struct opthdr		*optp;
18448 	mblk_t			*mp2ctl;
18449 	mblk_t			*mp_tail = NULL;
18450 	ill_t			*ill;
18451 	ipif_t			*ipif;
18452 	mib2_ipv6AddrEntry_t	mae6;
18453 	zoneid_t		zoneid;
18454 	ill_walk_context_t	ctx;
18455 
18456 	/*
18457 	 * make a copy of the original message
18458 	 */
18459 	mp2ctl = copymsg(mpctl);
18460 
18461 	/* ipv6AddrEntryTable */
18462 
18463 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18464 	optp->level = MIB2_IP6;
18465 	optp->name = MIB2_IP6_ADDR;
18466 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18467 
18468 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18469 	ill = ILL_START_WALK_V6(&ctx, ipst);
18470 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18471 		for (ipif = ill->ill_ipif; ipif != NULL;
18472 		    ipif = ipif->ipif_next) {
18473 			if (ipif->ipif_zoneid != zoneid &&
18474 			    ipif->ipif_zoneid != ALL_ZONES)
18475 				continue;
18476 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18477 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18478 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18479 
18480 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
18481 			    OCTET_LENGTH);
18482 			mae6.ipv6AddrIfIndex.o_length =
18483 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18484 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18485 			mae6.ipv6AddrPfxLength =
18486 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18487 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18488 			mae6.ipv6AddrInfo.ae_subnet_len =
18489 			    mae6.ipv6AddrPfxLength;
18490 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18491 
18492 			/* Type: stateless(1), stateful(2), unknown(3) */
18493 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18494 				mae6.ipv6AddrType = 1;
18495 			else
18496 				mae6.ipv6AddrType = 2;
18497 			/* Anycast: true(1), false(2) */
18498 			if (ipif->ipif_flags & IPIF_ANYCAST)
18499 				mae6.ipv6AddrAnycastFlag = 1;
18500 			else
18501 				mae6.ipv6AddrAnycastFlag = 2;
18502 
18503 			/*
18504 			 * Address status: preferred(1), deprecated(2),
18505 			 * invalid(3), inaccessible(4), unknown(5)
18506 			 */
18507 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18508 				mae6.ipv6AddrStatus = 3;
18509 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18510 				mae6.ipv6AddrStatus = 2;
18511 			else
18512 				mae6.ipv6AddrStatus = 1;
18513 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18514 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18515 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18516 			    ipif->ipif_v6pp_dst_addr;
18517 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18518 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18519 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18520 			mae6.ipv6AddrIdentifier = ill->ill_token;
18521 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18522 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18523 			mae6.ipv6AddrRetransmitTime =
18524 			    ill->ill_reachable_retrans_time;
18525 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18526 			    (char *)&mae6,
18527 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
18528 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18529 				    "allocate %u bytes\n",
18530 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18531 			}
18532 		}
18533 	}
18534 	rw_exit(&ipst->ips_ill_g_lock);
18535 
18536 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18537 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18538 	    (int)optp->level, (int)optp->name, (int)optp->len));
18539 	qreply(q, mpctl);
18540 	return (mp2ctl);
18541 }
18542 
18543 /* IPv4 multicast group membership. */
18544 static mblk_t *
18545 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18546 {
18547 	struct opthdr		*optp;
18548 	mblk_t			*mp2ctl;
18549 	ill_t			*ill;
18550 	ipif_t			*ipif;
18551 	ilm_t			*ilm;
18552 	ip_member_t		ipm;
18553 	mblk_t			*mp_tail = NULL;
18554 	ill_walk_context_t	ctx;
18555 	zoneid_t		zoneid;
18556 
18557 	/*
18558 	 * make a copy of the original message
18559 	 */
18560 	mp2ctl = copymsg(mpctl);
18561 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18562 
18563 	/* ipGroupMember table */
18564 	optp = (struct opthdr *)&mpctl->b_rptr[
18565 	    sizeof (struct T_optmgmt_ack)];
18566 	optp->level = MIB2_IP;
18567 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18568 
18569 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18570 	ill = ILL_START_WALK_V4(&ctx, ipst);
18571 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18572 		ILM_WALKER_HOLD(ill);
18573 		for (ipif = ill->ill_ipif; ipif != NULL;
18574 		    ipif = ipif->ipif_next) {
18575 			if (ipif->ipif_zoneid != zoneid &&
18576 			    ipif->ipif_zoneid != ALL_ZONES)
18577 				continue;	/* not this zone */
18578 			ipif_get_name(ipif, ipm.ipGroupMemberIfIndex.o_bytes,
18579 			    OCTET_LENGTH);
18580 			ipm.ipGroupMemberIfIndex.o_length =
18581 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18582 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18583 				ASSERT(ilm->ilm_ipif != NULL);
18584 				ASSERT(ilm->ilm_ill == NULL);
18585 				if (ilm->ilm_ipif != ipif)
18586 					continue;
18587 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18588 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18589 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18590 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18591 				    (char *)&ipm, (int)sizeof (ipm))) {
18592 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18593 					    "failed to allocate %u bytes\n",
18594 					    (uint_t)sizeof (ipm)));
18595 				}
18596 			}
18597 		}
18598 		ILM_WALKER_RELE(ill);
18599 	}
18600 	rw_exit(&ipst->ips_ill_g_lock);
18601 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18602 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18603 	    (int)optp->level, (int)optp->name, (int)optp->len));
18604 	qreply(q, mpctl);
18605 	return (mp2ctl);
18606 }
18607 
18608 /* IPv6 multicast group membership. */
18609 static mblk_t *
18610 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18611 {
18612 	struct opthdr		*optp;
18613 	mblk_t			*mp2ctl;
18614 	ill_t			*ill;
18615 	ilm_t			*ilm;
18616 	ipv6_member_t		ipm6;
18617 	mblk_t			*mp_tail = NULL;
18618 	ill_walk_context_t	ctx;
18619 	zoneid_t		zoneid;
18620 
18621 	/*
18622 	 * make a copy of the original message
18623 	 */
18624 	mp2ctl = copymsg(mpctl);
18625 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18626 
18627 	/* ip6GroupMember table */
18628 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18629 	optp->level = MIB2_IP6;
18630 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18631 
18632 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18633 	ill = ILL_START_WALK_V6(&ctx, ipst);
18634 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18635 		ILM_WALKER_HOLD(ill);
18636 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18637 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18638 			ASSERT(ilm->ilm_ipif == NULL);
18639 			ASSERT(ilm->ilm_ill != NULL);
18640 			if (ilm->ilm_zoneid != zoneid)
18641 				continue;	/* not this zone */
18642 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18643 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18644 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18645 			if (!snmp_append_data2(mpctl->b_cont,
18646 			    &mp_tail,
18647 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18648 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18649 				    "failed to allocate %u bytes\n",
18650 				    (uint_t)sizeof (ipm6)));
18651 			}
18652 		}
18653 		ILM_WALKER_RELE(ill);
18654 	}
18655 	rw_exit(&ipst->ips_ill_g_lock);
18656 
18657 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18658 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18659 	    (int)optp->level, (int)optp->name, (int)optp->len));
18660 	qreply(q, mpctl);
18661 	return (mp2ctl);
18662 }
18663 
18664 /* IP multicast filtered sources */
18665 static mblk_t *
18666 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18667 {
18668 	struct opthdr		*optp;
18669 	mblk_t			*mp2ctl;
18670 	ill_t			*ill;
18671 	ipif_t			*ipif;
18672 	ilm_t			*ilm;
18673 	ip_grpsrc_t		ips;
18674 	mblk_t			*mp_tail = NULL;
18675 	ill_walk_context_t	ctx;
18676 	zoneid_t		zoneid;
18677 	int			i;
18678 	slist_t			*sl;
18679 
18680 	/*
18681 	 * make a copy of the original message
18682 	 */
18683 	mp2ctl = copymsg(mpctl);
18684 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18685 
18686 	/* ipGroupSource table */
18687 	optp = (struct opthdr *)&mpctl->b_rptr[
18688 	    sizeof (struct T_optmgmt_ack)];
18689 	optp->level = MIB2_IP;
18690 	optp->name = EXPER_IP_GROUP_SOURCES;
18691 
18692 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18693 	ill = ILL_START_WALK_V4(&ctx, ipst);
18694 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18695 		ILM_WALKER_HOLD(ill);
18696 		for (ipif = ill->ill_ipif; ipif != NULL;
18697 		    ipif = ipif->ipif_next) {
18698 			if (ipif->ipif_zoneid != zoneid)
18699 				continue;	/* not this zone */
18700 			ipif_get_name(ipif, ips.ipGroupSourceIfIndex.o_bytes,
18701 			    OCTET_LENGTH);
18702 			ips.ipGroupSourceIfIndex.o_length =
18703 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18704 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18705 				ASSERT(ilm->ilm_ipif != NULL);
18706 				ASSERT(ilm->ilm_ill == NULL);
18707 				sl = ilm->ilm_filter;
18708 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18709 					continue;
18710 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18711 				for (i = 0; i < sl->sl_numsrc; i++) {
18712 					if (!IN6_IS_ADDR_V4MAPPED(
18713 					    &sl->sl_addr[i]))
18714 						continue;
18715 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18716 					    ips.ipGroupSourceAddress);
18717 					if (snmp_append_data2(mpctl->b_cont,
18718 					    &mp_tail, (char *)&ips,
18719 					    (int)sizeof (ips)) == 0) {
18720 						ip1dbg(("ip_snmp_get_mib2_"
18721 						    "ip_group_src: failed to "
18722 						    "allocate %u bytes\n",
18723 						    (uint_t)sizeof (ips)));
18724 					}
18725 				}
18726 			}
18727 		}
18728 		ILM_WALKER_RELE(ill);
18729 	}
18730 	rw_exit(&ipst->ips_ill_g_lock);
18731 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18732 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18733 	    (int)optp->level, (int)optp->name, (int)optp->len));
18734 	qreply(q, mpctl);
18735 	return (mp2ctl);
18736 }
18737 
18738 /* IPv6 multicast filtered sources. */
18739 static mblk_t *
18740 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18741 {
18742 	struct opthdr		*optp;
18743 	mblk_t			*mp2ctl;
18744 	ill_t			*ill;
18745 	ilm_t			*ilm;
18746 	ipv6_grpsrc_t		ips6;
18747 	mblk_t			*mp_tail = NULL;
18748 	ill_walk_context_t	ctx;
18749 	zoneid_t		zoneid;
18750 	int			i;
18751 	slist_t			*sl;
18752 
18753 	/*
18754 	 * make a copy of the original message
18755 	 */
18756 	mp2ctl = copymsg(mpctl);
18757 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18758 
18759 	/* ip6GroupMember table */
18760 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18761 	optp->level = MIB2_IP6;
18762 	optp->name = EXPER_IP6_GROUP_SOURCES;
18763 
18764 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18765 	ill = ILL_START_WALK_V6(&ctx, ipst);
18766 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18767 		ILM_WALKER_HOLD(ill);
18768 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18769 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18770 			ASSERT(ilm->ilm_ipif == NULL);
18771 			ASSERT(ilm->ilm_ill != NULL);
18772 			sl = ilm->ilm_filter;
18773 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
18774 				continue;
18775 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
18776 			for (i = 0; i < sl->sl_numsrc; i++) {
18777 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
18778 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18779 				    (char *)&ips6, (int)sizeof (ips6))) {
18780 					ip1dbg(("ip_snmp_get_mib2_ip6_"
18781 					    "group_src: failed to allocate "
18782 					    "%u bytes\n",
18783 					    (uint_t)sizeof (ips6)));
18784 				}
18785 			}
18786 		}
18787 		ILM_WALKER_RELE(ill);
18788 	}
18789 	rw_exit(&ipst->ips_ill_g_lock);
18790 
18791 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18792 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18793 	    (int)optp->level, (int)optp->name, (int)optp->len));
18794 	qreply(q, mpctl);
18795 	return (mp2ctl);
18796 }
18797 
18798 /* Multicast routing virtual interface table. */
18799 static mblk_t *
18800 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18801 {
18802 	struct opthdr		*optp;
18803 	mblk_t			*mp2ctl;
18804 
18805 	/*
18806 	 * make a copy of the original message
18807 	 */
18808 	mp2ctl = copymsg(mpctl);
18809 
18810 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18811 	optp->level = EXPER_DVMRP;
18812 	optp->name = EXPER_DVMRP_VIF;
18813 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
18814 		ip0dbg(("ip_mroute_vif: failed\n"));
18815 	}
18816 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18817 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
18818 	    (int)optp->level, (int)optp->name, (int)optp->len));
18819 	qreply(q, mpctl);
18820 	return (mp2ctl);
18821 }
18822 
18823 /* Multicast routing table. */
18824 static mblk_t *
18825 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18826 {
18827 	struct opthdr		*optp;
18828 	mblk_t			*mp2ctl;
18829 
18830 	/*
18831 	 * make a copy of the original message
18832 	 */
18833 	mp2ctl = copymsg(mpctl);
18834 
18835 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18836 	optp->level = EXPER_DVMRP;
18837 	optp->name = EXPER_DVMRP_MRT;
18838 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
18839 		ip0dbg(("ip_mroute_mrt: failed\n"));
18840 	}
18841 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18842 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
18843 	    (int)optp->level, (int)optp->name, (int)optp->len));
18844 	qreply(q, mpctl);
18845 	return (mp2ctl);
18846 }
18847 
18848 /*
18849  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
18850  * in one IRE walk.
18851  */
18852 static mblk_t *
18853 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18854 {
18855 	struct opthdr	*optp;
18856 	mblk_t		*mp2ctl;	/* Returned */
18857 	mblk_t		*mp3ctl;	/* nettomedia */
18858 	mblk_t		*mp4ctl;	/* routeattrs */
18859 	iproutedata_t	ird;
18860 	zoneid_t	zoneid;
18861 
18862 	/*
18863 	 * make copies of the original message
18864 	 *	- mp2ctl is returned unchanged to the caller for his use
18865 	 *	- mpctl is sent upstream as ipRouteEntryTable
18866 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
18867 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
18868 	 */
18869 	mp2ctl = copymsg(mpctl);
18870 	mp3ctl = copymsg(mpctl);
18871 	mp4ctl = copymsg(mpctl);
18872 	if (mp3ctl == NULL || mp4ctl == NULL) {
18873 		freemsg(mp4ctl);
18874 		freemsg(mp3ctl);
18875 		freemsg(mp2ctl);
18876 		freemsg(mpctl);
18877 		return (NULL);
18878 	}
18879 
18880 	bzero(&ird, sizeof (ird));
18881 
18882 	ird.ird_route.lp_head = mpctl->b_cont;
18883 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18884 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18885 
18886 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18887 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
18888 
18889 	/* ipRouteEntryTable in mpctl */
18890 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18891 	optp->level = MIB2_IP;
18892 	optp->name = MIB2_IP_ROUTE;
18893 	optp->len = msgdsize(ird.ird_route.lp_head);
18894 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18895 	    (int)optp->level, (int)optp->name, (int)optp->len));
18896 	qreply(q, mpctl);
18897 
18898 	/* ipNetToMediaEntryTable in mp3ctl */
18899 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18900 	optp->level = MIB2_IP;
18901 	optp->name = MIB2_IP_MEDIA;
18902 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18903 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18904 	    (int)optp->level, (int)optp->name, (int)optp->len));
18905 	qreply(q, mp3ctl);
18906 
18907 	/* ipRouteAttributeTable in mp4ctl */
18908 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18909 	optp->level = MIB2_IP;
18910 	optp->name = EXPER_IP_RTATTR;
18911 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18912 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18913 	    (int)optp->level, (int)optp->name, (int)optp->len));
18914 	if (optp->len == 0)
18915 		freemsg(mp4ctl);
18916 	else
18917 		qreply(q, mp4ctl);
18918 
18919 	return (mp2ctl);
18920 }
18921 
18922 /*
18923  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
18924  * ipv6NetToMediaEntryTable in an NDP walk.
18925  */
18926 static mblk_t *
18927 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18928 {
18929 	struct opthdr	*optp;
18930 	mblk_t		*mp2ctl;	/* Returned */
18931 	mblk_t		*mp3ctl;	/* nettomedia */
18932 	mblk_t		*mp4ctl;	/* routeattrs */
18933 	iproutedata_t	ird;
18934 	zoneid_t	zoneid;
18935 
18936 	/*
18937 	 * make copies of the original message
18938 	 *	- mp2ctl is returned unchanged to the caller for his use
18939 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
18940 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
18941 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
18942 	 */
18943 	mp2ctl = copymsg(mpctl);
18944 	mp3ctl = copymsg(mpctl);
18945 	mp4ctl = copymsg(mpctl);
18946 	if (mp3ctl == NULL || mp4ctl == NULL) {
18947 		freemsg(mp4ctl);
18948 		freemsg(mp3ctl);
18949 		freemsg(mp2ctl);
18950 		freemsg(mpctl);
18951 		return (NULL);
18952 	}
18953 
18954 	bzero(&ird, sizeof (ird));
18955 
18956 	ird.ird_route.lp_head = mpctl->b_cont;
18957 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18958 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18959 
18960 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18961 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
18962 
18963 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18964 	optp->level = MIB2_IP6;
18965 	optp->name = MIB2_IP6_ROUTE;
18966 	optp->len = msgdsize(ird.ird_route.lp_head);
18967 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18968 	    (int)optp->level, (int)optp->name, (int)optp->len));
18969 	qreply(q, mpctl);
18970 
18971 	/* ipv6NetToMediaEntryTable in mp3ctl */
18972 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
18973 
18974 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18975 	optp->level = MIB2_IP6;
18976 	optp->name = MIB2_IP6_MEDIA;
18977 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18978 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18979 	    (int)optp->level, (int)optp->name, (int)optp->len));
18980 	qreply(q, mp3ctl);
18981 
18982 	/* ipv6RouteAttributeTable in mp4ctl */
18983 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18984 	optp->level = MIB2_IP6;
18985 	optp->name = EXPER_IP_RTATTR;
18986 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18987 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18988 	    (int)optp->level, (int)optp->name, (int)optp->len));
18989 	if (optp->len == 0)
18990 		freemsg(mp4ctl);
18991 	else
18992 		qreply(q, mp4ctl);
18993 
18994 	return (mp2ctl);
18995 }
18996 
18997 /*
18998  * IPv6 mib: One per ill
18999  */
19000 static mblk_t *
19001 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19002 {
19003 	struct opthdr		*optp;
19004 	mblk_t			*mp2ctl;
19005 	ill_t			*ill;
19006 	ill_walk_context_t	ctx;
19007 	mblk_t			*mp_tail = NULL;
19008 
19009 	/*
19010 	 * Make a copy of the original message
19011 	 */
19012 	mp2ctl = copymsg(mpctl);
19013 
19014 	/* fixed length IPv6 structure ... */
19015 
19016 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19017 	optp->level = MIB2_IP6;
19018 	optp->name = 0;
19019 	/* Include "unknown interface" ip6_mib */
19020 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
19021 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
19022 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
19023 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
19024 	    ipst->ips_ipv6_forward ? 1 : 2);
19025 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
19026 	    ipst->ips_ipv6_def_hops);
19027 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
19028 	    sizeof (mib2_ipIfStatsEntry_t));
19029 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
19030 	    sizeof (mib2_ipv6AddrEntry_t));
19031 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
19032 	    sizeof (mib2_ipv6RouteEntry_t));
19033 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
19034 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19035 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
19036 	    sizeof (ipv6_member_t));
19037 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
19038 	    sizeof (ipv6_grpsrc_t));
19039 
19040 	/*
19041 	 * Synchronize 64- and 32-bit counters
19042 	 */
19043 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
19044 	    ipIfStatsHCInReceives);
19045 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
19046 	    ipIfStatsHCInDelivers);
19047 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
19048 	    ipIfStatsHCOutRequests);
19049 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
19050 	    ipIfStatsHCOutForwDatagrams);
19051 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
19052 	    ipIfStatsHCOutMcastPkts);
19053 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19054 	    ipIfStatsHCInMcastPkts);
19055 
19056 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19057 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19058 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19059 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19060 	}
19061 
19062 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19063 	ill = ILL_START_WALK_V6(&ctx, ipst);
19064 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19065 		ill->ill_ip_mib->ipIfStatsIfIndex =
19066 		    ill->ill_phyint->phyint_ifindex;
19067 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19068 		    ipst->ips_ipv6_forward ? 1 : 2);
19069 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19070 		    ill->ill_max_hops);
19071 
19072 		/*
19073 		 * Synchronize 64- and 32-bit counters
19074 		 */
19075 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19076 		    ipIfStatsHCInReceives);
19077 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19078 		    ipIfStatsHCInDelivers);
19079 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19080 		    ipIfStatsHCOutRequests);
19081 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19082 		    ipIfStatsHCOutForwDatagrams);
19083 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19084 		    ipIfStatsHCOutMcastPkts);
19085 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19086 		    ipIfStatsHCInMcastPkts);
19087 
19088 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19089 		    (char *)ill->ill_ip_mib,
19090 		    (int)sizeof (*ill->ill_ip_mib))) {
19091 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19092 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
19093 		}
19094 	}
19095 	rw_exit(&ipst->ips_ill_g_lock);
19096 
19097 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19098 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19099 	    (int)optp->level, (int)optp->name, (int)optp->len));
19100 	qreply(q, mpctl);
19101 	return (mp2ctl);
19102 }
19103 
19104 /*
19105  * ICMPv6 mib: One per ill
19106  */
19107 static mblk_t *
19108 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19109 {
19110 	struct opthdr		*optp;
19111 	mblk_t			*mp2ctl;
19112 	ill_t			*ill;
19113 	ill_walk_context_t	ctx;
19114 	mblk_t			*mp_tail = NULL;
19115 	/*
19116 	 * Make a copy of the original message
19117 	 */
19118 	mp2ctl = copymsg(mpctl);
19119 
19120 	/* fixed length ICMPv6 structure ... */
19121 
19122 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19123 	optp->level = MIB2_ICMP6;
19124 	optp->name = 0;
19125 	/* Include "unknown interface" icmp6_mib */
19126 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19127 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19128 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19129 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19130 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19131 	    (char *)&ipst->ips_icmp6_mib,
19132 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19133 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19134 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19135 	}
19136 
19137 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19138 	ill = ILL_START_WALK_V6(&ctx, ipst);
19139 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19140 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19141 		    ill->ill_phyint->phyint_ifindex;
19142 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19143 		    (char *)ill->ill_icmp6_mib,
19144 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19145 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19146 			    "%u bytes\n",
19147 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19148 		}
19149 	}
19150 	rw_exit(&ipst->ips_ill_g_lock);
19151 
19152 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19153 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19154 	    (int)optp->level, (int)optp->name, (int)optp->len));
19155 	qreply(q, mpctl);
19156 	return (mp2ctl);
19157 }
19158 
19159 /*
19160  * ire_walk routine to create both ipRouteEntryTable and
19161  * ipRouteAttributeTable in one IRE walk
19162  */
19163 static void
19164 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19165 {
19166 	ill_t				*ill;
19167 	ipif_t				*ipif;
19168 	mib2_ipRouteEntry_t		*re;
19169 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19170 	ipaddr_t			gw_addr;
19171 	tsol_ire_gw_secattr_t		*attrp;
19172 	tsol_gc_t			*gc = NULL;
19173 	tsol_gcgrp_t			*gcgrp = NULL;
19174 	uint_t				sacnt = 0;
19175 	int				i;
19176 
19177 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19178 
19179 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19180 		return;
19181 
19182 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19183 		mutex_enter(&attrp->igsa_lock);
19184 		if ((gc = attrp->igsa_gc) != NULL) {
19185 			gcgrp = gc->gc_grp;
19186 			ASSERT(gcgrp != NULL);
19187 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19188 			sacnt = 1;
19189 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19190 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19191 			gc = gcgrp->gcgrp_head;
19192 			sacnt = gcgrp->gcgrp_count;
19193 		}
19194 		mutex_exit(&attrp->igsa_lock);
19195 
19196 		/* do nothing if there's no gc to report */
19197 		if (gc == NULL) {
19198 			ASSERT(sacnt == 0);
19199 			if (gcgrp != NULL) {
19200 				/* we might as well drop the lock now */
19201 				rw_exit(&gcgrp->gcgrp_rwlock);
19202 				gcgrp = NULL;
19203 			}
19204 			attrp = NULL;
19205 		}
19206 
19207 		ASSERT(gc == NULL || (gcgrp != NULL &&
19208 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19209 	}
19210 	ASSERT(sacnt == 0 || gc != NULL);
19211 
19212 	if (sacnt != 0 &&
19213 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19214 		kmem_free(re, sizeof (*re));
19215 		rw_exit(&gcgrp->gcgrp_rwlock);
19216 		return;
19217 	}
19218 
19219 	/*
19220 	 * Return all IRE types for route table... let caller pick and choose
19221 	 */
19222 	re->ipRouteDest = ire->ire_addr;
19223 	ipif = ire->ire_ipif;
19224 	re->ipRouteIfIndex.o_length = 0;
19225 	if (ire->ire_type == IRE_CACHE) {
19226 		ill = (ill_t *)ire->ire_stq->q_ptr;
19227 		re->ipRouteIfIndex.o_length =
19228 		    ill->ill_name_length == 0 ? 0 :
19229 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19230 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19231 		    re->ipRouteIfIndex.o_length);
19232 	} else if (ipif != NULL) {
19233 		ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
19234 		re->ipRouteIfIndex.o_length =
19235 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19236 	}
19237 	re->ipRouteMetric1 = -1;
19238 	re->ipRouteMetric2 = -1;
19239 	re->ipRouteMetric3 = -1;
19240 	re->ipRouteMetric4 = -1;
19241 
19242 	gw_addr = ire->ire_gateway_addr;
19243 
19244 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19245 		re->ipRouteNextHop = ire->ire_src_addr;
19246 	else
19247 		re->ipRouteNextHop = gw_addr;
19248 	/* indirect(4), direct(3), or invalid(2) */
19249 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19250 		re->ipRouteType = 2;
19251 	else
19252 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19253 	re->ipRouteProto = -1;
19254 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19255 	re->ipRouteMask = ire->ire_mask;
19256 	re->ipRouteMetric5 = -1;
19257 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19258 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19259 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19260 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19261 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19262 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19263 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19264 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19265 
19266 	if (ire->ire_flags & RTF_DYNAMIC) {
19267 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19268 	} else {
19269 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19270 	}
19271 
19272 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19273 	    (char *)re, (int)sizeof (*re))) {
19274 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19275 		    (uint_t)sizeof (*re)));
19276 	}
19277 
19278 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19279 		iaeptr->iae_routeidx = ird->ird_idx;
19280 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19281 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19282 	}
19283 
19284 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19285 	    (char *)iae, sacnt * sizeof (*iae))) {
19286 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19287 		    (unsigned)(sacnt * sizeof (*iae))));
19288 	}
19289 
19290 	/* bump route index for next pass */
19291 	ird->ird_idx++;
19292 
19293 	kmem_free(re, sizeof (*re));
19294 	if (sacnt != 0)
19295 		kmem_free(iae, sacnt * sizeof (*iae));
19296 
19297 	if (gcgrp != NULL)
19298 		rw_exit(&gcgrp->gcgrp_rwlock);
19299 }
19300 
19301 /*
19302  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19303  */
19304 static void
19305 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19306 {
19307 	ill_t				*ill;
19308 	ipif_t				*ipif;
19309 	mib2_ipv6RouteEntry_t		*re;
19310 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19311 	in6_addr_t			gw_addr_v6;
19312 	tsol_ire_gw_secattr_t		*attrp;
19313 	tsol_gc_t			*gc = NULL;
19314 	tsol_gcgrp_t			*gcgrp = NULL;
19315 	uint_t				sacnt = 0;
19316 	int				i;
19317 
19318 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19319 
19320 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19321 		return;
19322 
19323 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19324 		mutex_enter(&attrp->igsa_lock);
19325 		if ((gc = attrp->igsa_gc) != NULL) {
19326 			gcgrp = gc->gc_grp;
19327 			ASSERT(gcgrp != NULL);
19328 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19329 			sacnt = 1;
19330 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19331 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19332 			gc = gcgrp->gcgrp_head;
19333 			sacnt = gcgrp->gcgrp_count;
19334 		}
19335 		mutex_exit(&attrp->igsa_lock);
19336 
19337 		/* do nothing if there's no gc to report */
19338 		if (gc == NULL) {
19339 			ASSERT(sacnt == 0);
19340 			if (gcgrp != NULL) {
19341 				/* we might as well drop the lock now */
19342 				rw_exit(&gcgrp->gcgrp_rwlock);
19343 				gcgrp = NULL;
19344 			}
19345 			attrp = NULL;
19346 		}
19347 
19348 		ASSERT(gc == NULL || (gcgrp != NULL &&
19349 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19350 	}
19351 	ASSERT(sacnt == 0 || gc != NULL);
19352 
19353 	if (sacnt != 0 &&
19354 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19355 		kmem_free(re, sizeof (*re));
19356 		rw_exit(&gcgrp->gcgrp_rwlock);
19357 		return;
19358 	}
19359 
19360 	/*
19361 	 * Return all IRE types for route table... let caller pick and choose
19362 	 */
19363 	re->ipv6RouteDest = ire->ire_addr_v6;
19364 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19365 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19366 	re->ipv6RouteIfIndex.o_length = 0;
19367 	ipif = ire->ire_ipif;
19368 	if (ire->ire_type == IRE_CACHE) {
19369 		ill = (ill_t *)ire->ire_stq->q_ptr;
19370 		re->ipv6RouteIfIndex.o_length =
19371 		    ill->ill_name_length == 0 ? 0 :
19372 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19373 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19374 		    re->ipv6RouteIfIndex.o_length);
19375 	} else if (ipif != NULL) {
19376 		ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
19377 		re->ipv6RouteIfIndex.o_length =
19378 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19379 	}
19380 
19381 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19382 
19383 	mutex_enter(&ire->ire_lock);
19384 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19385 	mutex_exit(&ire->ire_lock);
19386 
19387 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19388 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19389 	else
19390 		re->ipv6RouteNextHop = gw_addr_v6;
19391 
19392 	/* remote(4), local(3), or discard(2) */
19393 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19394 		re->ipv6RouteType = 2;
19395 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19396 		re->ipv6RouteType = 3;
19397 	else
19398 		re->ipv6RouteType = 4;
19399 
19400 	re->ipv6RouteProtocol	= -1;
19401 	re->ipv6RoutePolicy	= 0;
19402 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19403 	re->ipv6RouteNextHopRDI	= 0;
19404 	re->ipv6RouteWeight	= 0;
19405 	re->ipv6RouteMetric	= 0;
19406 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19407 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19408 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19409 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19410 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19411 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19412 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19413 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19414 
19415 	if (ire->ire_flags & RTF_DYNAMIC) {
19416 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19417 	} else {
19418 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19419 	}
19420 
19421 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19422 	    (char *)re, (int)sizeof (*re))) {
19423 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19424 		    (uint_t)sizeof (*re)));
19425 	}
19426 
19427 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19428 		iaeptr->iae_routeidx = ird->ird_idx;
19429 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19430 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19431 	}
19432 
19433 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19434 	    (char *)iae, sacnt * sizeof (*iae))) {
19435 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19436 		    (unsigned)(sacnt * sizeof (*iae))));
19437 	}
19438 
19439 	/* bump route index for next pass */
19440 	ird->ird_idx++;
19441 
19442 	kmem_free(re, sizeof (*re));
19443 	if (sacnt != 0)
19444 		kmem_free(iae, sacnt * sizeof (*iae));
19445 
19446 	if (gcgrp != NULL)
19447 		rw_exit(&gcgrp->gcgrp_rwlock);
19448 }
19449 
19450 /*
19451  * ndp_walk routine to create ipv6NetToMediaEntryTable
19452  */
19453 static int
19454 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19455 {
19456 	ill_t				*ill;
19457 	mib2_ipv6NetToMediaEntry_t	ntme;
19458 	dl_unitdata_req_t		*dl;
19459 
19460 	ill = nce->nce_ill;
19461 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19462 		return (0);
19463 
19464 	/*
19465 	 * Neighbor cache entry attached to IRE with on-link
19466 	 * destination.
19467 	 */
19468 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19469 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19470 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19471 	    (nce->nce_res_mp != NULL)) {
19472 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19473 		ntme.ipv6NetToMediaPhysAddress.o_length =
19474 		    dl->dl_dest_addr_length;
19475 	} else {
19476 		ntme.ipv6NetToMediaPhysAddress.o_length =
19477 		    ill->ill_phys_addr_length;
19478 	}
19479 	if (nce->nce_res_mp != NULL) {
19480 		bcopy((char *)nce->nce_res_mp->b_rptr +
19481 		    NCE_LL_ADDR_OFFSET(ill),
19482 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19483 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19484 	} else {
19485 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19486 		    ill->ill_phys_addr_length);
19487 	}
19488 	/*
19489 	 * Note: Returns ND_* states. Should be:
19490 	 * reachable(1), stale(2), delay(3), probe(4),
19491 	 * invalid(5), unknown(6)
19492 	 */
19493 	ntme.ipv6NetToMediaState = nce->nce_state;
19494 	ntme.ipv6NetToMediaLastUpdated = 0;
19495 
19496 	/* other(1), dynamic(2), static(3), local(4) */
19497 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19498 		ntme.ipv6NetToMediaType = 4;
19499 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19500 		ntme.ipv6NetToMediaType = 1;
19501 	} else {
19502 		ntme.ipv6NetToMediaType = 2;
19503 	}
19504 
19505 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19506 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19507 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19508 		    (uint_t)sizeof (ntme)));
19509 	}
19510 	return (0);
19511 }
19512 
19513 /*
19514  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19515  */
19516 /* ARGSUSED */
19517 int
19518 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19519 {
19520 	switch (level) {
19521 	case MIB2_IP:
19522 	case MIB2_ICMP:
19523 		switch (name) {
19524 		default:
19525 			break;
19526 		}
19527 		return (1);
19528 	default:
19529 		return (1);
19530 	}
19531 }
19532 
19533 /*
19534  * When there exists both a 64- and 32-bit counter of a particular type
19535  * (i.e., InReceives), only the 64-bit counters are added.
19536  */
19537 void
19538 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19539 {
19540 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19541 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19542 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19543 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19544 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19545 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19546 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19547 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19548 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19549 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19550 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19551 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19552 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19553 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19554 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
19555 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
19556 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
19557 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
19558 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
19559 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
19560 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
19561 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
19562 	    o2->ipIfStatsInWrongIPVersion);
19563 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
19564 	    o2->ipIfStatsInWrongIPVersion);
19565 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
19566 	    o2->ipIfStatsOutSwitchIPVersion);
19567 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
19568 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
19569 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
19570 	    o2->ipIfStatsHCInForwDatagrams);
19571 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
19572 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
19573 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
19574 	    o2->ipIfStatsHCOutForwDatagrams);
19575 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
19576 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
19577 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
19578 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
19579 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
19580 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
19581 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
19582 	    o2->ipIfStatsHCOutMcastOctets);
19583 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
19584 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
19585 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
19586 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
19587 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
19588 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
19589 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
19590 }
19591 
19592 void
19593 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
19594 {
19595 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
19596 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
19597 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
19598 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
19599 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
19600 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
19601 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
19602 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
19603 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
19604 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
19605 	    o2->ipv6IfIcmpInRouterSolicits);
19606 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
19607 	    o2->ipv6IfIcmpInRouterAdvertisements);
19608 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
19609 	    o2->ipv6IfIcmpInNeighborSolicits);
19610 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
19611 	    o2->ipv6IfIcmpInNeighborAdvertisements);
19612 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
19613 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
19614 	    o2->ipv6IfIcmpInGroupMembQueries);
19615 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
19616 	    o2->ipv6IfIcmpInGroupMembResponses);
19617 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
19618 	    o2->ipv6IfIcmpInGroupMembReductions);
19619 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
19620 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
19621 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
19622 	    o2->ipv6IfIcmpOutDestUnreachs);
19623 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
19624 	    o2->ipv6IfIcmpOutAdminProhibs);
19625 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
19626 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
19627 	    o2->ipv6IfIcmpOutParmProblems);
19628 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
19629 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
19630 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
19631 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
19632 	    o2->ipv6IfIcmpOutRouterSolicits);
19633 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
19634 	    o2->ipv6IfIcmpOutRouterAdvertisements);
19635 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
19636 	    o2->ipv6IfIcmpOutNeighborSolicits);
19637 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
19638 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
19639 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
19640 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
19641 	    o2->ipv6IfIcmpOutGroupMembQueries);
19642 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
19643 	    o2->ipv6IfIcmpOutGroupMembResponses);
19644 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
19645 	    o2->ipv6IfIcmpOutGroupMembReductions);
19646 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
19647 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
19648 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
19649 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
19650 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
19651 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
19652 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
19653 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
19654 	    o2->ipv6IfIcmpInGroupMembTotal);
19655 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
19656 	    o2->ipv6IfIcmpInGroupMembBadQueries);
19657 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
19658 	    o2->ipv6IfIcmpInGroupMembBadReports);
19659 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
19660 	    o2->ipv6IfIcmpInGroupMembOurReports);
19661 }
19662 
19663 /*
19664  * Called before the options are updated to check if this packet will
19665  * be source routed from here.
19666  * This routine assumes that the options are well formed i.e. that they
19667  * have already been checked.
19668  */
19669 static boolean_t
19670 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
19671 {
19672 	ipoptp_t	opts;
19673 	uchar_t		*opt;
19674 	uint8_t		optval;
19675 	uint8_t		optlen;
19676 	ipaddr_t	dst;
19677 	ire_t		*ire;
19678 
19679 	if (IS_SIMPLE_IPH(ipha)) {
19680 		ip2dbg(("not source routed\n"));
19681 		return (B_FALSE);
19682 	}
19683 	dst = ipha->ipha_dst;
19684 	for (optval = ipoptp_first(&opts, ipha);
19685 	    optval != IPOPT_EOL;
19686 	    optval = ipoptp_next(&opts)) {
19687 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19688 		opt = opts.ipoptp_cur;
19689 		optlen = opts.ipoptp_len;
19690 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19691 		    optval, optlen));
19692 		switch (optval) {
19693 			uint32_t off;
19694 		case IPOPT_SSRR:
19695 		case IPOPT_LSRR:
19696 			/*
19697 			 * If dst is one of our addresses and there are some
19698 			 * entries left in the source route return (true).
19699 			 */
19700 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19701 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
19702 			if (ire == NULL) {
19703 				ip2dbg(("ip_source_routed: not next"
19704 				    " source route 0x%x\n",
19705 				    ntohl(dst)));
19706 				return (B_FALSE);
19707 			}
19708 			ire_refrele(ire);
19709 			off = opt[IPOPT_OFFSET];
19710 			off--;
19711 			if (optlen < IP_ADDR_LEN ||
19712 			    off > optlen - IP_ADDR_LEN) {
19713 				/* End of source route */
19714 				ip1dbg(("ip_source_routed: end of SR\n"));
19715 				return (B_FALSE);
19716 			}
19717 			return (B_TRUE);
19718 		}
19719 	}
19720 	ip2dbg(("not source routed\n"));
19721 	return (B_FALSE);
19722 }
19723 
19724 /*
19725  * Check if the packet contains any source route.
19726  */
19727 static boolean_t
19728 ip_source_route_included(ipha_t *ipha)
19729 {
19730 	ipoptp_t	opts;
19731 	uint8_t		optval;
19732 
19733 	if (IS_SIMPLE_IPH(ipha))
19734 		return (B_FALSE);
19735 	for (optval = ipoptp_first(&opts, ipha);
19736 	    optval != IPOPT_EOL;
19737 	    optval = ipoptp_next(&opts)) {
19738 		switch (optval) {
19739 		case IPOPT_SSRR:
19740 		case IPOPT_LSRR:
19741 			return (B_TRUE);
19742 		}
19743 	}
19744 	return (B_FALSE);
19745 }
19746 
19747 /*
19748  * Called when the IRE expiration timer fires.
19749  */
19750 void
19751 ip_trash_timer_expire(void *args)
19752 {
19753 	int			flush_flag = 0;
19754 	ire_expire_arg_t	iea;
19755 	ip_stack_t		*ipst = (ip_stack_t *)args;
19756 
19757 	iea.iea_ipst = ipst;	/* No netstack_hold */
19758 
19759 	/*
19760 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
19761 	 * This lock makes sure that a new invocation of this function
19762 	 * that occurs due to an almost immediate timer firing will not
19763 	 * progress beyond this point until the current invocation is done
19764 	 */
19765 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19766 	ipst->ips_ip_ire_expire_id = 0;
19767 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19768 
19769 	/* Periodic timer */
19770 	if (ipst->ips_ip_ire_arp_time_elapsed >=
19771 	    ipst->ips_ip_ire_arp_interval) {
19772 		/*
19773 		 * Remove all IRE_CACHE entries since they might
19774 		 * contain arp information.
19775 		 */
19776 		flush_flag |= FLUSH_ARP_TIME;
19777 		ipst->ips_ip_ire_arp_time_elapsed = 0;
19778 		IP_STAT(ipst, ip_ire_arp_timer_expired);
19779 	}
19780 	if (ipst->ips_ip_ire_rd_time_elapsed >=
19781 	    ipst->ips_ip_ire_redir_interval) {
19782 		/* Remove all redirects */
19783 		flush_flag |= FLUSH_REDIRECT_TIME;
19784 		ipst->ips_ip_ire_rd_time_elapsed = 0;
19785 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
19786 	}
19787 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
19788 	    ipst->ips_ip_ire_pathmtu_interval) {
19789 		/* Increase path mtu */
19790 		flush_flag |= FLUSH_MTU_TIME;
19791 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
19792 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
19793 	}
19794 
19795 	/*
19796 	 * Optimize for the case when there are no redirects in the
19797 	 * ftable, that is, no need to walk the ftable in that case.
19798 	 */
19799 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
19800 		iea.iea_flush_flag = flush_flag;
19801 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
19802 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
19803 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
19804 		    NULL, ALL_ZONES, ipst);
19805 	}
19806 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
19807 	    ipst->ips_ip_redirect_cnt > 0) {
19808 		iea.iea_flush_flag = flush_flag;
19809 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
19810 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
19811 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
19812 	}
19813 	if (flush_flag & FLUSH_MTU_TIME) {
19814 		/*
19815 		 * Walk all IPv6 IRE's and update them
19816 		 * Note that ARP and redirect timers are not
19817 		 * needed since NUD handles stale entries.
19818 		 */
19819 		flush_flag = FLUSH_MTU_TIME;
19820 		iea.iea_flush_flag = flush_flag;
19821 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
19822 		    ALL_ZONES, ipst);
19823 	}
19824 
19825 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
19826 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
19827 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
19828 
19829 	/*
19830 	 * Hold the lock to serialize timeout calls and prevent
19831 	 * stale values in ip_ire_expire_id. Otherwise it is possible
19832 	 * for the timer to fire and a new invocation of this function
19833 	 * to start before the return value of timeout has been stored
19834 	 * in ip_ire_expire_id by the current invocation.
19835 	 */
19836 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19837 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
19838 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
19839 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19840 }
19841 
19842 /*
19843  * Called by the memory allocator subsystem directly, when the system
19844  * is running low on memory.
19845  */
19846 /* ARGSUSED */
19847 void
19848 ip_trash_ire_reclaim(void *args)
19849 {
19850 	netstack_handle_t nh;
19851 	netstack_t *ns;
19852 
19853 	netstack_next_init(&nh);
19854 	while ((ns = netstack_next(&nh)) != NULL) {
19855 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
19856 		netstack_rele(ns);
19857 	}
19858 	netstack_next_fini(&nh);
19859 }
19860 
19861 static void
19862 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
19863 {
19864 	ire_cache_count_t icc;
19865 	ire_cache_reclaim_t icr;
19866 	ncc_cache_count_t ncc;
19867 	nce_cache_reclaim_t ncr;
19868 	uint_t delete_cnt;
19869 	/*
19870 	 * Memory reclaim call back.
19871 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
19872 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
19873 	 * entries, determine what fraction to free for
19874 	 * each category of IRE_CACHE entries giving absolute priority
19875 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
19876 	 * entry will be freed unless all offlink entries are freed).
19877 	 */
19878 	icc.icc_total = 0;
19879 	icc.icc_unused = 0;
19880 	icc.icc_offlink = 0;
19881 	icc.icc_pmtu = 0;
19882 	icc.icc_onlink = 0;
19883 	ire_walk(ire_cache_count, (char *)&icc, ipst);
19884 
19885 	/*
19886 	 * Free NCEs for IPv6 like the onlink ires.
19887 	 */
19888 	ncc.ncc_total = 0;
19889 	ncc.ncc_host = 0;
19890 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
19891 
19892 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
19893 	    icc.icc_pmtu + icc.icc_onlink);
19894 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
19895 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
19896 	if (delete_cnt == 0)
19897 		return;
19898 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
19899 	/* Always delete all unused offlink entries */
19900 	icr.icr_ipst = ipst;
19901 	icr.icr_unused = 1;
19902 	if (delete_cnt <= icc.icc_unused) {
19903 		/*
19904 		 * Only need to free unused entries.  In other words,
19905 		 * there are enough unused entries to free to meet our
19906 		 * target number of freed ire cache entries.
19907 		 */
19908 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
19909 		ncr.ncr_host = 0;
19910 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
19911 		/*
19912 		 * Only need to free unused entries, plus a fraction of offlink
19913 		 * entries.  It follows from the first if statement that
19914 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
19915 		 */
19916 		delete_cnt -= icc.icc_unused;
19917 		/* Round up # deleted by truncating fraction */
19918 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
19919 		icr.icr_pmtu = icr.icr_onlink = 0;
19920 		ncr.ncr_host = 0;
19921 	} else if (delete_cnt <=
19922 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
19923 		/*
19924 		 * Free all unused and offlink entries, plus a fraction of
19925 		 * pmtu entries.  It follows from the previous if statement
19926 		 * that icc_pmtu is non-zero, and that
19927 		 * delete_cnt != icc_unused + icc_offlink.
19928 		 */
19929 		icr.icr_offlink = 1;
19930 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
19931 		/* Round up # deleted by truncating fraction */
19932 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
19933 		icr.icr_onlink = 0;
19934 		ncr.ncr_host = 0;
19935 	} else {
19936 		/*
19937 		 * Free all unused, offlink, and pmtu entries, plus a fraction
19938 		 * of onlink entries.  If we're here, then we know that
19939 		 * icc_onlink is non-zero, and that
19940 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
19941 		 */
19942 		icr.icr_offlink = icr.icr_pmtu = 1;
19943 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
19944 		    icc.icc_pmtu;
19945 		/* Round up # deleted by truncating fraction */
19946 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
19947 		/* Using the same delete fraction as for onlink IREs */
19948 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
19949 	}
19950 #ifdef DEBUG
19951 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
19952 	    "fractions %d/%d/%d/%d\n",
19953 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
19954 	    icc.icc_unused, icc.icc_offlink,
19955 	    icc.icc_pmtu, icc.icc_onlink,
19956 	    icr.icr_unused, icr.icr_offlink,
19957 	    icr.icr_pmtu, icr.icr_onlink));
19958 #endif
19959 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
19960 	if (ncr.ncr_host != 0)
19961 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
19962 		    (uchar_t *)&ncr, ipst);
19963 #ifdef DEBUG
19964 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
19965 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
19966 	ire_walk(ire_cache_count, (char *)&icc, ipst);
19967 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
19968 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
19969 	    icc.icc_pmtu, icc.icc_onlink));
19970 #endif
19971 }
19972 
19973 /*
19974  * ip_unbind is called when a copy of an unbind request is received from the
19975  * upper level protocol.  We remove this conn from any fanout hash list it is
19976  * on, and zero out the bind information.  No reply is expected up above.
19977  */
19978 mblk_t *
19979 ip_unbind(queue_t *q, mblk_t *mp)
19980 {
19981 	conn_t	*connp = Q_TO_CONN(q);
19982 
19983 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
19984 
19985 	if (is_system_labeled() && connp->conn_anon_port) {
19986 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
19987 		    connp->conn_mlp_type, connp->conn_ulp,
19988 		    ntohs(connp->conn_lport), B_FALSE);
19989 		connp->conn_anon_port = 0;
19990 	}
19991 	connp->conn_mlp_type = mlptSingle;
19992 
19993 	ipcl_hash_remove(connp);
19994 
19995 	ASSERT(mp->b_cont == NULL);
19996 	/*
19997 	 * Convert mp into a T_OK_ACK
19998 	 */
19999 	mp = mi_tpi_ok_ack_alloc(mp);
20000 
20001 	/*
20002 	 * should not happen in practice... T_OK_ACK is smaller than the
20003 	 * original message.
20004 	 */
20005 	if (mp == NULL)
20006 		return (NULL);
20007 
20008 	return (mp);
20009 }
20010 
20011 /*
20012  * Write side put procedure.  Outbound data, IOCTLs, responses from
20013  * resolvers, etc, come down through here.
20014  *
20015  * arg2 is always a queue_t *.
20016  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
20017  * the zoneid.
20018  * When that queue is not an ill_t, then arg must be a conn_t pointer.
20019  */
20020 void
20021 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
20022 {
20023 	ip_output_options(arg, mp, arg2, caller, &zero_info);
20024 }
20025 
20026 void
20027 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20028     ip_opt_info_t *infop)
20029 {
20030 	conn_t		*connp = NULL;
20031 	queue_t		*q = (queue_t *)arg2;
20032 	ipha_t		*ipha;
20033 #define	rptr	((uchar_t *)ipha)
20034 	ire_t		*ire = NULL;
20035 	ire_t		*sctp_ire = NULL;
20036 	uint32_t	v_hlen_tos_len;
20037 	ipaddr_t	dst;
20038 	mblk_t		*first_mp = NULL;
20039 	boolean_t	mctl_present;
20040 	ipsec_out_t	*io;
20041 	int		match_flags;
20042 	ill_t		*attach_ill = NULL;
20043 					/* Bind to IPIF_NOFAILOVER ill etc. */
20044 	ill_t		*xmit_ill = NULL;	/* IP_PKTINFO etc. */
20045 	ipif_t		*dst_ipif;
20046 	boolean_t	multirt_need_resolve = B_FALSE;
20047 	mblk_t		*copy_mp = NULL;
20048 	int		err;
20049 	zoneid_t	zoneid;
20050 	int	adjust;
20051 	uint16_t iplen;
20052 	boolean_t	need_decref = B_FALSE;
20053 	boolean_t	ignore_dontroute = B_FALSE;
20054 	boolean_t	ignore_nexthop = B_FALSE;
20055 	boolean_t	ip_nexthop = B_FALSE;
20056 	ipaddr_t	nexthop_addr;
20057 	ip_stack_t	*ipst;
20058 
20059 #ifdef	_BIG_ENDIAN
20060 #define	V_HLEN	(v_hlen_tos_len >> 24)
20061 #else
20062 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20063 #endif
20064 
20065 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20066 	    "ip_wput_start: q %p", q);
20067 
20068 	/*
20069 	 * ip_wput fast path
20070 	 */
20071 
20072 	/* is packet from ARP ? */
20073 	if (q->q_next != NULL) {
20074 		zoneid = (zoneid_t)(uintptr_t)arg;
20075 		goto qnext;
20076 	}
20077 
20078 	connp = (conn_t *)arg;
20079 	ASSERT(connp != NULL);
20080 	zoneid = connp->conn_zoneid;
20081 	ipst = connp->conn_netstack->netstack_ip;
20082 
20083 	/* is queue flow controlled? */
20084 	if ((q->q_first != NULL || connp->conn_draining) &&
20085 	    (caller == IP_WPUT)) {
20086 		ASSERT(!need_decref);
20087 		(void) putq(q, mp);
20088 		return;
20089 	}
20090 
20091 	/* Multidata transmit? */
20092 	if (DB_TYPE(mp) == M_MULTIDATA) {
20093 		/*
20094 		 * We should never get here, since all Multidata messages
20095 		 * originating from tcp should have been directed over to
20096 		 * tcp_multisend() in the first place.
20097 		 */
20098 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20099 		freemsg(mp);
20100 		return;
20101 	} else if (DB_TYPE(mp) != M_DATA)
20102 		goto notdata;
20103 
20104 	if (mp->b_flag & MSGHASREF) {
20105 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20106 		mp->b_flag &= ~MSGHASREF;
20107 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20108 		need_decref = B_TRUE;
20109 	}
20110 	ipha = (ipha_t *)mp->b_rptr;
20111 
20112 	/* is IP header non-aligned or mblk smaller than basic IP header */
20113 #ifndef SAFETY_BEFORE_SPEED
20114 	if (!OK_32PTR(rptr) ||
20115 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20116 		goto hdrtoosmall;
20117 #endif
20118 
20119 	ASSERT(OK_32PTR(ipha));
20120 
20121 	/*
20122 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20123 	 * wrong version, we'll catch it again in ip_output_v6.
20124 	 *
20125 	 * Note that this is *only* locally-generated output here, and never
20126 	 * forwarded data, and that we need to deal only with transports that
20127 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20128 	 * label.)
20129 	 */
20130 	if (is_system_labeled() &&
20131 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20132 	    !connp->conn_ulp_labeled) {
20133 		err = tsol_check_label(BEST_CRED(mp, connp), &mp, &adjust,
20134 		    connp->conn_mac_exempt, ipst);
20135 		ipha = (ipha_t *)mp->b_rptr;
20136 		if (err != 0) {
20137 			first_mp = mp;
20138 			if (err == EINVAL)
20139 				goto icmp_parameter_problem;
20140 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20141 			goto discard_pkt;
20142 		}
20143 		iplen = ntohs(ipha->ipha_length) + adjust;
20144 		ipha->ipha_length = htons(iplen);
20145 	}
20146 
20147 	ASSERT(infop != NULL);
20148 
20149 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20150 		/*
20151 		 * IP_PKTINFO ancillary option is present.
20152 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20153 		 * allows using address of any zone as the source address.
20154 		 */
20155 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20156 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20157 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20158 		if (ire == NULL)
20159 			goto drop_pkt;
20160 		ire_refrele(ire);
20161 		ire = NULL;
20162 	}
20163 
20164 	/*
20165 	 * IP_DONTFAILOVER_IF and IP_BOUND_IF have precedence over ill index
20166 	 * passed in IP_PKTINFO.
20167 	 */
20168 	if (infop->ip_opt_ill_index != 0 &&
20169 	    connp->conn_outgoing_ill == NULL &&
20170 	    connp->conn_nofailover_ill == NULL) {
20171 
20172 		xmit_ill = ill_lookup_on_ifindex(
20173 		    infop->ip_opt_ill_index, B_FALSE, NULL, NULL, NULL, NULL,
20174 		    ipst);
20175 
20176 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20177 			goto drop_pkt;
20178 		/*
20179 		 * check that there is an ipif belonging
20180 		 * to our zone. IPCL_ZONEID is not used because
20181 		 * IP_ALLZONES option is valid only when the ill is
20182 		 * accessible from all zones i.e has a valid ipif in
20183 		 * all zones.
20184 		 */
20185 		if (!ipif_lookup_zoneid_group(xmit_ill, zoneid, 0, NULL)) {
20186 			goto drop_pkt;
20187 		}
20188 	}
20189 
20190 	/*
20191 	 * If there is a policy, try to attach an ipsec_out in
20192 	 * the front. At the end, first_mp either points to a
20193 	 * M_DATA message or IPSEC_OUT message linked to a
20194 	 * M_DATA message. We have to do it now as we might
20195 	 * lose the "conn" if we go through ip_newroute.
20196 	 */
20197 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20198 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
20199 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20200 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20201 			if (need_decref)
20202 				CONN_DEC_REF(connp);
20203 			return;
20204 		} else {
20205 			ASSERT(mp->b_datap->db_type == M_CTL);
20206 			first_mp = mp;
20207 			mp = mp->b_cont;
20208 			mctl_present = B_TRUE;
20209 		}
20210 	} else {
20211 		first_mp = mp;
20212 		mctl_present = B_FALSE;
20213 	}
20214 
20215 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20216 
20217 	/* is wrong version or IP options present */
20218 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20219 		goto version_hdrlen_check;
20220 	dst = ipha->ipha_dst;
20221 
20222 	if (connp->conn_nofailover_ill != NULL) {
20223 		attach_ill = conn_get_held_ill(connp,
20224 		    &connp->conn_nofailover_ill, &err);
20225 		if (err == ILL_LOOKUP_FAILED) {
20226 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20227 			if (need_decref)
20228 				CONN_DEC_REF(connp);
20229 			freemsg(first_mp);
20230 			return;
20231 		}
20232 	}
20233 
20234 	/* If IP_BOUND_IF has been set, use that ill. */
20235 	if (connp->conn_outgoing_ill != NULL) {
20236 		xmit_ill = conn_get_held_ill(connp,
20237 		    &connp->conn_outgoing_ill, &err);
20238 		if (err == ILL_LOOKUP_FAILED)
20239 			goto drop_pkt;
20240 
20241 		goto send_from_ill;
20242 	}
20243 
20244 	/* is packet multicast? */
20245 	if (CLASSD(dst))
20246 		goto multicast;
20247 
20248 	/*
20249 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20250 	 * takes precedence over conn_dontroute and conn_nexthop_set
20251 	 */
20252 	if (xmit_ill != NULL)
20253 		goto send_from_ill;
20254 
20255 	if (connp->conn_dontroute || connp->conn_nexthop_set) {
20256 		/*
20257 		 * If the destination is a broadcast, local, or loopback
20258 		 * address, SO_DONTROUTE and IP_NEXTHOP go through the
20259 		 * standard path.
20260 		 */
20261 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20262 		if ((ire == NULL) || (ire->ire_type &
20263 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK)) == 0) {
20264 			if (ire != NULL) {
20265 				ire_refrele(ire);
20266 				/* No more access to ire */
20267 				ire = NULL;
20268 			}
20269 			/*
20270 			 * bypass routing checks and go directly to interface.
20271 			 */
20272 			if (connp->conn_dontroute)
20273 				goto dontroute;
20274 
20275 			ASSERT(connp->conn_nexthop_set);
20276 			ip_nexthop = B_TRUE;
20277 			nexthop_addr = connp->conn_nexthop_v4;
20278 			goto send_from_ill;
20279 		}
20280 
20281 		/* Must be a broadcast, a loopback or a local ire */
20282 		ire_refrele(ire);
20283 		/* No more access to ire */
20284 		ire = NULL;
20285 	}
20286 
20287 	if (attach_ill != NULL)
20288 		goto send_from_ill;
20289 
20290 	/*
20291 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20292 	 * this for the tcp global queue and listen end point
20293 	 * as it does not really have a real destination to
20294 	 * talk to.  This is also true for SCTP.
20295 	 */
20296 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20297 	    !connp->conn_fully_bound) {
20298 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20299 		if (ire == NULL)
20300 			goto noirefound;
20301 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20302 		    "ip_wput_end: q %p (%S)", q, "end");
20303 
20304 		/*
20305 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20306 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20307 		 */
20308 		if (ire->ire_flags & RTF_MULTIRT) {
20309 
20310 			/*
20311 			 * Force the TTL of multirouted packets if required.
20312 			 * The TTL of such packets is bounded by the
20313 			 * ip_multirt_ttl ndd variable.
20314 			 */
20315 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20316 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20317 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20318 				    "(was %d), dst 0x%08x\n",
20319 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20320 				    ntohl(ire->ire_addr)));
20321 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20322 			}
20323 			/*
20324 			 * We look at this point if there are pending
20325 			 * unresolved routes. ire_multirt_resolvable()
20326 			 * checks in O(n) that all IRE_OFFSUBNET ire
20327 			 * entries for the packet's destination and
20328 			 * flagged RTF_MULTIRT are currently resolved.
20329 			 * If some remain unresolved, we make a copy
20330 			 * of the current message. It will be used
20331 			 * to initiate additional route resolutions.
20332 			 */
20333 			multirt_need_resolve =
20334 			    ire_multirt_need_resolve(ire->ire_addr,
20335 			    MBLK_GETLABEL(first_mp), ipst);
20336 			ip2dbg(("ip_wput[TCP]: ire %p, "
20337 			    "multirt_need_resolve %d, first_mp %p\n",
20338 			    (void *)ire, multirt_need_resolve,
20339 			    (void *)first_mp));
20340 			if (multirt_need_resolve) {
20341 				copy_mp = copymsg(first_mp);
20342 				if (copy_mp != NULL) {
20343 					MULTIRT_DEBUG_TAG(copy_mp);
20344 				}
20345 			}
20346 		}
20347 
20348 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20349 
20350 		/*
20351 		 * Try to resolve another multiroute if
20352 		 * ire_multirt_need_resolve() deemed it necessary.
20353 		 */
20354 		if (copy_mp != NULL)
20355 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20356 		if (need_decref)
20357 			CONN_DEC_REF(connp);
20358 		return;
20359 	}
20360 
20361 	/*
20362 	 * Access to conn_ire_cache. (protected by conn_lock)
20363 	 *
20364 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20365 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20366 	 * send a packet or two with the IRE_CACHE that is going away.
20367 	 * Access to the ire requires an ire refhold on the ire prior to
20368 	 * its use since an interface unplumb thread may delete the cached
20369 	 * ire and release the refhold at any time.
20370 	 *
20371 	 * Caching an ire in the conn_ire_cache
20372 	 *
20373 	 * o Caching an ire pointer in the conn requires a strict check for
20374 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20375 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20376 	 * in the conn is done after making sure under the bucket lock that the
20377 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20378 	 * caching an ire after the unplumb thread has cleaned up the conn.
20379 	 * If the conn does not send a packet subsequently the unplumb thread
20380 	 * will be hanging waiting for the ire count to drop to zero.
20381 	 *
20382 	 * o We also need to atomically test for a null conn_ire_cache and
20383 	 * set the conn_ire_cache under the the protection of the conn_lock
20384 	 * to avoid races among concurrent threads trying to simultaneously
20385 	 * cache an ire in the conn_ire_cache.
20386 	 */
20387 	mutex_enter(&connp->conn_lock);
20388 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20389 
20390 	if (ire != NULL && ire->ire_addr == dst &&
20391 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20392 
20393 		IRE_REFHOLD(ire);
20394 		mutex_exit(&connp->conn_lock);
20395 
20396 	} else {
20397 		boolean_t cached = B_FALSE;
20398 		connp->conn_ire_cache = NULL;
20399 		mutex_exit(&connp->conn_lock);
20400 		/* Release the old ire */
20401 		if (ire != NULL && sctp_ire == NULL)
20402 			IRE_REFRELE_NOTR(ire);
20403 
20404 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20405 		if (ire == NULL)
20406 			goto noirefound;
20407 		IRE_REFHOLD_NOTR(ire);
20408 
20409 		mutex_enter(&connp->conn_lock);
20410 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20411 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20412 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20413 				if (connp->conn_ulp == IPPROTO_TCP)
20414 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20415 				connp->conn_ire_cache = ire;
20416 				cached = B_TRUE;
20417 			}
20418 			rw_exit(&ire->ire_bucket->irb_lock);
20419 		}
20420 		mutex_exit(&connp->conn_lock);
20421 
20422 		/*
20423 		 * We can continue to use the ire but since it was
20424 		 * not cached, we should drop the extra reference.
20425 		 */
20426 		if (!cached)
20427 			IRE_REFRELE_NOTR(ire);
20428 	}
20429 
20430 
20431 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20432 	    "ip_wput_end: q %p (%S)", q, "end");
20433 
20434 	/*
20435 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20436 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20437 	 */
20438 	if (ire->ire_flags & RTF_MULTIRT) {
20439 
20440 		/*
20441 		 * Force the TTL of multirouted packets if required.
20442 		 * The TTL of such packets is bounded by the
20443 		 * ip_multirt_ttl ndd variable.
20444 		 */
20445 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20446 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20447 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20448 			    "(was %d), dst 0x%08x\n",
20449 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20450 			    ntohl(ire->ire_addr)));
20451 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20452 		}
20453 
20454 		/*
20455 		 * At this point, we check to see if there are any pending
20456 		 * unresolved routes. ire_multirt_resolvable()
20457 		 * checks in O(n) that all IRE_OFFSUBNET ire
20458 		 * entries for the packet's destination and
20459 		 * flagged RTF_MULTIRT are currently resolved.
20460 		 * If some remain unresolved, we make a copy
20461 		 * of the current message. It will be used
20462 		 * to initiate additional route resolutions.
20463 		 */
20464 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20465 		    MBLK_GETLABEL(first_mp), ipst);
20466 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20467 		    "multirt_need_resolve %d, first_mp %p\n",
20468 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20469 		if (multirt_need_resolve) {
20470 			copy_mp = copymsg(first_mp);
20471 			if (copy_mp != NULL) {
20472 				MULTIRT_DEBUG_TAG(copy_mp);
20473 			}
20474 		}
20475 	}
20476 
20477 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20478 
20479 	/*
20480 	 * Try to resolve another multiroute if
20481 	 * ire_multirt_resolvable() deemed it necessary
20482 	 */
20483 	if (copy_mp != NULL)
20484 		ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20485 	if (need_decref)
20486 		CONN_DEC_REF(connp);
20487 	return;
20488 
20489 qnext:
20490 	/*
20491 	 * Upper Level Protocols pass down complete IP datagrams
20492 	 * as M_DATA messages.	Everything else is a sideshow.
20493 	 *
20494 	 * 1) We could be re-entering ip_wput because of ip_neworute
20495 	 *    in which case we could have a IPSEC_OUT message. We
20496 	 *    need to pass through ip_wput like other datagrams and
20497 	 *    hence cannot branch to ip_wput_nondata.
20498 	 *
20499 	 * 2) ARP, AH, ESP, and other clients who are on the module
20500 	 *    instance of IP stream, give us something to deal with.
20501 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20502 	 *
20503 	 * 3) ICMP replies also could come here.
20504 	 */
20505 	ipst = ILLQ_TO_IPST(q);
20506 
20507 	if (DB_TYPE(mp) != M_DATA) {
20508 notdata:
20509 		if (DB_TYPE(mp) == M_CTL) {
20510 			/*
20511 			 * M_CTL messages are used by ARP, AH and ESP to
20512 			 * communicate with IP. We deal with IPSEC_IN and
20513 			 * IPSEC_OUT here. ip_wput_nondata handles other
20514 			 * cases.
20515 			 */
20516 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20517 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20518 				first_mp = mp->b_cont;
20519 				first_mp->b_flag &= ~MSGHASREF;
20520 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20521 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20522 				CONN_DEC_REF(connp);
20523 				connp = NULL;
20524 			}
20525 			if (ii->ipsec_info_type == IPSEC_IN) {
20526 				/*
20527 				 * Either this message goes back to
20528 				 * IPsec for further processing or to
20529 				 * ULP after policy checks.
20530 				 */
20531 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20532 				return;
20533 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20534 				io = (ipsec_out_t *)ii;
20535 				if (io->ipsec_out_proc_begin) {
20536 					/*
20537 					 * IPsec processing has already started.
20538 					 * Complete it.
20539 					 * IPQoS notes: We don't care what is
20540 					 * in ipsec_out_ill_index since this
20541 					 * won't be processed for IPQoS policies
20542 					 * in ipsec_out_process.
20543 					 */
20544 					ipsec_out_process(q, mp, NULL,
20545 					    io->ipsec_out_ill_index);
20546 					return;
20547 				} else {
20548 					connp = (q->q_next != NULL) ?
20549 					    NULL : Q_TO_CONN(q);
20550 					first_mp = mp;
20551 					mp = mp->b_cont;
20552 					mctl_present = B_TRUE;
20553 				}
20554 				zoneid = io->ipsec_out_zoneid;
20555 				ASSERT(zoneid != ALL_ZONES);
20556 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20557 				/*
20558 				 * It's an IPsec control message requesting
20559 				 * an SADB update to be sent to the IPsec
20560 				 * hardware acceleration capable ills.
20561 				 */
20562 				ipsec_ctl_t *ipsec_ctl =
20563 				    (ipsec_ctl_t *)mp->b_rptr;
20564 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20565 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20566 				mblk_t *cmp = mp->b_cont;
20567 
20568 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20569 				ASSERT(cmp != NULL);
20570 
20571 				freeb(mp);
20572 				ill_ipsec_capab_send_all(satype, cmp, sa,
20573 				    ipst->ips_netstack);
20574 				return;
20575 			} else {
20576 				/*
20577 				 * This must be ARP or special TSOL signaling.
20578 				 */
20579 				ip_wput_nondata(NULL, q, mp, NULL);
20580 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20581 				    "ip_wput_end: q %p (%S)", q, "nondata");
20582 				return;
20583 			}
20584 		} else {
20585 			/*
20586 			 * This must be non-(ARP/AH/ESP) messages.
20587 			 */
20588 			ASSERT(!need_decref);
20589 			ip_wput_nondata(NULL, q, mp, NULL);
20590 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20591 			    "ip_wput_end: q %p (%S)", q, "nondata");
20592 			return;
20593 		}
20594 	} else {
20595 		first_mp = mp;
20596 		mctl_present = B_FALSE;
20597 	}
20598 
20599 	ASSERT(first_mp != NULL);
20600 	/*
20601 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
20602 	 * to make sure that this packet goes out on the same interface it
20603 	 * came in. We handle that here.
20604 	 */
20605 	if (mctl_present) {
20606 		uint_t ifindex;
20607 
20608 		io = (ipsec_out_t *)first_mp->b_rptr;
20609 		if (io->ipsec_out_attach_if || io->ipsec_out_ip_nexthop) {
20610 			/*
20611 			 * We may have lost the conn context if we are
20612 			 * coming here from ip_newroute(). Copy the
20613 			 * nexthop information.
20614 			 */
20615 			if (io->ipsec_out_ip_nexthop) {
20616 				ip_nexthop = B_TRUE;
20617 				nexthop_addr = io->ipsec_out_nexthop_addr;
20618 
20619 				ipha = (ipha_t *)mp->b_rptr;
20620 				dst = ipha->ipha_dst;
20621 				goto send_from_ill;
20622 			} else {
20623 				ASSERT(io->ipsec_out_ill_index != 0);
20624 				ifindex = io->ipsec_out_ill_index;
20625 				attach_ill = ill_lookup_on_ifindex(ifindex,
20626 				    B_FALSE, NULL, NULL, NULL, NULL, ipst);
20627 				if (attach_ill == NULL) {
20628 					ASSERT(xmit_ill == NULL);
20629 					ip1dbg(("ip_output: bad ifindex for "
20630 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
20631 					    ifindex));
20632 					freemsg(first_mp);
20633 					BUMP_MIB(&ipst->ips_ip_mib,
20634 					    ipIfStatsOutDiscards);
20635 					ASSERT(!need_decref);
20636 					return;
20637 				}
20638 			}
20639 		}
20640 	}
20641 
20642 	ASSERT(xmit_ill == NULL);
20643 
20644 	/* We have a complete IP datagram heading outbound. */
20645 	ipha = (ipha_t *)mp->b_rptr;
20646 
20647 #ifndef SPEED_BEFORE_SAFETY
20648 	/*
20649 	 * Make sure we have a full-word aligned message and that at least
20650 	 * a simple IP header is accessible in the first message.  If not,
20651 	 * try a pullup.
20652 	 */
20653 	if (!OK_32PTR(rptr) ||
20654 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
20655 hdrtoosmall:
20656 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20657 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20658 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20659 			if (first_mp == NULL)
20660 				first_mp = mp;
20661 			goto discard_pkt;
20662 		}
20663 
20664 		/* This function assumes that mp points to an IPv4 packet. */
20665 		if (is_system_labeled() && q->q_next == NULL &&
20666 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20667 		    !connp->conn_ulp_labeled) {
20668 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20669 			    &adjust, connp->conn_mac_exempt, ipst);
20670 			ipha = (ipha_t *)mp->b_rptr;
20671 			if (first_mp != NULL)
20672 				first_mp->b_cont = mp;
20673 			if (err != 0) {
20674 				if (first_mp == NULL)
20675 					first_mp = mp;
20676 				if (err == EINVAL)
20677 					goto icmp_parameter_problem;
20678 				ip2dbg(("ip_wput: label check failed (%d)\n",
20679 				    err));
20680 				goto discard_pkt;
20681 			}
20682 			iplen = ntohs(ipha->ipha_length) + adjust;
20683 			ipha->ipha_length = htons(iplen);
20684 		}
20685 
20686 		ipha = (ipha_t *)mp->b_rptr;
20687 		if (first_mp == NULL) {
20688 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
20689 			/*
20690 			 * If we got here because of "goto hdrtoosmall"
20691 			 * We need to attach a IPSEC_OUT.
20692 			 */
20693 			if (connp->conn_out_enforce_policy) {
20694 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
20695 				    NULL, ipha->ipha_protocol,
20696 				    ipst->ips_netstack)) == NULL)) {
20697 					BUMP_MIB(&ipst->ips_ip_mib,
20698 					    ipIfStatsOutDiscards);
20699 					if (need_decref)
20700 						CONN_DEC_REF(connp);
20701 					return;
20702 				} else {
20703 					ASSERT(mp->b_datap->db_type == M_CTL);
20704 					first_mp = mp;
20705 					mp = mp->b_cont;
20706 					mctl_present = B_TRUE;
20707 				}
20708 			} else {
20709 				first_mp = mp;
20710 				mctl_present = B_FALSE;
20711 			}
20712 		}
20713 	}
20714 #endif
20715 
20716 	/* Most of the code below is written for speed, not readability */
20717 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20718 
20719 	/*
20720 	 * If ip_newroute() fails, we're going to need a full
20721 	 * header for the icmp wraparound.
20722 	 */
20723 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
20724 		uint_t	v_hlen;
20725 version_hdrlen_check:
20726 		ASSERT(first_mp != NULL);
20727 		v_hlen = V_HLEN;
20728 		/*
20729 		 * siphon off IPv6 packets coming down from transport
20730 		 * layer modules here.
20731 		 * Note: high-order bit carries NUD reachability confirmation
20732 		 */
20733 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
20734 			/*
20735 			 * FIXME: assume that callers of ip_output* call
20736 			 * the right version?
20737 			 */
20738 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
20739 			ASSERT(xmit_ill == NULL);
20740 			if (attach_ill != NULL)
20741 				ill_refrele(attach_ill);
20742 			if (need_decref)
20743 				mp->b_flag |= MSGHASREF;
20744 			(void) ip_output_v6(arg, first_mp, arg2, caller);
20745 			return;
20746 		}
20747 
20748 		if ((v_hlen >> 4) != IP_VERSION) {
20749 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20750 			    "ip_wput_end: q %p (%S)", q, "badvers");
20751 			goto discard_pkt;
20752 		}
20753 		/*
20754 		 * Is the header length at least 20 bytes?
20755 		 *
20756 		 * Are there enough bytes accessible in the header?  If
20757 		 * not, try a pullup.
20758 		 */
20759 		v_hlen &= 0xF;
20760 		v_hlen <<= 2;
20761 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
20762 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20763 			    "ip_wput_end: q %p (%S)", q, "badlen");
20764 			goto discard_pkt;
20765 		}
20766 		if (v_hlen > (mp->b_wptr - rptr)) {
20767 			if (!pullupmsg(mp, v_hlen)) {
20768 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20769 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
20770 				goto discard_pkt;
20771 			}
20772 			ipha = (ipha_t *)mp->b_rptr;
20773 		}
20774 		/*
20775 		 * Move first entry from any source route into ipha_dst and
20776 		 * verify the options
20777 		 */
20778 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
20779 		    zoneid, ipst)) {
20780 			ASSERT(xmit_ill == NULL);
20781 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20782 			if (attach_ill != NULL)
20783 				ill_refrele(attach_ill);
20784 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20785 			    "ip_wput_end: q %p (%S)", q, "badopts");
20786 			if (need_decref)
20787 				CONN_DEC_REF(connp);
20788 			return;
20789 		}
20790 	}
20791 	dst = ipha->ipha_dst;
20792 
20793 	/*
20794 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
20795 	 * we have to run the packet through ip_newroute which will take
20796 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
20797 	 * a resolver, or assigning a default gateway, etc.
20798 	 */
20799 	if (CLASSD(dst)) {
20800 		ipif_t	*ipif;
20801 		uint32_t setsrc = 0;
20802 
20803 multicast:
20804 		ASSERT(first_mp != NULL);
20805 		ip2dbg(("ip_wput: CLASSD\n"));
20806 		if (connp == NULL) {
20807 			/*
20808 			 * Use the first good ipif on the ill.
20809 			 * XXX Should this ever happen? (Appears
20810 			 * to show up with just ppp and no ethernet due
20811 			 * to in.rdisc.)
20812 			 * However, ire_send should be able to
20813 			 * call ip_wput_ire directly.
20814 			 *
20815 			 * XXX Also, this can happen for ICMP and other packets
20816 			 * with multicast source addresses.  Perhaps we should
20817 			 * fix things so that we drop the packet in question,
20818 			 * but for now, just run with it.
20819 			 */
20820 			ill_t *ill = (ill_t *)q->q_ptr;
20821 
20822 			/*
20823 			 * Don't honor attach_if for this case. If ill
20824 			 * is part of the group, ipif could belong to
20825 			 * any ill and we cannot maintain attach_ill
20826 			 * and ipif_ill same anymore and the assert
20827 			 * below would fail.
20828 			 */
20829 			if (mctl_present && io->ipsec_out_attach_if) {
20830 				io->ipsec_out_ill_index = 0;
20831 				io->ipsec_out_attach_if = B_FALSE;
20832 				ASSERT(attach_ill != NULL);
20833 				ill_refrele(attach_ill);
20834 				attach_ill = NULL;
20835 			}
20836 
20837 			ASSERT(attach_ill == NULL);
20838 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
20839 			if (ipif == NULL) {
20840 				if (need_decref)
20841 					CONN_DEC_REF(connp);
20842 				freemsg(first_mp);
20843 				return;
20844 			}
20845 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
20846 			    ntohl(dst), ill->ill_name));
20847 		} else {
20848 			/*
20849 			 * The order of precedence is IP_BOUND_IF, IP_PKTINFO
20850 			 * and IP_MULTICAST_IF.  The block comment above this
20851 			 * function explains the locking mechanism used here.
20852 			 */
20853 			if (xmit_ill == NULL) {
20854 				xmit_ill = conn_get_held_ill(connp,
20855 				    &connp->conn_outgoing_ill, &err);
20856 				if (err == ILL_LOOKUP_FAILED) {
20857 					ip1dbg(("ip_wput: No ill for "
20858 					    "IP_BOUND_IF\n"));
20859 					BUMP_MIB(&ipst->ips_ip_mib,
20860 					    ipIfStatsOutNoRoutes);
20861 					goto drop_pkt;
20862 				}
20863 			}
20864 
20865 			if (xmit_ill == NULL) {
20866 				ipif = conn_get_held_ipif(connp,
20867 				    &connp->conn_multicast_ipif, &err);
20868 				if (err == IPIF_LOOKUP_FAILED) {
20869 					ip1dbg(("ip_wput: No ipif for "
20870 					    "multicast\n"));
20871 					BUMP_MIB(&ipst->ips_ip_mib,
20872 					    ipIfStatsOutNoRoutes);
20873 					goto drop_pkt;
20874 				}
20875 			}
20876 			if (xmit_ill != NULL) {
20877 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
20878 				if (ipif == NULL) {
20879 					ip1dbg(("ip_wput: No ipif for "
20880 					    "xmit_ill\n"));
20881 					BUMP_MIB(&ipst->ips_ip_mib,
20882 					    ipIfStatsOutNoRoutes);
20883 					goto drop_pkt;
20884 				}
20885 			} else if (ipif == NULL || ipif->ipif_isv6) {
20886 				/*
20887 				 * We must do this ipif determination here
20888 				 * else we could pass through ip_newroute
20889 				 * and come back here without the conn context.
20890 				 *
20891 				 * Note: we do late binding i.e. we bind to
20892 				 * the interface when the first packet is sent.
20893 				 * For performance reasons we do not rebind on
20894 				 * each packet but keep the binding until the
20895 				 * next IP_MULTICAST_IF option.
20896 				 *
20897 				 * conn_multicast_{ipif,ill} are shared between
20898 				 * IPv4 and IPv6 and AF_INET6 sockets can
20899 				 * send both IPv4 and IPv6 packets. Hence
20900 				 * we have to check that "isv6" matches above.
20901 				 */
20902 				if (ipif != NULL)
20903 					ipif_refrele(ipif);
20904 				ipif = ipif_lookup_group(dst, zoneid, ipst);
20905 				if (ipif == NULL) {
20906 					ip1dbg(("ip_wput: No ipif for "
20907 					    "multicast\n"));
20908 					BUMP_MIB(&ipst->ips_ip_mib,
20909 					    ipIfStatsOutNoRoutes);
20910 					goto drop_pkt;
20911 				}
20912 				err = conn_set_held_ipif(connp,
20913 				    &connp->conn_multicast_ipif, ipif);
20914 				if (err == IPIF_LOOKUP_FAILED) {
20915 					ipif_refrele(ipif);
20916 					ip1dbg(("ip_wput: No ipif for "
20917 					    "multicast\n"));
20918 					BUMP_MIB(&ipst->ips_ip_mib,
20919 					    ipIfStatsOutNoRoutes);
20920 					goto drop_pkt;
20921 				}
20922 			}
20923 		}
20924 		ASSERT(!ipif->ipif_isv6);
20925 		/*
20926 		 * As we may lose the conn by the time we reach ip_wput_ire,
20927 		 * we copy conn_multicast_loop and conn_dontroute on to an
20928 		 * ipsec_out. In case if this datagram goes out secure,
20929 		 * we need the ill_index also. Copy that also into the
20930 		 * ipsec_out.
20931 		 */
20932 		if (mctl_present) {
20933 			io = (ipsec_out_t *)first_mp->b_rptr;
20934 			ASSERT(first_mp->b_datap->db_type == M_CTL);
20935 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
20936 		} else {
20937 			ASSERT(mp == first_mp);
20938 			if ((first_mp = allocb(sizeof (ipsec_info_t),
20939 			    BPRI_HI)) == NULL) {
20940 				ipif_refrele(ipif);
20941 				first_mp = mp;
20942 				goto discard_pkt;
20943 			}
20944 			first_mp->b_datap->db_type = M_CTL;
20945 			first_mp->b_wptr += sizeof (ipsec_info_t);
20946 			/* ipsec_out_secure is B_FALSE now */
20947 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
20948 			io = (ipsec_out_t *)first_mp->b_rptr;
20949 			io->ipsec_out_type = IPSEC_OUT;
20950 			io->ipsec_out_len = sizeof (ipsec_out_t);
20951 			io->ipsec_out_use_global_policy = B_TRUE;
20952 			io->ipsec_out_ns = ipst->ips_netstack;
20953 			first_mp->b_cont = mp;
20954 			mctl_present = B_TRUE;
20955 		}
20956 		if (attach_ill != NULL) {
20957 			ASSERT(attach_ill == ipif->ipif_ill);
20958 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
20959 
20960 			/*
20961 			 * Check if we need an ire that will not be
20962 			 * looked up by anybody else i.e. HIDDEN.
20963 			 */
20964 			if (ill_is_probeonly(attach_ill)) {
20965 				match_flags |= MATCH_IRE_MARK_HIDDEN;
20966 			}
20967 			io->ipsec_out_ill_index =
20968 			    attach_ill->ill_phyint->phyint_ifindex;
20969 			io->ipsec_out_attach_if = B_TRUE;
20970 		} else {
20971 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
20972 			io->ipsec_out_ill_index =
20973 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
20974 		}
20975 		if (connp != NULL) {
20976 			io->ipsec_out_multicast_loop =
20977 			    connp->conn_multicast_loop;
20978 			io->ipsec_out_dontroute = connp->conn_dontroute;
20979 			io->ipsec_out_zoneid = connp->conn_zoneid;
20980 		}
20981 		/*
20982 		 * If the application uses IP_MULTICAST_IF with
20983 		 * different logical addresses of the same ILL, we
20984 		 * need to make sure that the soruce address of
20985 		 * the packet matches the logical IP address used
20986 		 * in the option. We do it by initializing ipha_src
20987 		 * here. This should keep IPsec also happy as
20988 		 * when we return from IPsec processing, we don't
20989 		 * have to worry about getting the right address on
20990 		 * the packet. Thus it is sufficient to look for
20991 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
20992 		 * MATCH_IRE_IPIF.
20993 		 *
20994 		 * NOTE : We need to do it for non-secure case also as
20995 		 * this might go out secure if there is a global policy
20996 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
20997 		 * address, the source should be initialized already and
20998 		 * hence we won't be initializing here.
20999 		 *
21000 		 * As we do not have the ire yet, it is possible that
21001 		 * we set the source address here and then later discover
21002 		 * that the ire implies the source address to be assigned
21003 		 * through the RTF_SETSRC flag.
21004 		 * In that case, the setsrc variable will remind us
21005 		 * that overwritting the source address by the one
21006 		 * of the RTF_SETSRC-flagged ire is allowed.
21007 		 */
21008 		if (ipha->ipha_src == INADDR_ANY &&
21009 		    (connp == NULL || !connp->conn_unspec_src)) {
21010 			ipha->ipha_src = ipif->ipif_src_addr;
21011 			setsrc = RTF_SETSRC;
21012 		}
21013 		/*
21014 		 * Find an IRE which matches the destination and the outgoing
21015 		 * queue (i.e. the outgoing interface.)
21016 		 * For loopback use a unicast IP address for
21017 		 * the ire lookup.
21018 		 */
21019 		if (IS_LOOPBACK(ipif->ipif_ill))
21020 			dst = ipif->ipif_lcl_addr;
21021 
21022 		/*
21023 		 * If xmit_ill is set, we branch out to ip_newroute_ipif.
21024 		 * We don't need to lookup ire in ctable as the packet
21025 		 * needs to be sent to the destination through the specified
21026 		 * ill irrespective of ires in the cache table.
21027 		 */
21028 		ire = NULL;
21029 		if (xmit_ill == NULL) {
21030 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21031 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21032 		}
21033 
21034 		/*
21035 		 * refrele attach_ill as its not needed anymore.
21036 		 */
21037 		if (attach_ill != NULL) {
21038 			ill_refrele(attach_ill);
21039 			attach_ill = NULL;
21040 		}
21041 
21042 		if (ire == NULL) {
21043 			/*
21044 			 * Multicast loopback and multicast forwarding is
21045 			 * done in ip_wput_ire.
21046 			 *
21047 			 * Mark this packet to make it be delivered to
21048 			 * ip_wput_ire after the new ire has been
21049 			 * created.
21050 			 *
21051 			 * The call to ip_newroute_ipif takes into account
21052 			 * the setsrc reminder. In any case, we take care
21053 			 * of the RTF_MULTIRT flag.
21054 			 */
21055 			mp->b_prev = mp->b_next = NULL;
21056 			if (xmit_ill == NULL ||
21057 			    xmit_ill->ill_ipif_up_count > 0) {
21058 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21059 				    setsrc | RTF_MULTIRT, zoneid, infop);
21060 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21061 				    "ip_wput_end: q %p (%S)", q, "noire");
21062 			} else {
21063 				freemsg(first_mp);
21064 			}
21065 			ipif_refrele(ipif);
21066 			if (xmit_ill != NULL)
21067 				ill_refrele(xmit_ill);
21068 			if (need_decref)
21069 				CONN_DEC_REF(connp);
21070 			return;
21071 		}
21072 
21073 		ipif_refrele(ipif);
21074 		ipif = NULL;
21075 		ASSERT(xmit_ill == NULL);
21076 
21077 		/*
21078 		 * Honor the RTF_SETSRC flag for multicast packets,
21079 		 * if allowed by the setsrc reminder.
21080 		 */
21081 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21082 			ipha->ipha_src = ire->ire_src_addr;
21083 		}
21084 
21085 		/*
21086 		 * Unconditionally force the TTL to 1 for
21087 		 * multirouted multicast packets:
21088 		 * multirouted multicast should not cross
21089 		 * multicast routers.
21090 		 */
21091 		if (ire->ire_flags & RTF_MULTIRT) {
21092 			if (ipha->ipha_ttl > 1) {
21093 				ip2dbg(("ip_wput: forcing multicast "
21094 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21095 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21096 				ipha->ipha_ttl = 1;
21097 			}
21098 		}
21099 	} else {
21100 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
21101 		if ((ire != NULL) && (ire->ire_type &
21102 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21103 			ignore_dontroute = B_TRUE;
21104 			ignore_nexthop = B_TRUE;
21105 		}
21106 		if (ire != NULL) {
21107 			ire_refrele(ire);
21108 			ire = NULL;
21109 		}
21110 		/*
21111 		 * Guard against coming in from arp in which case conn is NULL.
21112 		 * Also guard against non M_DATA with dontroute set but
21113 		 * destined to local, loopback or broadcast addresses.
21114 		 */
21115 		if (connp != NULL && connp->conn_dontroute &&
21116 		    !ignore_dontroute) {
21117 dontroute:
21118 			/*
21119 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21120 			 * routing protocols from seeing false direct
21121 			 * connectivity.
21122 			 */
21123 			ipha->ipha_ttl = 1;
21124 
21125 			/* If suitable ipif not found, drop packet */
21126 			dst_ipif = ipif_lookup_onlink_addr(dst, zoneid, ipst);
21127 			if (dst_ipif == NULL) {
21128 noroute:
21129 				ip1dbg(("ip_wput: no route for dst using"
21130 				    " SO_DONTROUTE\n"));
21131 				BUMP_MIB(&ipst->ips_ip_mib,
21132 				    ipIfStatsOutNoRoutes);
21133 				mp->b_prev = mp->b_next = NULL;
21134 				if (first_mp == NULL)
21135 					first_mp = mp;
21136 				goto drop_pkt;
21137 			} else {
21138 				/*
21139 				 * If suitable ipif has been found, set
21140 				 * xmit_ill to the corresponding
21141 				 * ipif_ill because we'll be using the
21142 				 * send_from_ill logic below.
21143 				 */
21144 				ASSERT(xmit_ill == NULL);
21145 				xmit_ill = dst_ipif->ipif_ill;
21146 				mutex_enter(&xmit_ill->ill_lock);
21147 				if (!ILL_CAN_LOOKUP(xmit_ill)) {
21148 					mutex_exit(&xmit_ill->ill_lock);
21149 					xmit_ill = NULL;
21150 					ipif_refrele(dst_ipif);
21151 					goto noroute;
21152 				}
21153 				ill_refhold_locked(xmit_ill);
21154 				mutex_exit(&xmit_ill->ill_lock);
21155 				ipif_refrele(dst_ipif);
21156 			}
21157 		}
21158 		/*
21159 		 * If we are bound to IPIF_NOFAILOVER address, look for
21160 		 * an IRE_CACHE matching the ill.
21161 		 */
21162 send_from_ill:
21163 		if (attach_ill != NULL) {
21164 			ipif_t	*attach_ipif;
21165 
21166 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21167 
21168 			/*
21169 			 * Check if we need an ire that will not be
21170 			 * looked up by anybody else i.e. HIDDEN.
21171 			 */
21172 			if (ill_is_probeonly(attach_ill)) {
21173 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21174 			}
21175 
21176 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
21177 			if (attach_ipif == NULL) {
21178 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
21179 				goto discard_pkt;
21180 			}
21181 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
21182 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21183 			ipif_refrele(attach_ipif);
21184 		} else if (xmit_ill != NULL) {
21185 			ipif_t *ipif;
21186 
21187 			/*
21188 			 * Mark this packet as originated locally
21189 			 */
21190 			mp->b_prev = mp->b_next = NULL;
21191 
21192 			/*
21193 			 * Could be SO_DONTROUTE case also.
21194 			 * Verify that at least one ipif is up on the ill.
21195 			 */
21196 			if (xmit_ill->ill_ipif_up_count == 0) {
21197 				ip1dbg(("ip_output: xmit_ill %s is down\n",
21198 				    xmit_ill->ill_name));
21199 				goto drop_pkt;
21200 			}
21201 
21202 			ipif = ipif_get_next_ipif(NULL, xmit_ill);
21203 			if (ipif == NULL) {
21204 				ip1dbg(("ip_output: xmit_ill %s NULL ipif\n",
21205 				    xmit_ill->ill_name));
21206 				goto drop_pkt;
21207 			}
21208 
21209 			/*
21210 			 * Look for a ire that is part of the group,
21211 			 * if found use it else call ip_newroute_ipif.
21212 			 * IPCL_ZONEID is not used for matching because
21213 			 * IP_ALLZONES option is valid only when the
21214 			 * ill is accessible from all zones i.e has a
21215 			 * valid ipif in all zones.
21216 			 */
21217 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
21218 			ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21219 			    MBLK_GETLABEL(mp), match_flags, ipst);
21220 			/*
21221 			 * If an ire exists use it or else create
21222 			 * an ire but don't add it to the cache.
21223 			 * Adding an ire may cause issues with
21224 			 * asymmetric routing.
21225 			 * In case of multiroute always act as if
21226 			 * ire does not exist.
21227 			 */
21228 			if (ire == NULL || ire->ire_flags & RTF_MULTIRT) {
21229 				if (ire != NULL)
21230 					ire_refrele(ire);
21231 				ip_newroute_ipif(q, first_mp, ipif,
21232 				    dst, connp, 0, zoneid, infop);
21233 				ipif_refrele(ipif);
21234 				ip1dbg(("ip_output: xmit_ill via %s\n",
21235 				    xmit_ill->ill_name));
21236 				ill_refrele(xmit_ill);
21237 				if (need_decref)
21238 					CONN_DEC_REF(connp);
21239 				return;
21240 			}
21241 			ipif_refrele(ipif);
21242 		} else if (ip_nexthop || (connp != NULL &&
21243 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21244 			if (!ip_nexthop) {
21245 				ip_nexthop = B_TRUE;
21246 				nexthop_addr = connp->conn_nexthop_v4;
21247 			}
21248 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21249 			    MATCH_IRE_GW;
21250 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21251 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21252 		} else {
21253 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp),
21254 			    ipst);
21255 		}
21256 		if (!ire) {
21257 			/*
21258 			 * Make sure we don't load spread if this
21259 			 * is IPIF_NOFAILOVER case.
21260 			 */
21261 			if ((attach_ill != NULL) ||
21262 			    (ip_nexthop && !ignore_nexthop)) {
21263 				if (mctl_present) {
21264 					io = (ipsec_out_t *)first_mp->b_rptr;
21265 					ASSERT(first_mp->b_datap->db_type ==
21266 					    M_CTL);
21267 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21268 				} else {
21269 					ASSERT(mp == first_mp);
21270 					first_mp = allocb(
21271 					    sizeof (ipsec_info_t), BPRI_HI);
21272 					if (first_mp == NULL) {
21273 						first_mp = mp;
21274 						goto discard_pkt;
21275 					}
21276 					first_mp->b_datap->db_type = M_CTL;
21277 					first_mp->b_wptr +=
21278 					    sizeof (ipsec_info_t);
21279 					/* ipsec_out_secure is B_FALSE now */
21280 					bzero(first_mp->b_rptr,
21281 					    sizeof (ipsec_info_t));
21282 					io = (ipsec_out_t *)first_mp->b_rptr;
21283 					io->ipsec_out_type = IPSEC_OUT;
21284 					io->ipsec_out_len =
21285 					    sizeof (ipsec_out_t);
21286 					io->ipsec_out_use_global_policy =
21287 					    B_TRUE;
21288 					io->ipsec_out_ns = ipst->ips_netstack;
21289 					first_mp->b_cont = mp;
21290 					mctl_present = B_TRUE;
21291 				}
21292 				if (attach_ill != NULL) {
21293 					io->ipsec_out_ill_index = attach_ill->
21294 					    ill_phyint->phyint_ifindex;
21295 					io->ipsec_out_attach_if = B_TRUE;
21296 				} else {
21297 					io->ipsec_out_ip_nexthop = ip_nexthop;
21298 					io->ipsec_out_nexthop_addr =
21299 					    nexthop_addr;
21300 				}
21301 			}
21302 noirefound:
21303 			/*
21304 			 * Mark this packet as having originated on
21305 			 * this machine.  This will be noted in
21306 			 * ire_add_then_send, which needs to know
21307 			 * whether to run it back through ip_wput or
21308 			 * ip_rput following successful resolution.
21309 			 */
21310 			mp->b_prev = NULL;
21311 			mp->b_next = NULL;
21312 			ip_newroute(q, first_mp, dst, connp, zoneid, ipst);
21313 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21314 			    "ip_wput_end: q %p (%S)", q, "newroute");
21315 			if (attach_ill != NULL)
21316 				ill_refrele(attach_ill);
21317 			if (xmit_ill != NULL)
21318 				ill_refrele(xmit_ill);
21319 			if (need_decref)
21320 				CONN_DEC_REF(connp);
21321 			return;
21322 		}
21323 	}
21324 
21325 	/* We now know where we are going with it. */
21326 
21327 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21328 	    "ip_wput_end: q %p (%S)", q, "end");
21329 
21330 	/*
21331 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21332 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21333 	 */
21334 	if (ire->ire_flags & RTF_MULTIRT) {
21335 		/*
21336 		 * Force the TTL of multirouted packets if required.
21337 		 * The TTL of such packets is bounded by the
21338 		 * ip_multirt_ttl ndd variable.
21339 		 */
21340 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21341 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21342 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21343 			    "(was %d), dst 0x%08x\n",
21344 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21345 			    ntohl(ire->ire_addr)));
21346 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21347 		}
21348 		/*
21349 		 * At this point, we check to see if there are any pending
21350 		 * unresolved routes. ire_multirt_resolvable()
21351 		 * checks in O(n) that all IRE_OFFSUBNET ire
21352 		 * entries for the packet's destination and
21353 		 * flagged RTF_MULTIRT are currently resolved.
21354 		 * If some remain unresolved, we make a copy
21355 		 * of the current message. It will be used
21356 		 * to initiate additional route resolutions.
21357 		 */
21358 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21359 		    MBLK_GETLABEL(first_mp), ipst);
21360 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21361 		    "multirt_need_resolve %d, first_mp %p\n",
21362 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21363 		if (multirt_need_resolve) {
21364 			copy_mp = copymsg(first_mp);
21365 			if (copy_mp != NULL) {
21366 				MULTIRT_DEBUG_TAG(copy_mp);
21367 			}
21368 		}
21369 	}
21370 
21371 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21372 	/*
21373 	 * Try to resolve another multiroute if
21374 	 * ire_multirt_resolvable() deemed it necessary.
21375 	 * At this point, we need to distinguish
21376 	 * multicasts from other packets. For multicasts,
21377 	 * we call ip_newroute_ipif() and request that both
21378 	 * multirouting and setsrc flags are checked.
21379 	 */
21380 	if (copy_mp != NULL) {
21381 		if (CLASSD(dst)) {
21382 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21383 			if (ipif) {
21384 				ASSERT(infop->ip_opt_ill_index == 0);
21385 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21386 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21387 				ipif_refrele(ipif);
21388 			} else {
21389 				MULTIRT_DEBUG_UNTAG(copy_mp);
21390 				freemsg(copy_mp);
21391 				copy_mp = NULL;
21392 			}
21393 		} else {
21394 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
21395 		}
21396 	}
21397 	if (attach_ill != NULL)
21398 		ill_refrele(attach_ill);
21399 	if (xmit_ill != NULL)
21400 		ill_refrele(xmit_ill);
21401 	if (need_decref)
21402 		CONN_DEC_REF(connp);
21403 	return;
21404 
21405 icmp_parameter_problem:
21406 	/* could not have originated externally */
21407 	ASSERT(mp->b_prev == NULL);
21408 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21409 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21410 		/* it's the IP header length that's in trouble */
21411 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21412 		first_mp = NULL;
21413 	}
21414 
21415 discard_pkt:
21416 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21417 drop_pkt:
21418 	ip1dbg(("ip_wput: dropped packet\n"));
21419 	if (ire != NULL)
21420 		ire_refrele(ire);
21421 	if (need_decref)
21422 		CONN_DEC_REF(connp);
21423 	freemsg(first_mp);
21424 	if (attach_ill != NULL)
21425 		ill_refrele(attach_ill);
21426 	if (xmit_ill != NULL)
21427 		ill_refrele(xmit_ill);
21428 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21429 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21430 }
21431 
21432 /*
21433  * If this is a conn_t queue, then we pass in the conn. This includes the
21434  * zoneid.
21435  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21436  * in which case we use the global zoneid since those are all part of
21437  * the global zone.
21438  */
21439 void
21440 ip_wput(queue_t *q, mblk_t *mp)
21441 {
21442 	if (CONN_Q(q))
21443 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21444 	else
21445 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21446 }
21447 
21448 /*
21449  *
21450  * The following rules must be observed when accessing any ipif or ill
21451  * that has been cached in the conn. Typically conn_nofailover_ill,
21452  * conn_outgoing_ill, conn_multicast_ipif and conn_multicast_ill.
21453  *
21454  * Access: The ipif or ill pointed to from the conn can be accessed under
21455  * the protection of the conn_lock or after it has been refheld under the
21456  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21457  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21458  * The reason for this is that a concurrent unplumb could actually be
21459  * cleaning up these cached pointers by walking the conns and might have
21460  * finished cleaning up the conn in question. The macros check that an
21461  * unplumb has not yet started on the ipif or ill.
21462  *
21463  * Caching: An ipif or ill pointer may be cached in the conn only after
21464  * making sure that an unplumb has not started. So the caching is done
21465  * while holding both the conn_lock and the ill_lock and after using the
21466  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21467  * flag before starting the cleanup of conns.
21468  *
21469  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21470  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21471  * or a reference to the ipif or a reference to an ire that references the
21472  * ipif. An ipif does not change its ill except for failover/failback. Since
21473  * failover/failback happens only after bringing down the ipif and making sure
21474  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
21475  * the above holds.
21476  */
21477 ipif_t *
21478 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21479 {
21480 	ipif_t	*ipif;
21481 	ill_t	*ill;
21482 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21483 
21484 	*err = 0;
21485 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21486 	mutex_enter(&connp->conn_lock);
21487 	ipif = *ipifp;
21488 	if (ipif != NULL) {
21489 		ill = ipif->ipif_ill;
21490 		mutex_enter(&ill->ill_lock);
21491 		if (IPIF_CAN_LOOKUP(ipif)) {
21492 			ipif_refhold_locked(ipif);
21493 			mutex_exit(&ill->ill_lock);
21494 			mutex_exit(&connp->conn_lock);
21495 			rw_exit(&ipst->ips_ill_g_lock);
21496 			return (ipif);
21497 		} else {
21498 			*err = IPIF_LOOKUP_FAILED;
21499 		}
21500 		mutex_exit(&ill->ill_lock);
21501 	}
21502 	mutex_exit(&connp->conn_lock);
21503 	rw_exit(&ipst->ips_ill_g_lock);
21504 	return (NULL);
21505 }
21506 
21507 ill_t *
21508 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21509 {
21510 	ill_t	*ill;
21511 
21512 	*err = 0;
21513 	mutex_enter(&connp->conn_lock);
21514 	ill = *illp;
21515 	if (ill != NULL) {
21516 		mutex_enter(&ill->ill_lock);
21517 		if (ILL_CAN_LOOKUP(ill)) {
21518 			ill_refhold_locked(ill);
21519 			mutex_exit(&ill->ill_lock);
21520 			mutex_exit(&connp->conn_lock);
21521 			return (ill);
21522 		} else {
21523 			*err = ILL_LOOKUP_FAILED;
21524 		}
21525 		mutex_exit(&ill->ill_lock);
21526 	}
21527 	mutex_exit(&connp->conn_lock);
21528 	return (NULL);
21529 }
21530 
21531 static int
21532 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21533 {
21534 	ill_t	*ill;
21535 
21536 	ill = ipif->ipif_ill;
21537 	mutex_enter(&connp->conn_lock);
21538 	mutex_enter(&ill->ill_lock);
21539 	if (IPIF_CAN_LOOKUP(ipif)) {
21540 		*ipifp = ipif;
21541 		mutex_exit(&ill->ill_lock);
21542 		mutex_exit(&connp->conn_lock);
21543 		return (0);
21544 	}
21545 	mutex_exit(&ill->ill_lock);
21546 	mutex_exit(&connp->conn_lock);
21547 	return (IPIF_LOOKUP_FAILED);
21548 }
21549 
21550 /*
21551  * This is called if the outbound datagram needs fragmentation.
21552  *
21553  * NOTE : This function does not ire_refrele the ire argument passed in.
21554  */
21555 static void
21556 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21557     ip_stack_t *ipst)
21558 {
21559 	ipha_t		*ipha;
21560 	mblk_t		*mp;
21561 	uint32_t	v_hlen_tos_len;
21562 	uint32_t	max_frag;
21563 	uint32_t	frag_flag;
21564 	boolean_t	dont_use;
21565 
21566 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21567 		mp = ipsec_mp->b_cont;
21568 	} else {
21569 		mp = ipsec_mp;
21570 	}
21571 
21572 	ipha = (ipha_t *)mp->b_rptr;
21573 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21574 
21575 #ifdef	_BIG_ENDIAN
21576 #define	V_HLEN	(v_hlen_tos_len >> 24)
21577 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21578 #else
21579 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21580 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21581 #endif
21582 
21583 #ifndef SPEED_BEFORE_SAFETY
21584 	/*
21585 	 * Check that ipha_length is consistent with
21586 	 * the mblk length
21587 	 */
21588 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21589 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21590 		    LENGTH, msgdsize(mp)));
21591 		freemsg(ipsec_mp);
21592 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21593 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21594 		    "packet length mismatch");
21595 		return;
21596 	}
21597 #endif
21598 	/*
21599 	 * Don't use frag_flag if pre-built packet or source
21600 	 * routed or if multicast (since multicast packets do not solicit
21601 	 * ICMP "packet too big" messages). Get the values of
21602 	 * max_frag and frag_flag atomically by acquiring the
21603 	 * ire_lock.
21604 	 */
21605 	mutex_enter(&ire->ire_lock);
21606 	max_frag = ire->ire_max_frag;
21607 	frag_flag = ire->ire_frag_flag;
21608 	mutex_exit(&ire->ire_lock);
21609 
21610 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21611 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21612 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21613 
21614 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21615 	    (dont_use ? 0 : frag_flag), zoneid, ipst);
21616 }
21617 
21618 /*
21619  * Used for deciding the MSS size for the upper layer. Thus
21620  * we need to check the outbound policy values in the conn.
21621  */
21622 int
21623 conn_ipsec_length(conn_t *connp)
21624 {
21625 	ipsec_latch_t *ipl;
21626 
21627 	ipl = connp->conn_latch;
21628 	if (ipl == NULL)
21629 		return (0);
21630 
21631 	if (ipl->ipl_out_policy == NULL)
21632 		return (0);
21633 
21634 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21635 }
21636 
21637 /*
21638  * Returns an estimate of the IPsec headers size. This is used if
21639  * we don't want to call into IPsec to get the exact size.
21640  */
21641 int
21642 ipsec_out_extra_length(mblk_t *ipsec_mp)
21643 {
21644 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21645 	ipsec_action_t *a;
21646 
21647 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21648 	if (!io->ipsec_out_secure)
21649 		return (0);
21650 
21651 	a = io->ipsec_out_act;
21652 
21653 	if (a == NULL) {
21654 		ASSERT(io->ipsec_out_policy != NULL);
21655 		a = io->ipsec_out_policy->ipsp_act;
21656 	}
21657 	ASSERT(a != NULL);
21658 
21659 	return (a->ipa_ovhd);
21660 }
21661 
21662 /*
21663  * Returns an estimate of the IPsec headers size. This is used if
21664  * we don't want to call into IPsec to get the exact size.
21665  */
21666 int
21667 ipsec_in_extra_length(mblk_t *ipsec_mp)
21668 {
21669 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21670 	ipsec_action_t *a;
21671 
21672 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21673 
21674 	a = ii->ipsec_in_action;
21675 	return (a == NULL ? 0 : a->ipa_ovhd);
21676 }
21677 
21678 /*
21679  * If there are any source route options, return the true final
21680  * destination. Otherwise, return the destination.
21681  */
21682 ipaddr_t
21683 ip_get_dst(ipha_t *ipha)
21684 {
21685 	ipoptp_t	opts;
21686 	uchar_t		*opt;
21687 	uint8_t		optval;
21688 	uint8_t		optlen;
21689 	ipaddr_t	dst;
21690 	uint32_t off;
21691 
21692 	dst = ipha->ipha_dst;
21693 
21694 	if (IS_SIMPLE_IPH(ipha))
21695 		return (dst);
21696 
21697 	for (optval = ipoptp_first(&opts, ipha);
21698 	    optval != IPOPT_EOL;
21699 	    optval = ipoptp_next(&opts)) {
21700 		opt = opts.ipoptp_cur;
21701 		optlen = opts.ipoptp_len;
21702 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
21703 		switch (optval) {
21704 		case IPOPT_SSRR:
21705 		case IPOPT_LSRR:
21706 			off = opt[IPOPT_OFFSET];
21707 			/*
21708 			 * If one of the conditions is true, it means
21709 			 * end of options and dst already has the right
21710 			 * value.
21711 			 */
21712 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
21713 				off = optlen - IP_ADDR_LEN;
21714 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
21715 			}
21716 			return (dst);
21717 		default:
21718 			break;
21719 		}
21720 	}
21721 
21722 	return (dst);
21723 }
21724 
21725 mblk_t *
21726 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
21727     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
21728 {
21729 	ipsec_out_t	*io;
21730 	mblk_t		*first_mp;
21731 	boolean_t policy_present;
21732 	ip_stack_t	*ipst;
21733 	ipsec_stack_t	*ipss;
21734 
21735 	ASSERT(ire != NULL);
21736 	ipst = ire->ire_ipst;
21737 	ipss = ipst->ips_netstack->netstack_ipsec;
21738 
21739 	first_mp = mp;
21740 	if (mp->b_datap->db_type == M_CTL) {
21741 		io = (ipsec_out_t *)first_mp->b_rptr;
21742 		/*
21743 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
21744 		 *
21745 		 * 1) There is per-socket policy (including cached global
21746 		 *    policy) or a policy on the IP-in-IP tunnel.
21747 		 * 2) There is no per-socket policy, but it is
21748 		 *    a multicast packet that needs to go out
21749 		 *    on a specific interface. This is the case
21750 		 *    where (ip_wput and ip_wput_multicast) attaches
21751 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
21752 		 *
21753 		 * In case (2) we check with global policy to
21754 		 * see if there is a match and set the ill_index
21755 		 * appropriately so that we can lookup the ire
21756 		 * properly in ip_wput_ipsec_out.
21757 		 */
21758 
21759 		/*
21760 		 * ipsec_out_use_global_policy is set to B_FALSE
21761 		 * in ipsec_in_to_out(). Refer to that function for
21762 		 * details.
21763 		 */
21764 		if ((io->ipsec_out_latch == NULL) &&
21765 		    (io->ipsec_out_use_global_policy)) {
21766 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
21767 			    ire, connp, unspec_src, zoneid));
21768 		}
21769 		if (!io->ipsec_out_secure) {
21770 			/*
21771 			 * If this is not a secure packet, drop
21772 			 * the IPSEC_OUT mp and treat it as a clear
21773 			 * packet. This happens when we are sending
21774 			 * a ICMP reply back to a clear packet. See
21775 			 * ipsec_in_to_out() for details.
21776 			 */
21777 			mp = first_mp->b_cont;
21778 			freeb(first_mp);
21779 		}
21780 		return (mp);
21781 	}
21782 	/*
21783 	 * See whether we need to attach a global policy here. We
21784 	 * don't depend on the conn (as it could be null) for deciding
21785 	 * what policy this datagram should go through because it
21786 	 * should have happened in ip_wput if there was some
21787 	 * policy. This normally happens for connections which are not
21788 	 * fully bound preventing us from caching policies in
21789 	 * ip_bind. Packets coming from the TCP listener/global queue
21790 	 * - which are non-hard_bound - could also be affected by
21791 	 * applying policy here.
21792 	 *
21793 	 * If this packet is coming from tcp global queue or listener,
21794 	 * we will be applying policy here.  This may not be *right*
21795 	 * if these packets are coming from the detached connection as
21796 	 * it could have gone in clear before. This happens only if a
21797 	 * TCP connection started when there is no policy and somebody
21798 	 * added policy before it became detached. Thus packets of the
21799 	 * detached connection could go out secure and the other end
21800 	 * would drop it because it will be expecting in clear. The
21801 	 * converse is not true i.e if somebody starts a TCP
21802 	 * connection and deletes the policy, all the packets will
21803 	 * still go out with the policy that existed before deleting
21804 	 * because ip_unbind sends up policy information which is used
21805 	 * by TCP on subsequent ip_wputs. The right solution is to fix
21806 	 * TCP to attach a dummy IPSEC_OUT and set
21807 	 * ipsec_out_use_global_policy to B_FALSE. As this might
21808 	 * affect performance for normal cases, we are not doing it.
21809 	 * Thus, set policy before starting any TCP connections.
21810 	 *
21811 	 * NOTE - We might apply policy even for a hard bound connection
21812 	 * - for which we cached policy in ip_bind - if somebody added
21813 	 * global policy after we inherited the policy in ip_bind.
21814 	 * This means that the packets that were going out in clear
21815 	 * previously would start going secure and hence get dropped
21816 	 * on the other side. To fix this, TCP attaches a dummy
21817 	 * ipsec_out and make sure that we don't apply global policy.
21818 	 */
21819 	if (ipha != NULL)
21820 		policy_present = ipss->ipsec_outbound_v4_policy_present;
21821 	else
21822 		policy_present = ipss->ipsec_outbound_v6_policy_present;
21823 	if (!policy_present)
21824 		return (mp);
21825 
21826 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
21827 	    zoneid));
21828 }
21829 
21830 ire_t *
21831 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
21832 {
21833 	ipaddr_t addr;
21834 	ire_t *save_ire;
21835 	irb_t *irb;
21836 	ill_group_t *illgrp;
21837 	int	err;
21838 
21839 	save_ire = ire;
21840 	addr = ire->ire_addr;
21841 
21842 	ASSERT(ire->ire_type == IRE_BROADCAST);
21843 
21844 	illgrp = connp->conn_outgoing_ill->ill_group;
21845 	if (illgrp == NULL) {
21846 		*conn_outgoing_ill = conn_get_held_ill(connp,
21847 		    &connp->conn_outgoing_ill, &err);
21848 		if (err == ILL_LOOKUP_FAILED) {
21849 			ire_refrele(save_ire);
21850 			return (NULL);
21851 		}
21852 		return (save_ire);
21853 	}
21854 	/*
21855 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
21856 	 * If it is part of the group, we need to send on the ire
21857 	 * that has been cleared of IRE_MARK_NORECV and that belongs
21858 	 * to this group. This is okay as IP_BOUND_IF really means
21859 	 * any ill in the group. We depend on the fact that the
21860 	 * first ire in the group is always cleared of IRE_MARK_NORECV
21861 	 * if such an ire exists. This is possible only if you have
21862 	 * at least one ill in the group that has not failed.
21863 	 *
21864 	 * First get to the ire that matches the address and group.
21865 	 *
21866 	 * We don't look for an ire with a matching zoneid because a given zone
21867 	 * won't always have broadcast ires on all ills in the group.
21868 	 */
21869 	irb = ire->ire_bucket;
21870 	rw_enter(&irb->irb_lock, RW_READER);
21871 	if (ire->ire_marks & IRE_MARK_NORECV) {
21872 		/*
21873 		 * If the current zone only has an ire broadcast for this
21874 		 * address marked NORECV, the ire we want is ahead in the
21875 		 * bucket, so we look it up deliberately ignoring the zoneid.
21876 		 */
21877 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
21878 			if (ire->ire_addr != addr)
21879 				continue;
21880 			/* skip over deleted ires */
21881 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
21882 				continue;
21883 		}
21884 	}
21885 	while (ire != NULL) {
21886 		/*
21887 		 * If a new interface is coming up, we could end up
21888 		 * seeing the loopback ire and the non-loopback ire
21889 		 * may not have been added yet. So check for ire_stq
21890 		 */
21891 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
21892 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
21893 			break;
21894 		}
21895 		ire = ire->ire_next;
21896 	}
21897 	if (ire != NULL && ire->ire_addr == addr &&
21898 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
21899 		IRE_REFHOLD(ire);
21900 		rw_exit(&irb->irb_lock);
21901 		ire_refrele(save_ire);
21902 		*conn_outgoing_ill = ire_to_ill(ire);
21903 		/*
21904 		 * Refhold the ill to make the conn_outgoing_ill
21905 		 * independent of the ire. ip_wput_ire goes in a loop
21906 		 * and may refrele the ire. Since we have an ire at this
21907 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
21908 		 */
21909 		ill_refhold(*conn_outgoing_ill);
21910 		return (ire);
21911 	}
21912 	rw_exit(&irb->irb_lock);
21913 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
21914 	/*
21915 	 * If we can't find a suitable ire, return the original ire.
21916 	 */
21917 	return (save_ire);
21918 }
21919 
21920 /*
21921  * This function does the ire_refrele of the ire passed in as the
21922  * argument. As this function looks up more ires i.e broadcast ires,
21923  * it needs to REFRELE them. Currently, for simplicity we don't
21924  * differentiate the one passed in and looked up here. We always
21925  * REFRELE.
21926  * IPQoS Notes:
21927  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
21928  * IPsec packets are done in ipsec_out_process.
21929  *
21930  */
21931 void
21932 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
21933     zoneid_t zoneid)
21934 {
21935 	ipha_t		*ipha;
21936 #define	rptr	((uchar_t *)ipha)
21937 	queue_t		*stq;
21938 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
21939 	uint32_t	v_hlen_tos_len;
21940 	uint32_t	ttl_protocol;
21941 	ipaddr_t	src;
21942 	ipaddr_t	dst;
21943 	uint32_t	cksum;
21944 	ipaddr_t	orig_src;
21945 	ire_t		*ire1;
21946 	mblk_t		*next_mp;
21947 	uint_t		hlen;
21948 	uint16_t	*up;
21949 	uint32_t	max_frag = ire->ire_max_frag;
21950 	ill_t		*ill = ire_to_ill(ire);
21951 	int		clusterwide;
21952 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
21953 	int		ipsec_len;
21954 	mblk_t		*first_mp;
21955 	ipsec_out_t	*io;
21956 	boolean_t	conn_dontroute;		/* conn value for multicast */
21957 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
21958 	boolean_t	multicast_forward;	/* Should we forward ? */
21959 	boolean_t	unspec_src;
21960 	ill_t		*conn_outgoing_ill = NULL;
21961 	ill_t		*ire_ill;
21962 	ill_t		*ire1_ill;
21963 	ill_t		*out_ill;
21964 	uint32_t 	ill_index = 0;
21965 	boolean_t	multirt_send = B_FALSE;
21966 	int		err;
21967 	ipxmit_state_t	pktxmit_state;
21968 	ip_stack_t	*ipst = ire->ire_ipst;
21969 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
21970 
21971 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
21972 	    "ip_wput_ire_start: q %p", q);
21973 
21974 	multicast_forward = B_FALSE;
21975 	unspec_src = (connp != NULL && connp->conn_unspec_src);
21976 
21977 	if (ire->ire_flags & RTF_MULTIRT) {
21978 		/*
21979 		 * Multirouting case. The bucket where ire is stored
21980 		 * probably holds other RTF_MULTIRT flagged ire
21981 		 * to the destination. In this call to ip_wput_ire,
21982 		 * we attempt to send the packet through all
21983 		 * those ires. Thus, we first ensure that ire is the
21984 		 * first RTF_MULTIRT ire in the bucket,
21985 		 * before walking the ire list.
21986 		 */
21987 		ire_t *first_ire;
21988 		irb_t *irb = ire->ire_bucket;
21989 		ASSERT(irb != NULL);
21990 
21991 		/* Make sure we do not omit any multiroute ire. */
21992 		IRB_REFHOLD(irb);
21993 		for (first_ire = irb->irb_ire;
21994 		    first_ire != NULL;
21995 		    first_ire = first_ire->ire_next) {
21996 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
21997 			    (first_ire->ire_addr == ire->ire_addr) &&
21998 			    !(first_ire->ire_marks &
21999 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
22000 				break;
22001 			}
22002 		}
22003 
22004 		if ((first_ire != NULL) && (first_ire != ire)) {
22005 			IRE_REFHOLD(first_ire);
22006 			ire_refrele(ire);
22007 			ire = first_ire;
22008 			ill = ire_to_ill(ire);
22009 		}
22010 		IRB_REFRELE(irb);
22011 	}
22012 
22013 	/*
22014 	 * conn_outgoing_ill variable is used only in the broadcast loop.
22015 	 * for performance we don't grab the mutexs in the fastpath
22016 	 */
22017 	if ((connp != NULL) &&
22018 	    (ire->ire_type == IRE_BROADCAST) &&
22019 	    ((connp->conn_nofailover_ill != NULL) ||
22020 	    (connp->conn_outgoing_ill != NULL))) {
22021 		/*
22022 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
22023 		 * option. So, see if this endpoint is bound to a
22024 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
22025 		 * that if the interface is failed, we will still send
22026 		 * the packet on the same ill which is what we want.
22027 		 */
22028 		conn_outgoing_ill = conn_get_held_ill(connp,
22029 		    &connp->conn_nofailover_ill, &err);
22030 		if (err == ILL_LOOKUP_FAILED) {
22031 			ire_refrele(ire);
22032 			freemsg(mp);
22033 			return;
22034 		}
22035 		if (conn_outgoing_ill == NULL) {
22036 			/*
22037 			 * Choose a good ill in the group to send the
22038 			 * packets on.
22039 			 */
22040 			ire = conn_set_outgoing_ill(connp, ire,
22041 			    &conn_outgoing_ill);
22042 			if (ire == NULL) {
22043 				freemsg(mp);
22044 				return;
22045 			}
22046 		}
22047 	}
22048 
22049 	if (mp->b_datap->db_type != M_CTL) {
22050 		ipha = (ipha_t *)mp->b_rptr;
22051 	} else {
22052 		io = (ipsec_out_t *)mp->b_rptr;
22053 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22054 		ASSERT(zoneid == io->ipsec_out_zoneid);
22055 		ASSERT(zoneid != ALL_ZONES);
22056 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22057 		dst = ipha->ipha_dst;
22058 		/*
22059 		 * For the multicast case, ipsec_out carries conn_dontroute and
22060 		 * conn_multicast_loop as conn may not be available here. We
22061 		 * need this for multicast loopback and forwarding which is done
22062 		 * later in the code.
22063 		 */
22064 		if (CLASSD(dst)) {
22065 			conn_dontroute = io->ipsec_out_dontroute;
22066 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22067 			/*
22068 			 * If conn_dontroute is not set or conn_multicast_loop
22069 			 * is set, we need to do forwarding/loopback. For
22070 			 * datagrams from ip_wput_multicast, conn_dontroute is
22071 			 * set to B_TRUE and conn_multicast_loop is set to
22072 			 * B_FALSE so that we neither do forwarding nor
22073 			 * loopback.
22074 			 */
22075 			if (!conn_dontroute || conn_multicast_loop)
22076 				multicast_forward = B_TRUE;
22077 		}
22078 	}
22079 
22080 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22081 	    ire->ire_zoneid != ALL_ZONES) {
22082 		/*
22083 		 * When a zone sends a packet to another zone, we try to deliver
22084 		 * the packet under the same conditions as if the destination
22085 		 * was a real node on the network. To do so, we look for a
22086 		 * matching route in the forwarding table.
22087 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22088 		 * ip_newroute() does.
22089 		 * Note that IRE_LOCAL are special, since they are used
22090 		 * when the zoneid doesn't match in some cases. This means that
22091 		 * we need to handle ipha_src differently since ire_src_addr
22092 		 * belongs to the receiving zone instead of the sending zone.
22093 		 * When ip_restrict_interzone_loopback is set, then
22094 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22095 		 * for loopback between zones when the logical "Ethernet" would
22096 		 * have looped them back.
22097 		 */
22098 		ire_t *src_ire;
22099 
22100 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22101 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22102 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22103 		if (src_ire != NULL &&
22104 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22105 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22106 		    ire_local_same_ill_group(ire, src_ire))) {
22107 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22108 				ipha->ipha_src = src_ire->ire_src_addr;
22109 			ire_refrele(src_ire);
22110 		} else {
22111 			ire_refrele(ire);
22112 			if (conn_outgoing_ill != NULL)
22113 				ill_refrele(conn_outgoing_ill);
22114 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22115 			if (src_ire != NULL) {
22116 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22117 					ire_refrele(src_ire);
22118 					freemsg(mp);
22119 					return;
22120 				}
22121 				ire_refrele(src_ire);
22122 			}
22123 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22124 				/* Failed */
22125 				freemsg(mp);
22126 				return;
22127 			}
22128 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22129 			    ipst);
22130 			return;
22131 		}
22132 	}
22133 
22134 	if (mp->b_datap->db_type == M_CTL ||
22135 	    ipss->ipsec_outbound_v4_policy_present) {
22136 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22137 		    unspec_src, zoneid);
22138 		if (mp == NULL) {
22139 			ire_refrele(ire);
22140 			if (conn_outgoing_ill != NULL)
22141 				ill_refrele(conn_outgoing_ill);
22142 			return;
22143 		}
22144 	}
22145 
22146 	first_mp = mp;
22147 	ipsec_len = 0;
22148 
22149 	if (first_mp->b_datap->db_type == M_CTL) {
22150 		io = (ipsec_out_t *)first_mp->b_rptr;
22151 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22152 		mp = first_mp->b_cont;
22153 		ipsec_len = ipsec_out_extra_length(first_mp);
22154 		ASSERT(ipsec_len >= 0);
22155 		/* We already picked up the zoneid from the M_CTL above */
22156 		ASSERT(zoneid == io->ipsec_out_zoneid);
22157 		ASSERT(zoneid != ALL_ZONES);
22158 
22159 		/*
22160 		 * Drop M_CTL here if IPsec processing is not needed.
22161 		 * (Non-IPsec use of M_CTL extracted any information it
22162 		 * needed above).
22163 		 */
22164 		if (ipsec_len == 0) {
22165 			freeb(first_mp);
22166 			first_mp = mp;
22167 		}
22168 	}
22169 
22170 	/*
22171 	 * Fast path for ip_wput_ire
22172 	 */
22173 
22174 	ipha = (ipha_t *)mp->b_rptr;
22175 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22176 	dst = ipha->ipha_dst;
22177 
22178 	/*
22179 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22180 	 * if the socket is a SOCK_RAW type. The transport checksum should
22181 	 * be provided in the pre-built packet, so we don't need to compute it.
22182 	 * Also, other application set flags, like DF, should not be altered.
22183 	 * Other transport MUST pass down zero.
22184 	 */
22185 	ip_hdr_included = ipha->ipha_ident;
22186 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22187 
22188 	if (CLASSD(dst)) {
22189 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22190 		    ntohl(dst),
22191 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22192 		    ntohl(ire->ire_addr)));
22193 	}
22194 
22195 /* Macros to extract header fields from data already in registers */
22196 #ifdef	_BIG_ENDIAN
22197 #define	V_HLEN	(v_hlen_tos_len >> 24)
22198 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22199 #define	PROTO	(ttl_protocol & 0xFF)
22200 #else
22201 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22202 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22203 #define	PROTO	(ttl_protocol >> 8)
22204 #endif
22205 
22206 
22207 	orig_src = src = ipha->ipha_src;
22208 	/* (The loop back to "another" is explained down below.) */
22209 another:;
22210 	/*
22211 	 * Assign an ident value for this packet.  We assign idents on
22212 	 * a per destination basis out of the IRE.  There could be
22213 	 * other threads targeting the same destination, so we have to
22214 	 * arrange for a atomic increment.  Note that we use a 32-bit
22215 	 * atomic add because it has better performance than its
22216 	 * 16-bit sibling.
22217 	 *
22218 	 * If running in cluster mode and if the source address
22219 	 * belongs to a replicated service then vector through
22220 	 * cl_inet_ipident vector to allocate ip identifier
22221 	 * NOTE: This is a contract private interface with the
22222 	 * clustering group.
22223 	 */
22224 	clusterwide = 0;
22225 	if (cl_inet_ipident) {
22226 		ASSERT(cl_inet_isclusterwide);
22227 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
22228 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
22229 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
22230 			    AF_INET, (uint8_t *)(uintptr_t)src,
22231 			    (uint8_t *)(uintptr_t)dst);
22232 			clusterwide = 1;
22233 		}
22234 	}
22235 	if (!clusterwide) {
22236 		ipha->ipha_ident =
22237 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22238 	}
22239 
22240 #ifndef _BIG_ENDIAN
22241 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22242 #endif
22243 
22244 	/*
22245 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22246 	 * This is needed to obey conn_unspec_src when packets go through
22247 	 * ip_newroute + arp.
22248 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22249 	 */
22250 	if (src == INADDR_ANY && !unspec_src) {
22251 		/*
22252 		 * Assign the appropriate source address from the IRE if none
22253 		 * was specified.
22254 		 */
22255 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22256 
22257 		/*
22258 		 * With IP multipathing, broadcast packets are sent on the ire
22259 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
22260 		 * the group. However, this ire might not be in the same zone so
22261 		 * we can't always use its source address. We look for a
22262 		 * broadcast ire in the same group and in the right zone.
22263 		 */
22264 		if (ire->ire_type == IRE_BROADCAST &&
22265 		    ire->ire_zoneid != zoneid) {
22266 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
22267 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
22268 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
22269 			if (src_ire != NULL) {
22270 				src = src_ire->ire_src_addr;
22271 				ire_refrele(src_ire);
22272 			} else {
22273 				ire_refrele(ire);
22274 				if (conn_outgoing_ill != NULL)
22275 					ill_refrele(conn_outgoing_ill);
22276 				freemsg(first_mp);
22277 				if (ill != NULL) {
22278 					BUMP_MIB(ill->ill_ip_mib,
22279 					    ipIfStatsOutDiscards);
22280 				} else {
22281 					BUMP_MIB(&ipst->ips_ip_mib,
22282 					    ipIfStatsOutDiscards);
22283 				}
22284 				return;
22285 			}
22286 		} else {
22287 			src = ire->ire_src_addr;
22288 		}
22289 
22290 		if (connp == NULL) {
22291 			ip1dbg(("ip_wput_ire: no connp and no src "
22292 			    "address for dst 0x%x, using src 0x%x\n",
22293 			    ntohl(dst),
22294 			    ntohl(src)));
22295 		}
22296 		ipha->ipha_src = src;
22297 	}
22298 	stq = ire->ire_stq;
22299 
22300 	/*
22301 	 * We only allow ire chains for broadcasts since there will
22302 	 * be multiple IRE_CACHE entries for the same multicast
22303 	 * address (one per ipif).
22304 	 */
22305 	next_mp = NULL;
22306 
22307 	/* broadcast packet */
22308 	if (ire->ire_type == IRE_BROADCAST)
22309 		goto broadcast;
22310 
22311 	/* loopback ? */
22312 	if (stq == NULL)
22313 		goto nullstq;
22314 
22315 	/* The ill_index for outbound ILL */
22316 	ill_index = Q_TO_INDEX(stq);
22317 
22318 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22319 	ttl_protocol = ((uint16_t *)ipha)[4];
22320 
22321 	/* pseudo checksum (do it in parts for IP header checksum) */
22322 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22323 
22324 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22325 		queue_t *dev_q = stq->q_next;
22326 
22327 		/* flow controlled */
22328 		if ((dev_q->q_next || dev_q->q_first) &&
22329 		    !canput(dev_q))
22330 			goto blocked;
22331 		if ((PROTO == IPPROTO_UDP) &&
22332 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22333 			hlen = (V_HLEN & 0xF) << 2;
22334 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22335 			if (*up != 0) {
22336 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22337 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22338 				/* Software checksum? */
22339 				if (DB_CKSUMFLAGS(mp) == 0) {
22340 					IP_STAT(ipst, ip_out_sw_cksum);
22341 					IP_STAT_UPDATE(ipst,
22342 					    ip_udp_out_sw_cksum_bytes,
22343 					    LENGTH - hlen);
22344 				}
22345 			}
22346 		}
22347 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22348 		hlen = (V_HLEN & 0xF) << 2;
22349 		if (PROTO == IPPROTO_TCP) {
22350 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22351 			/*
22352 			 * The packet header is processed once and for all, even
22353 			 * in the multirouting case. We disable hardware
22354 			 * checksum if the packet is multirouted, as it will be
22355 			 * replicated via several interfaces, and not all of
22356 			 * them may have this capability.
22357 			 */
22358 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22359 			    LENGTH, max_frag, ipsec_len, cksum);
22360 			/* Software checksum? */
22361 			if (DB_CKSUMFLAGS(mp) == 0) {
22362 				IP_STAT(ipst, ip_out_sw_cksum);
22363 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22364 				    LENGTH - hlen);
22365 			}
22366 		} else {
22367 			sctp_hdr_t	*sctph;
22368 
22369 			ASSERT(PROTO == IPPROTO_SCTP);
22370 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22371 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22372 			/*
22373 			 * Zero out the checksum field to ensure proper
22374 			 * checksum calculation.
22375 			 */
22376 			sctph->sh_chksum = 0;
22377 #ifdef	DEBUG
22378 			if (!skip_sctp_cksum)
22379 #endif
22380 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22381 		}
22382 	}
22383 
22384 	/*
22385 	 * If this is a multicast packet and originated from ip_wput
22386 	 * we need to do loopback and forwarding checks. If it comes
22387 	 * from ip_wput_multicast, we SHOULD not do this.
22388 	 */
22389 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22390 
22391 	/* checksum */
22392 	cksum += ttl_protocol;
22393 
22394 	/* fragment the packet */
22395 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22396 		goto fragmentit;
22397 	/*
22398 	 * Don't use frag_flag if packet is pre-built or source
22399 	 * routed or if multicast (since multicast packets do
22400 	 * not solicit ICMP "packet too big" messages).
22401 	 */
22402 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22403 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22404 	    !ip_source_route_included(ipha)) &&
22405 	    !CLASSD(ipha->ipha_dst))
22406 		ipha->ipha_fragment_offset_and_flags |=
22407 		    htons(ire->ire_frag_flag);
22408 
22409 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22410 		/* calculate IP header checksum */
22411 		cksum += ipha->ipha_ident;
22412 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22413 		cksum += ipha->ipha_fragment_offset_and_flags;
22414 
22415 		/* IP options present */
22416 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22417 		if (hlen)
22418 			goto checksumoptions;
22419 
22420 		/* calculate hdr checksum */
22421 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22422 		cksum = ~(cksum + (cksum >> 16));
22423 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22424 	}
22425 	if (ipsec_len != 0) {
22426 		/*
22427 		 * We will do the rest of the processing after
22428 		 * we come back from IPsec in ip_wput_ipsec_out().
22429 		 */
22430 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22431 
22432 		io = (ipsec_out_t *)first_mp->b_rptr;
22433 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
22434 		    ill_phyint->phyint_ifindex;
22435 
22436 		ipsec_out_process(q, first_mp, ire, ill_index);
22437 		ire_refrele(ire);
22438 		if (conn_outgoing_ill != NULL)
22439 			ill_refrele(conn_outgoing_ill);
22440 		return;
22441 	}
22442 
22443 	/*
22444 	 * In most cases, the emission loop below is entered only
22445 	 * once. Only in the case where the ire holds the
22446 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22447 	 * flagged ires in the bucket, and send the packet
22448 	 * through all crossed RTF_MULTIRT routes.
22449 	 */
22450 	if (ire->ire_flags & RTF_MULTIRT) {
22451 		multirt_send = B_TRUE;
22452 	}
22453 	do {
22454 		if (multirt_send) {
22455 			irb_t *irb;
22456 			/*
22457 			 * We are in a multiple send case, need to get
22458 			 * the next ire and make a duplicate of the packet.
22459 			 * ire1 holds here the next ire to process in the
22460 			 * bucket. If multirouting is expected,
22461 			 * any non-RTF_MULTIRT ire that has the
22462 			 * right destination address is ignored.
22463 			 */
22464 			irb = ire->ire_bucket;
22465 			ASSERT(irb != NULL);
22466 
22467 			IRB_REFHOLD(irb);
22468 			for (ire1 = ire->ire_next;
22469 			    ire1 != NULL;
22470 			    ire1 = ire1->ire_next) {
22471 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22472 					continue;
22473 				if (ire1->ire_addr != ire->ire_addr)
22474 					continue;
22475 				if (ire1->ire_marks &
22476 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
22477 					continue;
22478 
22479 				/* Got one */
22480 				IRE_REFHOLD(ire1);
22481 				break;
22482 			}
22483 			IRB_REFRELE(irb);
22484 
22485 			if (ire1 != NULL) {
22486 				next_mp = copyb(mp);
22487 				if ((next_mp == NULL) ||
22488 				    ((mp->b_cont != NULL) &&
22489 				    ((next_mp->b_cont =
22490 				    dupmsg(mp->b_cont)) == NULL))) {
22491 					freemsg(next_mp);
22492 					next_mp = NULL;
22493 					ire_refrele(ire1);
22494 					ire1 = NULL;
22495 				}
22496 			}
22497 
22498 			/* Last multiroute ire; don't loop anymore. */
22499 			if (ire1 == NULL) {
22500 				multirt_send = B_FALSE;
22501 			}
22502 		}
22503 
22504 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22505 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22506 		    mblk_t *, mp);
22507 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22508 		    ipst->ips_ipv4firewall_physical_out,
22509 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, ipst);
22510 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22511 		if (mp == NULL)
22512 			goto release_ire_and_ill;
22513 
22514 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22515 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22516 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE);
22517 		if ((pktxmit_state == SEND_FAILED) ||
22518 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22519 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22520 			    "- packet dropped\n"));
22521 release_ire_and_ill:
22522 			ire_refrele(ire);
22523 			if (next_mp != NULL) {
22524 				freemsg(next_mp);
22525 				ire_refrele(ire1);
22526 			}
22527 			if (conn_outgoing_ill != NULL)
22528 				ill_refrele(conn_outgoing_ill);
22529 			return;
22530 		}
22531 
22532 		if (CLASSD(dst)) {
22533 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22534 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22535 			    LENGTH);
22536 		}
22537 
22538 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22539 		    "ip_wput_ire_end: q %p (%S)",
22540 		    q, "last copy out");
22541 		IRE_REFRELE(ire);
22542 
22543 		if (multirt_send) {
22544 			ASSERT(ire1);
22545 			/*
22546 			 * Proceed with the next RTF_MULTIRT ire,
22547 			 * Also set up the send-to queue accordingly.
22548 			 */
22549 			ire = ire1;
22550 			ire1 = NULL;
22551 			stq = ire->ire_stq;
22552 			mp = next_mp;
22553 			next_mp = NULL;
22554 			ipha = (ipha_t *)mp->b_rptr;
22555 			ill_index = Q_TO_INDEX(stq);
22556 			ill = (ill_t *)stq->q_ptr;
22557 		}
22558 	} while (multirt_send);
22559 	if (conn_outgoing_ill != NULL)
22560 		ill_refrele(conn_outgoing_ill);
22561 	return;
22562 
22563 	/*
22564 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22565 	 */
22566 broadcast:
22567 	{
22568 		/*
22569 		 * To avoid broadcast storms, we usually set the TTL to 1 for
22570 		 * broadcasts.  However, if SO_DONTROUTE isn't set, this value
22571 		 * can be overridden stack-wide through the ip_broadcast_ttl
22572 		 * ndd tunable, or on a per-connection basis through the
22573 		 * IP_BROADCAST_TTL socket option.
22574 		 *
22575 		 * In the event that we are replying to incoming ICMP packets,
22576 		 * connp could be NULL.
22577 		 */
22578 		ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22579 		if (connp != NULL) {
22580 			if (connp->conn_dontroute)
22581 				ipha->ipha_ttl = 1;
22582 			else if (connp->conn_broadcast_ttl != 0)
22583 				ipha->ipha_ttl = connp->conn_broadcast_ttl;
22584 		}
22585 
22586 		/*
22587 		 * Note that we are not doing a IRB_REFHOLD here.
22588 		 * Actually we don't care if the list changes i.e
22589 		 * if somebody deletes an IRE from the list while
22590 		 * we drop the lock, the next time we come around
22591 		 * ire_next will be NULL and hence we won't send
22592 		 * out multiple copies which is fine.
22593 		 */
22594 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22595 		ire1 = ire->ire_next;
22596 		if (conn_outgoing_ill != NULL) {
22597 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22598 				ASSERT(ire1 == ire->ire_next);
22599 				if (ire1 != NULL && ire1->ire_addr == dst) {
22600 					ire_refrele(ire);
22601 					ire = ire1;
22602 					IRE_REFHOLD(ire);
22603 					ire1 = ire->ire_next;
22604 					continue;
22605 				}
22606 				rw_exit(&ire->ire_bucket->irb_lock);
22607 				/* Did not find a matching ill */
22608 				ip1dbg(("ip_wput_ire: broadcast with no "
22609 				    "matching IP_BOUND_IF ill %s dst %x\n",
22610 				    conn_outgoing_ill->ill_name, dst));
22611 				freemsg(first_mp);
22612 				if (ire != NULL)
22613 					ire_refrele(ire);
22614 				ill_refrele(conn_outgoing_ill);
22615 				return;
22616 			}
22617 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22618 			/*
22619 			 * If the next IRE has the same address and is not one
22620 			 * of the two copies that we need to send, try to see
22621 			 * whether this copy should be sent at all. This
22622 			 * assumes that we insert loopbacks first and then
22623 			 * non-loopbacks. This is acheived by inserting the
22624 			 * loopback always before non-loopback.
22625 			 * This is used to send a single copy of a broadcast
22626 			 * packet out all physical interfaces that have an
22627 			 * matching IRE_BROADCAST while also looping
22628 			 * back one copy (to ip_wput_local) for each
22629 			 * matching physical interface. However, we avoid
22630 			 * sending packets out different logical that match by
22631 			 * having ipif_up/ipif_down supress duplicate
22632 			 * IRE_BROADCASTS.
22633 			 *
22634 			 * This feature is currently used to get broadcasts
22635 			 * sent to multiple interfaces, when the broadcast
22636 			 * address being used applies to multiple interfaces.
22637 			 * For example, a whole net broadcast will be
22638 			 * replicated on every connected subnet of
22639 			 * the target net.
22640 			 *
22641 			 * Each zone has its own set of IRE_BROADCASTs, so that
22642 			 * we're able to distribute inbound packets to multiple
22643 			 * zones who share a broadcast address. We avoid looping
22644 			 * back outbound packets in different zones but on the
22645 			 * same ill, as the application would see duplicates.
22646 			 *
22647 			 * If the interfaces are part of the same group,
22648 			 * we would want to send only one copy out for
22649 			 * whole group.
22650 			 *
22651 			 * This logic assumes that ire_add_v4() groups the
22652 			 * IRE_BROADCAST entries so that those with the same
22653 			 * ire_addr and ill_group are kept together.
22654 			 */
22655 			ire_ill = ire->ire_ipif->ipif_ill;
22656 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
22657 				if (ire_ill->ill_group != NULL &&
22658 				    (ire->ire_marks & IRE_MARK_NORECV)) {
22659 					/*
22660 					 * If the current zone only has an ire
22661 					 * broadcast for this address marked
22662 					 * NORECV, the ire we want is ahead in
22663 					 * the bucket, so we look it up
22664 					 * deliberately ignoring the zoneid.
22665 					 */
22666 					for (ire1 = ire->ire_bucket->irb_ire;
22667 					    ire1 != NULL;
22668 					    ire1 = ire1->ire_next) {
22669 						ire1_ill =
22670 						    ire1->ire_ipif->ipif_ill;
22671 						if (ire1->ire_addr != dst)
22672 							continue;
22673 						/* skip over the current ire */
22674 						if (ire1 == ire)
22675 							continue;
22676 						/* skip over deleted ires */
22677 						if (ire1->ire_marks &
22678 						    IRE_MARK_CONDEMNED)
22679 							continue;
22680 						/*
22681 						 * non-loopback ire in our
22682 						 * group: use it for the next
22683 						 * pass in the loop
22684 						 */
22685 						if (ire1->ire_stq != NULL &&
22686 						    ire1_ill->ill_group ==
22687 						    ire_ill->ill_group)
22688 							break;
22689 					}
22690 				}
22691 			} else {
22692 				while (ire1 != NULL && ire1->ire_addr == dst) {
22693 					ire1_ill = ire1->ire_ipif->ipif_ill;
22694 					/*
22695 					 * We can have two broadcast ires on the
22696 					 * same ill in different zones; here
22697 					 * we'll send a copy of the packet on
22698 					 * each ill and the fanout code will
22699 					 * call conn_wantpacket() to check that
22700 					 * the zone has the broadcast address
22701 					 * configured on the ill. If the two
22702 					 * ires are in the same group we only
22703 					 * send one copy up.
22704 					 */
22705 					if (ire1_ill != ire_ill &&
22706 					    (ire1_ill->ill_group == NULL ||
22707 					    ire_ill->ill_group == NULL ||
22708 					    ire1_ill->ill_group !=
22709 					    ire_ill->ill_group)) {
22710 						break;
22711 					}
22712 					ire1 = ire1->ire_next;
22713 				}
22714 			}
22715 		}
22716 		ASSERT(multirt_send == B_FALSE);
22717 		if (ire1 != NULL && ire1->ire_addr == dst) {
22718 			if ((ire->ire_flags & RTF_MULTIRT) &&
22719 			    (ire1->ire_flags & RTF_MULTIRT)) {
22720 				/*
22721 				 * We are in the multirouting case.
22722 				 * The message must be sent at least
22723 				 * on both ires. These ires have been
22724 				 * inserted AFTER the standard ones
22725 				 * in ip_rt_add(). There are thus no
22726 				 * other ire entries for the destination
22727 				 * address in the rest of the bucket
22728 				 * that do not have the RTF_MULTIRT
22729 				 * flag. We don't process a copy
22730 				 * of the message here. This will be
22731 				 * done in the final sending loop.
22732 				 */
22733 				multirt_send = B_TRUE;
22734 			} else {
22735 				next_mp = ip_copymsg(first_mp);
22736 				if (next_mp != NULL)
22737 					IRE_REFHOLD(ire1);
22738 			}
22739 		}
22740 		rw_exit(&ire->ire_bucket->irb_lock);
22741 	}
22742 
22743 	if (stq) {
22744 		/*
22745 		 * A non-NULL send-to queue means this packet is going
22746 		 * out of this machine.
22747 		 */
22748 		out_ill = (ill_t *)stq->q_ptr;
22749 
22750 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
22751 		ttl_protocol = ((uint16_t *)ipha)[4];
22752 		/*
22753 		 * We accumulate the pseudo header checksum in cksum.
22754 		 * This is pretty hairy code, so watch close.  One
22755 		 * thing to keep in mind is that UDP and TCP have
22756 		 * stored their respective datagram lengths in their
22757 		 * checksum fields.  This lines things up real nice.
22758 		 */
22759 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22760 		    (src >> 16) + (src & 0xFFFF);
22761 		/*
22762 		 * We assume the udp checksum field contains the
22763 		 * length, so to compute the pseudo header checksum,
22764 		 * all we need is the protocol number and src/dst.
22765 		 */
22766 		/* Provide the checksums for UDP and TCP. */
22767 		if ((PROTO == IPPROTO_TCP) &&
22768 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22769 			/* hlen gets the number of uchar_ts in the IP header */
22770 			hlen = (V_HLEN & 0xF) << 2;
22771 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22772 			IP_STAT(ipst, ip_out_sw_cksum);
22773 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22774 			    LENGTH - hlen);
22775 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22776 		} else if (PROTO == IPPROTO_SCTP &&
22777 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22778 			sctp_hdr_t	*sctph;
22779 
22780 			hlen = (V_HLEN & 0xF) << 2;
22781 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22782 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22783 			sctph->sh_chksum = 0;
22784 #ifdef	DEBUG
22785 			if (!skip_sctp_cksum)
22786 #endif
22787 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22788 		} else {
22789 			queue_t *dev_q = stq->q_next;
22790 
22791 			if ((dev_q->q_next || dev_q->q_first) &&
22792 			    !canput(dev_q)) {
22793 blocked:
22794 				ipha->ipha_ident = ip_hdr_included;
22795 				/*
22796 				 * If we don't have a conn to apply
22797 				 * backpressure, free the message.
22798 				 * In the ire_send path, we don't know
22799 				 * the position to requeue the packet. Rather
22800 				 * than reorder packets, we just drop this
22801 				 * packet.
22802 				 */
22803 				if (ipst->ips_ip_output_queue &&
22804 				    connp != NULL &&
22805 				    caller != IRE_SEND) {
22806 					if (caller == IP_WSRV) {
22807 						connp->conn_did_putbq = 1;
22808 						(void) putbq(connp->conn_wq,
22809 						    first_mp);
22810 						conn_drain_insert(connp);
22811 						/*
22812 						 * This is the service thread,
22813 						 * and the queue is already
22814 						 * noenabled. The check for
22815 						 * canput and the putbq is not
22816 						 * atomic. So we need to check
22817 						 * again.
22818 						 */
22819 						if (canput(stq->q_next))
22820 							connp->conn_did_putbq
22821 							    = 0;
22822 						IP_STAT(ipst, ip_conn_flputbq);
22823 					} else {
22824 						/*
22825 						 * We are not the service proc.
22826 						 * ip_wsrv will be scheduled or
22827 						 * is already running.
22828 						 */
22829 						(void) putq(connp->conn_wq,
22830 						    first_mp);
22831 					}
22832 				} else {
22833 					out_ill = (ill_t *)stq->q_ptr;
22834 					BUMP_MIB(out_ill->ill_ip_mib,
22835 					    ipIfStatsOutDiscards);
22836 					freemsg(first_mp);
22837 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22838 					    "ip_wput_ire_end: q %p (%S)",
22839 					    q, "discard");
22840 				}
22841 				ire_refrele(ire);
22842 				if (next_mp) {
22843 					ire_refrele(ire1);
22844 					freemsg(next_mp);
22845 				}
22846 				if (conn_outgoing_ill != NULL)
22847 					ill_refrele(conn_outgoing_ill);
22848 				return;
22849 			}
22850 			if ((PROTO == IPPROTO_UDP) &&
22851 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
22852 				/*
22853 				 * hlen gets the number of uchar_ts in the
22854 				 * IP header
22855 				 */
22856 				hlen = (V_HLEN & 0xF) << 2;
22857 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22858 				max_frag = ire->ire_max_frag;
22859 				if (*up != 0) {
22860 					IP_CKSUM_XMIT(out_ill, ire, mp, ipha,
22861 					    up, PROTO, hlen, LENGTH, max_frag,
22862 					    ipsec_len, cksum);
22863 					/* Software checksum? */
22864 					if (DB_CKSUMFLAGS(mp) == 0) {
22865 						IP_STAT(ipst, ip_out_sw_cksum);
22866 						IP_STAT_UPDATE(ipst,
22867 						    ip_udp_out_sw_cksum_bytes,
22868 						    LENGTH - hlen);
22869 					}
22870 				}
22871 			}
22872 		}
22873 		/*
22874 		 * Need to do this even when fragmenting. The local
22875 		 * loopback can be done without computing checksums
22876 		 * but forwarding out other interface must be done
22877 		 * after the IP checksum (and ULP checksums) have been
22878 		 * computed.
22879 		 *
22880 		 * NOTE : multicast_forward is set only if this packet
22881 		 * originated from ip_wput. For packets originating from
22882 		 * ip_wput_multicast, it is not set.
22883 		 */
22884 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
22885 multi_loopback:
22886 			ip2dbg(("ip_wput: multicast, loop %d\n",
22887 			    conn_multicast_loop));
22888 
22889 			/*  Forget header checksum offload */
22890 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
22891 
22892 			/*
22893 			 * Local loopback of multicasts?  Check the
22894 			 * ill.
22895 			 *
22896 			 * Note that the loopback function will not come
22897 			 * in through ip_rput - it will only do the
22898 			 * client fanout thus we need to do an mforward
22899 			 * as well.  The is different from the BSD
22900 			 * logic.
22901 			 */
22902 			if (ill != NULL) {
22903 				ilm_t	*ilm;
22904 
22905 				ILM_WALKER_HOLD(ill);
22906 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
22907 				    ALL_ZONES);
22908 				ILM_WALKER_RELE(ill);
22909 				if (ilm != NULL) {
22910 					/*
22911 					 * Pass along the virtual output q.
22912 					 * ip_wput_local() will distribute the
22913 					 * packet to all the matching zones,
22914 					 * except the sending zone when
22915 					 * IP_MULTICAST_LOOP is false.
22916 					 */
22917 					ip_multicast_loopback(q, ill, first_mp,
22918 					    conn_multicast_loop ? 0 :
22919 					    IP_FF_NO_MCAST_LOOP, zoneid);
22920 				}
22921 			}
22922 			if (ipha->ipha_ttl == 0) {
22923 				/*
22924 				 * 0 => only to this host i.e. we are
22925 				 * done. We are also done if this was the
22926 				 * loopback interface since it is sufficient
22927 				 * to loopback one copy of a multicast packet.
22928 				 */
22929 				freemsg(first_mp);
22930 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22931 				    "ip_wput_ire_end: q %p (%S)",
22932 				    q, "loopback");
22933 				ire_refrele(ire);
22934 				if (conn_outgoing_ill != NULL)
22935 					ill_refrele(conn_outgoing_ill);
22936 				return;
22937 			}
22938 			/*
22939 			 * ILLF_MULTICAST is checked in ip_newroute
22940 			 * i.e. we don't need to check it here since
22941 			 * all IRE_CACHEs come from ip_newroute.
22942 			 * For multicast traffic, SO_DONTROUTE is interpreted
22943 			 * to mean only send the packet out the interface
22944 			 * (optionally specified with IP_MULTICAST_IF)
22945 			 * and do not forward it out additional interfaces.
22946 			 * RSVP and the rsvp daemon is an example of a
22947 			 * protocol and user level process that
22948 			 * handles it's own routing. Hence, it uses the
22949 			 * SO_DONTROUTE option to accomplish this.
22950 			 */
22951 
22952 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
22953 			    ill != NULL) {
22954 				/* Unconditionally redo the checksum */
22955 				ipha->ipha_hdr_checksum = 0;
22956 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22957 
22958 				/*
22959 				 * If this needs to go out secure, we need
22960 				 * to wait till we finish the IPsec
22961 				 * processing.
22962 				 */
22963 				if (ipsec_len == 0 &&
22964 				    ip_mforward(ill, ipha, mp)) {
22965 					freemsg(first_mp);
22966 					ip1dbg(("ip_wput: mforward failed\n"));
22967 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22968 					    "ip_wput_ire_end: q %p (%S)",
22969 					    q, "mforward failed");
22970 					ire_refrele(ire);
22971 					if (conn_outgoing_ill != NULL)
22972 						ill_refrele(conn_outgoing_ill);
22973 					return;
22974 				}
22975 			}
22976 		}
22977 		max_frag = ire->ire_max_frag;
22978 		cksum += ttl_protocol;
22979 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
22980 			/* No fragmentation required for this one. */
22981 			/*
22982 			 * Don't use frag_flag if packet is pre-built or source
22983 			 * routed or if multicast (since multicast packets do
22984 			 * not solicit ICMP "packet too big" messages).
22985 			 */
22986 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22987 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22988 			    !ip_source_route_included(ipha)) &&
22989 			    !CLASSD(ipha->ipha_dst))
22990 				ipha->ipha_fragment_offset_and_flags |=
22991 				    htons(ire->ire_frag_flag);
22992 
22993 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22994 				/* Complete the IP header checksum. */
22995 				cksum += ipha->ipha_ident;
22996 				cksum += (v_hlen_tos_len >> 16)+
22997 				    (v_hlen_tos_len & 0xFFFF);
22998 				cksum += ipha->ipha_fragment_offset_and_flags;
22999 				hlen = (V_HLEN & 0xF) -
23000 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
23001 				if (hlen) {
23002 checksumoptions:
23003 					/*
23004 					 * Account for the IP Options in the IP
23005 					 * header checksum.
23006 					 */
23007 					up = (uint16_t *)(rptr+
23008 					    IP_SIMPLE_HDR_LENGTH);
23009 					do {
23010 						cksum += up[0];
23011 						cksum += up[1];
23012 						up += 2;
23013 					} while (--hlen);
23014 				}
23015 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
23016 				cksum = ~(cksum + (cksum >> 16));
23017 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
23018 			}
23019 			if (ipsec_len != 0) {
23020 				ipsec_out_process(q, first_mp, ire, ill_index);
23021 				if (!next_mp) {
23022 					ire_refrele(ire);
23023 					if (conn_outgoing_ill != NULL)
23024 						ill_refrele(conn_outgoing_ill);
23025 					return;
23026 				}
23027 				goto next;
23028 			}
23029 
23030 			/*
23031 			 * multirt_send has already been handled
23032 			 * for broadcast, but not yet for multicast
23033 			 * or IP options.
23034 			 */
23035 			if (next_mp == NULL) {
23036 				if (ire->ire_flags & RTF_MULTIRT) {
23037 					multirt_send = B_TRUE;
23038 				}
23039 			}
23040 
23041 			/*
23042 			 * In most cases, the emission loop below is
23043 			 * entered only once. Only in the case where
23044 			 * the ire holds the RTF_MULTIRT flag, do we loop
23045 			 * to process all RTF_MULTIRT ires in the bucket,
23046 			 * and send the packet through all crossed
23047 			 * RTF_MULTIRT routes.
23048 			 */
23049 			do {
23050 				if (multirt_send) {
23051 					irb_t *irb;
23052 
23053 					irb = ire->ire_bucket;
23054 					ASSERT(irb != NULL);
23055 					/*
23056 					 * We are in a multiple send case,
23057 					 * need to get the next IRE and make
23058 					 * a duplicate of the packet.
23059 					 */
23060 					IRB_REFHOLD(irb);
23061 					for (ire1 = ire->ire_next;
23062 					    ire1 != NULL;
23063 					    ire1 = ire1->ire_next) {
23064 						if (!(ire1->ire_flags &
23065 						    RTF_MULTIRT)) {
23066 							continue;
23067 						}
23068 						if (ire1->ire_addr !=
23069 						    ire->ire_addr) {
23070 							continue;
23071 						}
23072 						if (ire1->ire_marks &
23073 						    (IRE_MARK_CONDEMNED|
23074 						    IRE_MARK_HIDDEN)) {
23075 							continue;
23076 						}
23077 
23078 						/* Got one */
23079 						IRE_REFHOLD(ire1);
23080 						break;
23081 					}
23082 					IRB_REFRELE(irb);
23083 
23084 					if (ire1 != NULL) {
23085 						next_mp = copyb(mp);
23086 						if ((next_mp == NULL) ||
23087 						    ((mp->b_cont != NULL) &&
23088 						    ((next_mp->b_cont =
23089 						    dupmsg(mp->b_cont))
23090 						    == NULL))) {
23091 							freemsg(next_mp);
23092 							next_mp = NULL;
23093 							ire_refrele(ire1);
23094 							ire1 = NULL;
23095 						}
23096 					}
23097 
23098 					/*
23099 					 * Last multiroute ire; don't loop
23100 					 * anymore. The emission is over
23101 					 * and next_mp is NULL.
23102 					 */
23103 					if (ire1 == NULL) {
23104 						multirt_send = B_FALSE;
23105 					}
23106 				}
23107 
23108 				out_ill = ire_to_ill(ire);
23109 				DTRACE_PROBE4(ip4__physical__out__start,
23110 				    ill_t *, NULL,
23111 				    ill_t *, out_ill,
23112 				    ipha_t *, ipha, mblk_t *, mp);
23113 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23114 				    ipst->ips_ipv4firewall_physical_out,
23115 				    NULL, out_ill, ipha, mp, mp, ipst);
23116 				DTRACE_PROBE1(ip4__physical__out__end,
23117 				    mblk_t *, mp);
23118 				if (mp == NULL)
23119 					goto release_ire_and_ill_2;
23120 
23121 				ASSERT(ipsec_len == 0);
23122 				mp->b_prev =
23123 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23124 				DTRACE_PROBE2(ip__xmit__2,
23125 				    mblk_t *, mp, ire_t *, ire);
23126 				pktxmit_state = ip_xmit_v4(mp, ire,
23127 				    NULL, B_TRUE);
23128 				if ((pktxmit_state == SEND_FAILED) ||
23129 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23130 release_ire_and_ill_2:
23131 					if (next_mp) {
23132 						freemsg(next_mp);
23133 						ire_refrele(ire1);
23134 					}
23135 					ire_refrele(ire);
23136 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23137 					    "ip_wput_ire_end: q %p (%S)",
23138 					    q, "discard MDATA");
23139 					if (conn_outgoing_ill != NULL)
23140 						ill_refrele(conn_outgoing_ill);
23141 					return;
23142 				}
23143 
23144 				if (CLASSD(dst)) {
23145 					BUMP_MIB(out_ill->ill_ip_mib,
23146 					    ipIfStatsHCOutMcastPkts);
23147 					UPDATE_MIB(out_ill->ill_ip_mib,
23148 					    ipIfStatsHCOutMcastOctets,
23149 					    LENGTH);
23150 				} else if (ire->ire_type == IRE_BROADCAST) {
23151 					BUMP_MIB(out_ill->ill_ip_mib,
23152 					    ipIfStatsHCOutBcastPkts);
23153 				}
23154 
23155 				if (multirt_send) {
23156 					/*
23157 					 * We are in a multiple send case,
23158 					 * need to re-enter the sending loop
23159 					 * using the next ire.
23160 					 */
23161 					ire_refrele(ire);
23162 					ire = ire1;
23163 					stq = ire->ire_stq;
23164 					mp = next_mp;
23165 					next_mp = NULL;
23166 					ipha = (ipha_t *)mp->b_rptr;
23167 					ill_index = Q_TO_INDEX(stq);
23168 				}
23169 			} while (multirt_send);
23170 
23171 			if (!next_mp) {
23172 				/*
23173 				 * Last copy going out (the ultra-common
23174 				 * case).  Note that we intentionally replicate
23175 				 * the putnext rather than calling it before
23176 				 * the next_mp check in hopes of a little
23177 				 * tail-call action out of the compiler.
23178 				 */
23179 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23180 				    "ip_wput_ire_end: q %p (%S)",
23181 				    q, "last copy out(1)");
23182 				ire_refrele(ire);
23183 				if (conn_outgoing_ill != NULL)
23184 					ill_refrele(conn_outgoing_ill);
23185 				return;
23186 			}
23187 			/* More copies going out below. */
23188 		} else {
23189 			int offset;
23190 fragmentit:
23191 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23192 			/*
23193 			 * If this would generate a icmp_frag_needed message,
23194 			 * we need to handle it before we do the IPsec
23195 			 * processing. Otherwise, we need to strip the IPsec
23196 			 * headers before we send up the message to the ULPs
23197 			 * which becomes messy and difficult.
23198 			 */
23199 			if (ipsec_len != 0) {
23200 				if ((max_frag < (unsigned int)(LENGTH +
23201 				    ipsec_len)) && (offset & IPH_DF)) {
23202 					out_ill = (ill_t *)stq->q_ptr;
23203 					BUMP_MIB(out_ill->ill_ip_mib,
23204 					    ipIfStatsOutFragFails);
23205 					BUMP_MIB(out_ill->ill_ip_mib,
23206 					    ipIfStatsOutFragReqds);
23207 					ipha->ipha_hdr_checksum = 0;
23208 					ipha->ipha_hdr_checksum =
23209 					    (uint16_t)ip_csum_hdr(ipha);
23210 					icmp_frag_needed(ire->ire_stq, first_mp,
23211 					    max_frag, zoneid, ipst);
23212 					if (!next_mp) {
23213 						ire_refrele(ire);
23214 						if (conn_outgoing_ill != NULL) {
23215 							ill_refrele(
23216 							    conn_outgoing_ill);
23217 						}
23218 						return;
23219 					}
23220 				} else {
23221 					/*
23222 					 * This won't cause a icmp_frag_needed
23223 					 * message. to be generated. Send it on
23224 					 * the wire. Note that this could still
23225 					 * cause fragmentation and all we
23226 					 * do is the generation of the message
23227 					 * to the ULP if needed before IPsec.
23228 					 */
23229 					if (!next_mp) {
23230 						ipsec_out_process(q, first_mp,
23231 						    ire, ill_index);
23232 						TRACE_2(TR_FAC_IP,
23233 						    TR_IP_WPUT_IRE_END,
23234 						    "ip_wput_ire_end: q %p "
23235 						    "(%S)", q,
23236 						    "last ipsec_out_process");
23237 						ire_refrele(ire);
23238 						if (conn_outgoing_ill != NULL) {
23239 							ill_refrele(
23240 							    conn_outgoing_ill);
23241 						}
23242 						return;
23243 					}
23244 					ipsec_out_process(q, first_mp,
23245 					    ire, ill_index);
23246 				}
23247 			} else {
23248 				/*
23249 				 * Initiate IPPF processing. For
23250 				 * fragmentable packets we finish
23251 				 * all QOS packet processing before
23252 				 * calling:
23253 				 * ip_wput_ire_fragmentit->ip_wput_frag
23254 				 */
23255 
23256 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23257 					ip_process(IPP_LOCAL_OUT, &mp,
23258 					    ill_index);
23259 					if (mp == NULL) {
23260 						out_ill = (ill_t *)stq->q_ptr;
23261 						BUMP_MIB(out_ill->ill_ip_mib,
23262 						    ipIfStatsOutDiscards);
23263 						if (next_mp != NULL) {
23264 							freemsg(next_mp);
23265 							ire_refrele(ire1);
23266 						}
23267 						ire_refrele(ire);
23268 						TRACE_2(TR_FAC_IP,
23269 						    TR_IP_WPUT_IRE_END,
23270 						    "ip_wput_ire: q %p (%S)",
23271 						    q, "discard MDATA");
23272 						if (conn_outgoing_ill != NULL) {
23273 							ill_refrele(
23274 							    conn_outgoing_ill);
23275 						}
23276 						return;
23277 					}
23278 				}
23279 				if (!next_mp) {
23280 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23281 					    "ip_wput_ire_end: q %p (%S)",
23282 					    q, "last fragmentation");
23283 					ip_wput_ire_fragmentit(mp, ire,
23284 					    zoneid, ipst);
23285 					ire_refrele(ire);
23286 					if (conn_outgoing_ill != NULL)
23287 						ill_refrele(conn_outgoing_ill);
23288 					return;
23289 				}
23290 				ip_wput_ire_fragmentit(mp, ire, zoneid, ipst);
23291 			}
23292 		}
23293 	} else {
23294 nullstq:
23295 		/* A NULL stq means the destination address is local. */
23296 		UPDATE_OB_PKT_COUNT(ire);
23297 		ire->ire_last_used_time = lbolt;
23298 		ASSERT(ire->ire_ipif != NULL);
23299 		if (!next_mp) {
23300 			/*
23301 			 * Is there an "in" and "out" for traffic local
23302 			 * to a host (loopback)?  The code in Solaris doesn't
23303 			 * explicitly draw a line in its code for in vs out,
23304 			 * so we've had to draw a line in the sand: ip_wput_ire
23305 			 * is considered to be the "output" side and
23306 			 * ip_wput_local to be the "input" side.
23307 			 */
23308 			out_ill = ire_to_ill(ire);
23309 
23310 			DTRACE_PROBE4(ip4__loopback__out__start,
23311 			    ill_t *, NULL, ill_t *, out_ill,
23312 			    ipha_t *, ipha, mblk_t *, first_mp);
23313 
23314 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23315 			    ipst->ips_ipv4firewall_loopback_out,
23316 			    NULL, out_ill, ipha, first_mp, mp, ipst);
23317 
23318 			DTRACE_PROBE1(ip4__loopback__out_end,
23319 			    mblk_t *, first_mp);
23320 
23321 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23322 			    "ip_wput_ire_end: q %p (%S)",
23323 			    q, "local address");
23324 
23325 			if (first_mp != NULL)
23326 				ip_wput_local(q, out_ill, ipha,
23327 				    first_mp, ire, 0, ire->ire_zoneid);
23328 			ire_refrele(ire);
23329 			if (conn_outgoing_ill != NULL)
23330 				ill_refrele(conn_outgoing_ill);
23331 			return;
23332 		}
23333 
23334 		out_ill = ire_to_ill(ire);
23335 
23336 		DTRACE_PROBE4(ip4__loopback__out__start,
23337 		    ill_t *, NULL, ill_t *, out_ill,
23338 		    ipha_t *, ipha, mblk_t *, first_mp);
23339 
23340 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23341 		    ipst->ips_ipv4firewall_loopback_out,
23342 		    NULL, out_ill, ipha, first_mp, mp, ipst);
23343 
23344 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23345 
23346 		if (first_mp != NULL)
23347 			ip_wput_local(q, out_ill, ipha,
23348 			    first_mp, ire, 0, ire->ire_zoneid);
23349 	}
23350 next:
23351 	/*
23352 	 * More copies going out to additional interfaces.
23353 	 * ire1 has already been held. We don't need the
23354 	 * "ire" anymore.
23355 	 */
23356 	ire_refrele(ire);
23357 	ire = ire1;
23358 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23359 	mp = next_mp;
23360 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23361 	ill = ire_to_ill(ire);
23362 	first_mp = mp;
23363 	if (ipsec_len != 0) {
23364 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23365 		mp = mp->b_cont;
23366 	}
23367 	dst = ire->ire_addr;
23368 	ipha = (ipha_t *)mp->b_rptr;
23369 	/*
23370 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23371 	 * Restore ipha_ident "no checksum" flag.
23372 	 */
23373 	src = orig_src;
23374 	ipha->ipha_ident = ip_hdr_included;
23375 	goto another;
23376 
23377 #undef	rptr
23378 #undef	Q_TO_INDEX
23379 }
23380 
23381 /*
23382  * Routine to allocate a message that is used to notify the ULP about MDT.
23383  * The caller may provide a pointer to the link-layer MDT capabilities,
23384  * or NULL if MDT is to be disabled on the stream.
23385  */
23386 mblk_t *
23387 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23388 {
23389 	mblk_t *mp;
23390 	ip_mdt_info_t *mdti;
23391 	ill_mdt_capab_t *idst;
23392 
23393 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23394 		DB_TYPE(mp) = M_CTL;
23395 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23396 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23397 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23398 		idst = &(mdti->mdt_capab);
23399 
23400 		/*
23401 		 * If the caller provides us with the capability, copy
23402 		 * it over into our notification message; otherwise
23403 		 * we zero out the capability portion.
23404 		 */
23405 		if (isrc != NULL)
23406 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23407 		else
23408 			bzero((caddr_t)idst, sizeof (*idst));
23409 	}
23410 	return (mp);
23411 }
23412 
23413 /*
23414  * Routine which determines whether MDT can be enabled on the destination
23415  * IRE and IPC combination, and if so, allocates and returns the MDT
23416  * notification mblk that may be used by ULP.  We also check if we need to
23417  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23418  * MDT usage in the past have been lifted.  This gets called during IP
23419  * and ULP binding.
23420  */
23421 mblk_t *
23422 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23423     ill_mdt_capab_t *mdt_cap)
23424 {
23425 	mblk_t *mp;
23426 	boolean_t rc = B_FALSE;
23427 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23428 
23429 	ASSERT(dst_ire != NULL);
23430 	ASSERT(connp != NULL);
23431 	ASSERT(mdt_cap != NULL);
23432 
23433 	/*
23434 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23435 	 * Multidata, which is handled in tcp_multisend().  This
23436 	 * is the reason why we do all these checks here, to ensure
23437 	 * that we don't enable Multidata for the cases which we
23438 	 * can't handle at the moment.
23439 	 */
23440 	do {
23441 		/* Only do TCP at the moment */
23442 		if (connp->conn_ulp != IPPROTO_TCP)
23443 			break;
23444 
23445 		/*
23446 		 * IPsec outbound policy present?  Note that we get here
23447 		 * after calling ipsec_conn_cache_policy() where the global
23448 		 * policy checking is performed.  conn_latch will be
23449 		 * non-NULL as long as there's a policy defined,
23450 		 * i.e. conn_out_enforce_policy may be NULL in such case
23451 		 * when the connection is non-secure, and hence we check
23452 		 * further if the latch refers to an outbound policy.
23453 		 */
23454 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23455 			break;
23456 
23457 		/* CGTP (multiroute) is enabled? */
23458 		if (dst_ire->ire_flags & RTF_MULTIRT)
23459 			break;
23460 
23461 		/* Outbound IPQoS enabled? */
23462 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23463 			/*
23464 			 * In this case, we disable MDT for this and all
23465 			 * future connections going over the interface.
23466 			 */
23467 			mdt_cap->ill_mdt_on = 0;
23468 			break;
23469 		}
23470 
23471 		/* socket option(s) present? */
23472 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23473 			break;
23474 
23475 		rc = B_TRUE;
23476 	/* CONSTCOND */
23477 	} while (0);
23478 
23479 	/* Remember the result */
23480 	connp->conn_mdt_ok = rc;
23481 
23482 	if (!rc)
23483 		return (NULL);
23484 	else if (!mdt_cap->ill_mdt_on) {
23485 		/*
23486 		 * If MDT has been previously turned off in the past, and we
23487 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23488 		 * then enable it for this interface.
23489 		 */
23490 		mdt_cap->ill_mdt_on = 1;
23491 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23492 		    "interface %s\n", ill_name));
23493 	}
23494 
23495 	/* Allocate the MDT info mblk */
23496 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23497 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23498 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23499 		return (NULL);
23500 	}
23501 	return (mp);
23502 }
23503 
23504 /*
23505  * Routine to allocate a message that is used to notify the ULP about LSO.
23506  * The caller may provide a pointer to the link-layer LSO capabilities,
23507  * or NULL if LSO is to be disabled on the stream.
23508  */
23509 mblk_t *
23510 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23511 {
23512 	mblk_t *mp;
23513 	ip_lso_info_t *lsoi;
23514 	ill_lso_capab_t *idst;
23515 
23516 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23517 		DB_TYPE(mp) = M_CTL;
23518 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23519 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23520 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23521 		idst = &(lsoi->lso_capab);
23522 
23523 		/*
23524 		 * If the caller provides us with the capability, copy
23525 		 * it over into our notification message; otherwise
23526 		 * we zero out the capability portion.
23527 		 */
23528 		if (isrc != NULL)
23529 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23530 		else
23531 			bzero((caddr_t)idst, sizeof (*idst));
23532 	}
23533 	return (mp);
23534 }
23535 
23536 /*
23537  * Routine which determines whether LSO can be enabled on the destination
23538  * IRE and IPC combination, and if so, allocates and returns the LSO
23539  * notification mblk that may be used by ULP.  We also check if we need to
23540  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23541  * LSO usage in the past have been lifted.  This gets called during IP
23542  * and ULP binding.
23543  */
23544 mblk_t *
23545 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23546     ill_lso_capab_t *lso_cap)
23547 {
23548 	mblk_t *mp;
23549 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23550 
23551 	ASSERT(dst_ire != NULL);
23552 	ASSERT(connp != NULL);
23553 	ASSERT(lso_cap != NULL);
23554 
23555 	connp->conn_lso_ok = B_TRUE;
23556 
23557 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23558 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23559 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23560 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23561 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23562 		connp->conn_lso_ok = B_FALSE;
23563 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23564 			/*
23565 			 * Disable LSO for this and all future connections going
23566 			 * over the interface.
23567 			 */
23568 			lso_cap->ill_lso_on = 0;
23569 		}
23570 	}
23571 
23572 	if (!connp->conn_lso_ok)
23573 		return (NULL);
23574 	else if (!lso_cap->ill_lso_on) {
23575 		/*
23576 		 * If LSO has been previously turned off in the past, and we
23577 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23578 		 * then enable it for this interface.
23579 		 */
23580 		lso_cap->ill_lso_on = 1;
23581 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23582 		    ill_name));
23583 	}
23584 
23585 	/* Allocate the LSO info mblk */
23586 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23587 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23588 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23589 
23590 	return (mp);
23591 }
23592 
23593 /*
23594  * Create destination address attribute, and fill it with the physical
23595  * destination address and SAP taken from the template DL_UNITDATA_REQ
23596  * message block.
23597  */
23598 boolean_t
23599 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23600 {
23601 	dl_unitdata_req_t *dlurp;
23602 	pattr_t *pa;
23603 	pattrinfo_t pa_info;
23604 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23605 	uint_t das_len, das_off;
23606 
23607 	ASSERT(dlmp != NULL);
23608 
23609 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23610 	das_len = dlurp->dl_dest_addr_length;
23611 	das_off = dlurp->dl_dest_addr_offset;
23612 
23613 	pa_info.type = PATTR_DSTADDRSAP;
23614 	pa_info.len = sizeof (**das) + das_len - 1;
23615 
23616 	/* create and associate the attribute */
23617 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23618 	if (pa != NULL) {
23619 		ASSERT(*das != NULL);
23620 		(*das)->addr_is_group = 0;
23621 		(*das)->addr_len = (uint8_t)das_len;
23622 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23623 	}
23624 
23625 	return (pa != NULL);
23626 }
23627 
23628 /*
23629  * Create hardware checksum attribute and fill it with the values passed.
23630  */
23631 boolean_t
23632 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23633     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23634 {
23635 	pattr_t *pa;
23636 	pattrinfo_t pa_info;
23637 
23638 	ASSERT(mmd != NULL);
23639 
23640 	pa_info.type = PATTR_HCKSUM;
23641 	pa_info.len = sizeof (pattr_hcksum_t);
23642 
23643 	/* create and associate the attribute */
23644 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23645 	if (pa != NULL) {
23646 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23647 
23648 		hck->hcksum_start_offset = start_offset;
23649 		hck->hcksum_stuff_offset = stuff_offset;
23650 		hck->hcksum_end_offset = end_offset;
23651 		hck->hcksum_flags = flags;
23652 	}
23653 	return (pa != NULL);
23654 }
23655 
23656 /*
23657  * Create zerocopy attribute and fill it with the specified flags
23658  */
23659 boolean_t
23660 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23661 {
23662 	pattr_t *pa;
23663 	pattrinfo_t pa_info;
23664 
23665 	ASSERT(mmd != NULL);
23666 	pa_info.type = PATTR_ZCOPY;
23667 	pa_info.len = sizeof (pattr_zcopy_t);
23668 
23669 	/* create and associate the attribute */
23670 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23671 	if (pa != NULL) {
23672 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23673 
23674 		zcopy->zcopy_flags = flags;
23675 	}
23676 	return (pa != NULL);
23677 }
23678 
23679 /*
23680  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23681  * block chain. We could rewrite to handle arbitrary message block chains but
23682  * that would make the code complicated and slow. Right now there three
23683  * restrictions:
23684  *
23685  *   1. The first message block must contain the complete IP header and
23686  *	at least 1 byte of payload data.
23687  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23688  *	so that we can use a single Multidata message.
23689  *   3. No frag must be distributed over two or more message blocks so
23690  *	that we don't need more than two packet descriptors per frag.
23691  *
23692  * The above restrictions allow us to support userland applications (which
23693  * will send down a single message block) and NFS over UDP (which will
23694  * send down a chain of at most three message blocks).
23695  *
23696  * We also don't use MDT for payloads with less than or equal to
23697  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23698  */
23699 boolean_t
23700 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23701 {
23702 	int	blocks;
23703 	ssize_t	total, missing, size;
23704 
23705 	ASSERT(mp != NULL);
23706 	ASSERT(hdr_len > 0);
23707 
23708 	size = MBLKL(mp) - hdr_len;
23709 	if (size <= 0)
23710 		return (B_FALSE);
23711 
23712 	/* The first mblk contains the header and some payload. */
23713 	blocks = 1;
23714 	total = size;
23715 	size %= len;
23716 	missing = (size == 0) ? 0 : (len - size);
23717 	mp = mp->b_cont;
23718 
23719 	while (mp != NULL) {
23720 		/*
23721 		 * Give up if we encounter a zero length message block.
23722 		 * In practice, this should rarely happen and therefore
23723 		 * not worth the trouble of freeing and re-linking the
23724 		 * mblk from the chain to handle such case.
23725 		 */
23726 		if ((size = MBLKL(mp)) == 0)
23727 			return (B_FALSE);
23728 
23729 		/* Too many payload buffers for a single Multidata message? */
23730 		if (++blocks > MULTIDATA_MAX_PBUFS)
23731 			return (B_FALSE);
23732 
23733 		total += size;
23734 		/* Is a frag distributed over two or more message blocks? */
23735 		if (missing > size)
23736 			return (B_FALSE);
23737 		size -= missing;
23738 
23739 		size %= len;
23740 		missing = (size == 0) ? 0 : (len - size);
23741 
23742 		mp = mp->b_cont;
23743 	}
23744 
23745 	return (total > ip_wput_frag_mdt_min);
23746 }
23747 
23748 /*
23749  * Outbound IPv4 fragmentation routine using MDT.
23750  */
23751 static void
23752 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23753     uint32_t frag_flag, int offset)
23754 {
23755 	ipha_t		*ipha_orig;
23756 	int		i1, ip_data_end;
23757 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23758 	mblk_t		*hdr_mp, *md_mp = NULL;
23759 	unsigned char	*hdr_ptr, *pld_ptr;
23760 	multidata_t	*mmd;
23761 	ip_pdescinfo_t	pdi;
23762 	ill_t		*ill;
23763 	ip_stack_t	*ipst = ire->ire_ipst;
23764 
23765 	ASSERT(DB_TYPE(mp) == M_DATA);
23766 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23767 
23768 	ill = ire_to_ill(ire);
23769 	ASSERT(ill != NULL);
23770 
23771 	ipha_orig = (ipha_t *)mp->b_rptr;
23772 	mp->b_rptr += sizeof (ipha_t);
23773 
23774 	/* Calculate how many packets we will send out */
23775 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
23776 	pkts = (i1 + len - 1) / len;
23777 	ASSERT(pkts > 1);
23778 
23779 	/* Allocate a message block which will hold all the IP Headers. */
23780 	wroff = ipst->ips_ip_wroff_extra;
23781 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
23782 
23783 	i1 = pkts * hdr_chunk_len;
23784 	/*
23785 	 * Create the header buffer, Multidata and destination address
23786 	 * and SAP attribute that should be associated with it.
23787 	 */
23788 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
23789 	    ((hdr_mp->b_wptr += i1),
23790 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
23791 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
23792 		freemsg(mp);
23793 		if (md_mp == NULL) {
23794 			freemsg(hdr_mp);
23795 		} else {
23796 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
23797 			freemsg(md_mp);
23798 		}
23799 		IP_STAT(ipst, ip_frag_mdt_allocfail);
23800 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
23801 		return;
23802 	}
23803 	IP_STAT(ipst, ip_frag_mdt_allocd);
23804 
23805 	/*
23806 	 * Add a payload buffer to the Multidata; this operation must not
23807 	 * fail, or otherwise our logic in this routine is broken.  There
23808 	 * is no memory allocation done by the routine, so any returned
23809 	 * failure simply tells us that we've done something wrong.
23810 	 *
23811 	 * A failure tells us that either we're adding the same payload
23812 	 * buffer more than once, or we're trying to add more buffers than
23813 	 * allowed.  None of the above cases should happen, and we panic
23814 	 * because either there's horrible heap corruption, and/or
23815 	 * programming mistake.
23816 	 */
23817 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23818 		goto pbuf_panic;
23819 
23820 	hdr_ptr = hdr_mp->b_rptr;
23821 	pld_ptr = mp->b_rptr;
23822 
23823 	/* Establish the ending byte offset, based on the starting offset. */
23824 	offset <<= 3;
23825 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
23826 	    IP_SIMPLE_HDR_LENGTH;
23827 
23828 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
23829 
23830 	while (pld_ptr < mp->b_wptr) {
23831 		ipha_t		*ipha;
23832 		uint16_t	offset_and_flags;
23833 		uint16_t	ip_len;
23834 		int		error;
23835 
23836 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
23837 		ipha = (ipha_t *)(hdr_ptr + wroff);
23838 		ASSERT(OK_32PTR(ipha));
23839 		*ipha = *ipha_orig;
23840 
23841 		if (ip_data_end - offset > len) {
23842 			offset_and_flags = IPH_MF;
23843 		} else {
23844 			/*
23845 			 * Last frag. Set len to the length of this last piece.
23846 			 */
23847 			len = ip_data_end - offset;
23848 			/* A frag of a frag might have IPH_MF non-zero */
23849 			offset_and_flags =
23850 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23851 			    IPH_MF;
23852 		}
23853 		offset_and_flags |= (uint16_t)(offset >> 3);
23854 		offset_and_flags |= (uint16_t)frag_flag;
23855 		/* Store the offset and flags in the IP header. */
23856 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23857 
23858 		/* Store the length in the IP header. */
23859 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
23860 		ipha->ipha_length = htons(ip_len);
23861 
23862 		/*
23863 		 * Set the IP header checksum.  Note that mp is just
23864 		 * the header, so this is easy to pass to ip_csum.
23865 		 */
23866 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23867 
23868 		/*
23869 		 * Record offset and size of header and data of the next packet
23870 		 * in the multidata message.
23871 		 */
23872 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
23873 		PDESC_PLD_INIT(&pdi);
23874 		i1 = MIN(mp->b_wptr - pld_ptr, len);
23875 		ASSERT(i1 > 0);
23876 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
23877 		if (i1 == len) {
23878 			pld_ptr += len;
23879 		} else {
23880 			i1 = len - i1;
23881 			mp = mp->b_cont;
23882 			ASSERT(mp != NULL);
23883 			ASSERT(MBLKL(mp) >= i1);
23884 			/*
23885 			 * Attach the next payload message block to the
23886 			 * multidata message.
23887 			 */
23888 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23889 				goto pbuf_panic;
23890 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
23891 			pld_ptr = mp->b_rptr + i1;
23892 		}
23893 
23894 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
23895 		    KM_NOSLEEP)) == NULL) {
23896 			/*
23897 			 * Any failure other than ENOMEM indicates that we
23898 			 * have passed in invalid pdesc info or parameters
23899 			 * to mmd_addpdesc, which must not happen.
23900 			 *
23901 			 * EINVAL is a result of failure on boundary checks
23902 			 * against the pdesc info contents.  It should not
23903 			 * happen, and we panic because either there's
23904 			 * horrible heap corruption, and/or programming
23905 			 * mistake.
23906 			 */
23907 			if (error != ENOMEM) {
23908 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
23909 				    "pdesc logic error detected for "
23910 				    "mmd %p pinfo %p (%d)\n",
23911 				    (void *)mmd, (void *)&pdi, error);
23912 				/* NOTREACHED */
23913 			}
23914 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
23915 			/* Free unattached payload message blocks as well */
23916 			md_mp->b_cont = mp->b_cont;
23917 			goto free_mmd;
23918 		}
23919 
23920 		/* Advance fragment offset. */
23921 		offset += len;
23922 
23923 		/* Advance to location for next header in the buffer. */
23924 		hdr_ptr += hdr_chunk_len;
23925 
23926 		/* Did we reach the next payload message block? */
23927 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
23928 			mp = mp->b_cont;
23929 			/*
23930 			 * Attach the next message block with payload
23931 			 * data to the multidata message.
23932 			 */
23933 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23934 				goto pbuf_panic;
23935 			pld_ptr = mp->b_rptr;
23936 		}
23937 	}
23938 
23939 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
23940 	ASSERT(mp->b_wptr == pld_ptr);
23941 
23942 	/* Update IP statistics */
23943 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
23944 
23945 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
23946 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
23947 
23948 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
23949 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
23950 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
23951 
23952 	if (pkt_type == OB_PKT) {
23953 		ire->ire_ob_pkt_count += pkts;
23954 		if (ire->ire_ipif != NULL)
23955 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
23956 	} else {
23957 		/* The type is IB_PKT in the forwarding path. */
23958 		ire->ire_ib_pkt_count += pkts;
23959 		ASSERT(!IRE_IS_LOCAL(ire));
23960 		if (ire->ire_type & IRE_BROADCAST) {
23961 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
23962 		} else {
23963 			UPDATE_MIB(ill->ill_ip_mib,
23964 			    ipIfStatsHCOutForwDatagrams, pkts);
23965 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
23966 		}
23967 	}
23968 	ire->ire_last_used_time = lbolt;
23969 	/* Send it down */
23970 	putnext(ire->ire_stq, md_mp);
23971 	return;
23972 
23973 pbuf_panic:
23974 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
23975 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
23976 	    pbuf_idx);
23977 	/* NOTREACHED */
23978 }
23979 
23980 /*
23981  * Outbound IP fragmentation routine.
23982  *
23983  * NOTE : This routine does not ire_refrele the ire that is passed in
23984  * as the argument.
23985  */
23986 static void
23987 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
23988     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst)
23989 {
23990 	int		i1;
23991 	mblk_t		*ll_hdr_mp;
23992 	int 		ll_hdr_len;
23993 	int		hdr_len;
23994 	mblk_t		*hdr_mp;
23995 	ipha_t		*ipha;
23996 	int		ip_data_end;
23997 	int		len;
23998 	mblk_t		*mp = mp_orig, *mp1;
23999 	int		offset;
24000 	queue_t		*q;
24001 	uint32_t	v_hlen_tos_len;
24002 	mblk_t		*first_mp;
24003 	boolean_t	mctl_present;
24004 	ill_t		*ill;
24005 	ill_t		*out_ill;
24006 	mblk_t		*xmit_mp;
24007 	mblk_t		*carve_mp;
24008 	ire_t		*ire1 = NULL;
24009 	ire_t		*save_ire = NULL;
24010 	mblk_t  	*next_mp = NULL;
24011 	boolean_t	last_frag = B_FALSE;
24012 	boolean_t	multirt_send = B_FALSE;
24013 	ire_t		*first_ire = NULL;
24014 	irb_t		*irb = NULL;
24015 	mib2_ipIfStatsEntry_t *mibptr = NULL;
24016 
24017 	ill = ire_to_ill(ire);
24018 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
24019 
24020 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
24021 
24022 	if (max_frag == 0) {
24023 		ip1dbg(("ip_wput_frag: ire frag size is 0"
24024 		    " -  dropping packet\n"));
24025 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24026 		freemsg(mp);
24027 		return;
24028 	}
24029 
24030 	/*
24031 	 * IPsec does not allow hw accelerated packets to be fragmented
24032 	 * This check is made in ip_wput_ipsec_out prior to coming here
24033 	 * via ip_wput_ire_fragmentit.
24034 	 *
24035 	 * If at this point we have an ire whose ARP request has not
24036 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24037 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24038 	 * This packet and all fragmentable packets for this ire will
24039 	 * continue to get dropped while ire_nce->nce_state remains in
24040 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24041 	 * ND_REACHABLE, all subsquent large packets for this ire will
24042 	 * get fragemented and sent out by this function.
24043 	 */
24044 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24045 		/* If nce_state is ND_INITIAL, trigger ARP query */
24046 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
24047 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24048 		    " -  dropping packet\n"));
24049 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24050 		freemsg(mp);
24051 		return;
24052 	}
24053 
24054 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24055 	    "ip_wput_frag_start:");
24056 
24057 	if (mp->b_datap->db_type == M_CTL) {
24058 		first_mp = mp;
24059 		mp_orig = mp = mp->b_cont;
24060 		mctl_present = B_TRUE;
24061 	} else {
24062 		first_mp = mp;
24063 		mctl_present = B_FALSE;
24064 	}
24065 
24066 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24067 	ipha = (ipha_t *)mp->b_rptr;
24068 
24069 	/*
24070 	 * If the Don't Fragment flag is on, generate an ICMP destination
24071 	 * unreachable, fragmentation needed.
24072 	 */
24073 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24074 	if (offset & IPH_DF) {
24075 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24076 		if (is_system_labeled()) {
24077 			max_frag = tsol_pmtu_adjust(mp, ire->ire_max_frag,
24078 			    ire->ire_max_frag - max_frag, AF_INET);
24079 		}
24080 		/*
24081 		 * Need to compute hdr checksum if called from ip_wput_ire.
24082 		 * Note that ip_rput_forward verifies the checksum before
24083 		 * calling this routine so in that case this is a noop.
24084 		 */
24085 		ipha->ipha_hdr_checksum = 0;
24086 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24087 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24088 		    ipst);
24089 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24090 		    "ip_wput_frag_end:(%S)",
24091 		    "don't fragment");
24092 		return;
24093 	}
24094 	/*
24095 	 * Labeled systems adjust max_frag if they add a label
24096 	 * to send the correct path mtu.  We need the real mtu since we
24097 	 * are fragmenting the packet after label adjustment.
24098 	 */
24099 	if (is_system_labeled())
24100 		max_frag = ire->ire_max_frag;
24101 	if (mctl_present)
24102 		freeb(first_mp);
24103 	/*
24104 	 * Establish the starting offset.  May not be zero if we are fragging
24105 	 * a fragment that is being forwarded.
24106 	 */
24107 	offset = offset & IPH_OFFSET;
24108 
24109 	/* TODO why is this test needed? */
24110 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24111 	if (((max_frag - LENGTH) & ~7) < 8) {
24112 		/* TODO: notify ulp somehow */
24113 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24114 		freemsg(mp);
24115 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24116 		    "ip_wput_frag_end:(%S)",
24117 		    "len < 8");
24118 		return;
24119 	}
24120 
24121 	hdr_len = (V_HLEN & 0xF) << 2;
24122 
24123 	ipha->ipha_hdr_checksum = 0;
24124 
24125 	/*
24126 	 * Establish the number of bytes maximum per frag, after putting
24127 	 * in the header.
24128 	 */
24129 	len = (max_frag - hdr_len) & ~7;
24130 
24131 	/* Check if we can use MDT to send out the frags. */
24132 	ASSERT(!IRE_IS_LOCAL(ire));
24133 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24134 	    ipst->ips_ip_multidata_outbound &&
24135 	    !(ire->ire_flags & RTF_MULTIRT) &&
24136 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24137 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24138 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24139 		ASSERT(ill->ill_mdt_capab != NULL);
24140 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24141 			/*
24142 			 * If MDT has been previously turned off in the past,
24143 			 * and we currently can do MDT (due to IPQoS policy
24144 			 * removal, etc.) then enable it for this interface.
24145 			 */
24146 			ill->ill_mdt_capab->ill_mdt_on = 1;
24147 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24148 			    ill->ill_name));
24149 		}
24150 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24151 		    offset);
24152 		return;
24153 	}
24154 
24155 	/* Get a copy of the header for the trailing frags */
24156 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst);
24157 	if (!hdr_mp) {
24158 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24159 		freemsg(mp);
24160 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24161 		    "ip_wput_frag_end:(%S)",
24162 		    "couldn't copy hdr");
24163 		return;
24164 	}
24165 	if (DB_CRED(mp) != NULL)
24166 		mblk_setcred(hdr_mp, DB_CRED(mp));
24167 
24168 	/* Store the starting offset, with the MoreFrags flag. */
24169 	i1 = offset | IPH_MF | frag_flag;
24170 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24171 
24172 	/* Establish the ending byte offset, based on the starting offset. */
24173 	offset <<= 3;
24174 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24175 
24176 	/* Store the length of the first fragment in the IP header. */
24177 	i1 = len + hdr_len;
24178 	ASSERT(i1 <= IP_MAXPACKET);
24179 	ipha->ipha_length = htons((uint16_t)i1);
24180 
24181 	/*
24182 	 * Compute the IP header checksum for the first frag.  We have to
24183 	 * watch out that we stop at the end of the header.
24184 	 */
24185 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24186 
24187 	/*
24188 	 * Now carve off the first frag.  Note that this will include the
24189 	 * original IP header.
24190 	 */
24191 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24192 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24193 		freeb(hdr_mp);
24194 		freemsg(mp_orig);
24195 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24196 		    "ip_wput_frag_end:(%S)",
24197 		    "couldn't carve first");
24198 		return;
24199 	}
24200 
24201 	/*
24202 	 * Multirouting case. Each fragment is replicated
24203 	 * via all non-condemned RTF_MULTIRT routes
24204 	 * currently resolved.
24205 	 * We ensure that first_ire is the first RTF_MULTIRT
24206 	 * ire in the bucket.
24207 	 */
24208 	if (ire->ire_flags & RTF_MULTIRT) {
24209 		irb = ire->ire_bucket;
24210 		ASSERT(irb != NULL);
24211 
24212 		multirt_send = B_TRUE;
24213 
24214 		/* Make sure we do not omit any multiroute ire. */
24215 		IRB_REFHOLD(irb);
24216 		for (first_ire = irb->irb_ire;
24217 		    first_ire != NULL;
24218 		    first_ire = first_ire->ire_next) {
24219 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24220 			    (first_ire->ire_addr == ire->ire_addr) &&
24221 			    !(first_ire->ire_marks &
24222 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
24223 				break;
24224 			}
24225 		}
24226 
24227 		if (first_ire != NULL) {
24228 			if (first_ire != ire) {
24229 				IRE_REFHOLD(first_ire);
24230 				/*
24231 				 * Do not release the ire passed in
24232 				 * as the argument.
24233 				 */
24234 				ire = first_ire;
24235 			} else {
24236 				first_ire = NULL;
24237 			}
24238 		}
24239 		IRB_REFRELE(irb);
24240 
24241 		/*
24242 		 * Save the first ire; we will need to restore it
24243 		 * for the trailing frags.
24244 		 * We REFHOLD save_ire, as each iterated ire will be
24245 		 * REFRELEd.
24246 		 */
24247 		save_ire = ire;
24248 		IRE_REFHOLD(save_ire);
24249 	}
24250 
24251 	/*
24252 	 * First fragment emission loop.
24253 	 * In most cases, the emission loop below is entered only
24254 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24255 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24256 	 * bucket, and send the fragment through all crossed
24257 	 * RTF_MULTIRT routes.
24258 	 */
24259 	do {
24260 		if (ire->ire_flags & RTF_MULTIRT) {
24261 			/*
24262 			 * We are in a multiple send case, need to get
24263 			 * the next ire and make a copy of the packet.
24264 			 * ire1 holds here the next ire to process in the
24265 			 * bucket. If multirouting is expected,
24266 			 * any non-RTF_MULTIRT ire that has the
24267 			 * right destination address is ignored.
24268 			 *
24269 			 * We have to take into account the MTU of
24270 			 * each walked ire. max_frag is set by the
24271 			 * the caller and generally refers to
24272 			 * the primary ire entry. Here we ensure that
24273 			 * no route with a lower MTU will be used, as
24274 			 * fragments are carved once for all ires,
24275 			 * then replicated.
24276 			 */
24277 			ASSERT(irb != NULL);
24278 			IRB_REFHOLD(irb);
24279 			for (ire1 = ire->ire_next;
24280 			    ire1 != NULL;
24281 			    ire1 = ire1->ire_next) {
24282 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24283 					continue;
24284 				if (ire1->ire_addr != ire->ire_addr)
24285 					continue;
24286 				if (ire1->ire_marks &
24287 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
24288 					continue;
24289 				/*
24290 				 * Ensure we do not exceed the MTU
24291 				 * of the next route.
24292 				 */
24293 				if (ire1->ire_max_frag < max_frag) {
24294 					ip_multirt_bad_mtu(ire1, max_frag);
24295 					continue;
24296 				}
24297 
24298 				/* Got one. */
24299 				IRE_REFHOLD(ire1);
24300 				break;
24301 			}
24302 			IRB_REFRELE(irb);
24303 
24304 			if (ire1 != NULL) {
24305 				next_mp = copyb(mp);
24306 				if ((next_mp == NULL) ||
24307 				    ((mp->b_cont != NULL) &&
24308 				    ((next_mp->b_cont =
24309 				    dupmsg(mp->b_cont)) == NULL))) {
24310 					freemsg(next_mp);
24311 					next_mp = NULL;
24312 					ire_refrele(ire1);
24313 					ire1 = NULL;
24314 				}
24315 			}
24316 
24317 			/* Last multiroute ire; don't loop anymore. */
24318 			if (ire1 == NULL) {
24319 				multirt_send = B_FALSE;
24320 			}
24321 		}
24322 
24323 		ll_hdr_len = 0;
24324 		LOCK_IRE_FP_MP(ire);
24325 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24326 		if (ll_hdr_mp != NULL) {
24327 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24328 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24329 		} else {
24330 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24331 		}
24332 
24333 		/* If there is a transmit header, get a copy for this frag. */
24334 		/*
24335 		 * TODO: should check db_ref before calling ip_carve_mp since
24336 		 * it might give us a dup.
24337 		 */
24338 		if (!ll_hdr_mp) {
24339 			/* No xmit header. */
24340 			xmit_mp = mp;
24341 
24342 		/* We have a link-layer header that can fit in our mblk. */
24343 		} else if (mp->b_datap->db_ref == 1 &&
24344 		    ll_hdr_len != 0 &&
24345 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24346 			/* M_DATA fastpath */
24347 			mp->b_rptr -= ll_hdr_len;
24348 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24349 			xmit_mp = mp;
24350 
24351 		/* Corner case if copyb has failed */
24352 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24353 			UNLOCK_IRE_FP_MP(ire);
24354 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24355 			freeb(hdr_mp);
24356 			freemsg(mp);
24357 			freemsg(mp_orig);
24358 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24359 			    "ip_wput_frag_end:(%S)",
24360 			    "discard");
24361 
24362 			if (multirt_send) {
24363 				ASSERT(ire1);
24364 				ASSERT(next_mp);
24365 
24366 				freemsg(next_mp);
24367 				ire_refrele(ire1);
24368 			}
24369 			if (save_ire != NULL)
24370 				IRE_REFRELE(save_ire);
24371 
24372 			if (first_ire != NULL)
24373 				ire_refrele(first_ire);
24374 			return;
24375 
24376 		/*
24377 		 * Case of res_mp OR the fastpath mp can't fit
24378 		 * in the mblk
24379 		 */
24380 		} else {
24381 			xmit_mp->b_cont = mp;
24382 			if (DB_CRED(mp) != NULL)
24383 				mblk_setcred(xmit_mp, DB_CRED(mp));
24384 			/*
24385 			 * Get priority marking, if any.
24386 			 * We propagate the CoS marking from the
24387 			 * original packet that went to QoS processing
24388 			 * in ip_wput_ire to the newly carved mp.
24389 			 */
24390 			if (DB_TYPE(xmit_mp) == M_DATA)
24391 				xmit_mp->b_band = mp->b_band;
24392 		}
24393 		UNLOCK_IRE_FP_MP(ire);
24394 
24395 		q = ire->ire_stq;
24396 		out_ill = (ill_t *)q->q_ptr;
24397 
24398 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24399 
24400 		DTRACE_PROBE4(ip4__physical__out__start,
24401 		    ill_t *, NULL, ill_t *, out_ill,
24402 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24403 
24404 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24405 		    ipst->ips_ipv4firewall_physical_out,
24406 		    NULL, out_ill, ipha, xmit_mp, mp, ipst);
24407 
24408 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24409 
24410 		if (xmit_mp != NULL) {
24411 			putnext(q, xmit_mp);
24412 
24413 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24414 			UPDATE_MIB(out_ill->ill_ip_mib,
24415 			    ipIfStatsHCOutOctets, i1);
24416 
24417 			if (pkt_type != OB_PKT) {
24418 				/*
24419 				 * Update the packet count and MIB stats
24420 				 * of trailing RTF_MULTIRT ires.
24421 				 */
24422 				UPDATE_OB_PKT_COUNT(ire);
24423 				BUMP_MIB(out_ill->ill_ip_mib,
24424 				    ipIfStatsOutFragReqds);
24425 			}
24426 		}
24427 
24428 		if (multirt_send) {
24429 			/*
24430 			 * We are in a multiple send case; look for
24431 			 * the next ire and re-enter the loop.
24432 			 */
24433 			ASSERT(ire1);
24434 			ASSERT(next_mp);
24435 			/* REFRELE the current ire before looping */
24436 			ire_refrele(ire);
24437 			ire = ire1;
24438 			ire1 = NULL;
24439 			mp = next_mp;
24440 			next_mp = NULL;
24441 		}
24442 	} while (multirt_send);
24443 
24444 	ASSERT(ire1 == NULL);
24445 
24446 	/* Restore the original ire; we need it for the trailing frags */
24447 	if (save_ire != NULL) {
24448 		/* REFRELE the last iterated ire */
24449 		ire_refrele(ire);
24450 		/* save_ire has been REFHOLDed */
24451 		ire = save_ire;
24452 		save_ire = NULL;
24453 		q = ire->ire_stq;
24454 	}
24455 
24456 	if (pkt_type == OB_PKT) {
24457 		UPDATE_OB_PKT_COUNT(ire);
24458 	} else {
24459 		out_ill = (ill_t *)q->q_ptr;
24460 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24461 		UPDATE_IB_PKT_COUNT(ire);
24462 	}
24463 
24464 	/* Advance the offset to the second frag starting point. */
24465 	offset += len;
24466 	/*
24467 	 * Update hdr_len from the copied header - there might be less options
24468 	 * in the later fragments.
24469 	 */
24470 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24471 	/* Loop until done. */
24472 	for (;;) {
24473 		uint16_t	offset_and_flags;
24474 		uint16_t	ip_len;
24475 
24476 		if (ip_data_end - offset > len) {
24477 			/*
24478 			 * Carve off the appropriate amount from the original
24479 			 * datagram.
24480 			 */
24481 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24482 				mp = NULL;
24483 				break;
24484 			}
24485 			/*
24486 			 * More frags after this one.  Get another copy
24487 			 * of the header.
24488 			 */
24489 			if (carve_mp->b_datap->db_ref == 1 &&
24490 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24491 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24492 				/* Inline IP header */
24493 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24494 				    hdr_mp->b_rptr;
24495 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24496 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24497 				mp = carve_mp;
24498 			} else {
24499 				if (!(mp = copyb(hdr_mp))) {
24500 					freemsg(carve_mp);
24501 					break;
24502 				}
24503 				/* Get priority marking, if any. */
24504 				mp->b_band = carve_mp->b_band;
24505 				mp->b_cont = carve_mp;
24506 			}
24507 			ipha = (ipha_t *)mp->b_rptr;
24508 			offset_and_flags = IPH_MF;
24509 		} else {
24510 			/*
24511 			 * Last frag.  Consume the header. Set len to
24512 			 * the length of this last piece.
24513 			 */
24514 			len = ip_data_end - offset;
24515 
24516 			/*
24517 			 * Carve off the appropriate amount from the original
24518 			 * datagram.
24519 			 */
24520 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24521 				mp = NULL;
24522 				break;
24523 			}
24524 			if (carve_mp->b_datap->db_ref == 1 &&
24525 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24526 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24527 				/* Inline IP header */
24528 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24529 				    hdr_mp->b_rptr;
24530 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24531 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24532 				mp = carve_mp;
24533 				freeb(hdr_mp);
24534 				hdr_mp = mp;
24535 			} else {
24536 				mp = hdr_mp;
24537 				/* Get priority marking, if any. */
24538 				mp->b_band = carve_mp->b_band;
24539 				mp->b_cont = carve_mp;
24540 			}
24541 			ipha = (ipha_t *)mp->b_rptr;
24542 			/* A frag of a frag might have IPH_MF non-zero */
24543 			offset_and_flags =
24544 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24545 			    IPH_MF;
24546 		}
24547 		offset_and_flags |= (uint16_t)(offset >> 3);
24548 		offset_and_flags |= (uint16_t)frag_flag;
24549 		/* Store the offset and flags in the IP header. */
24550 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24551 
24552 		/* Store the length in the IP header. */
24553 		ip_len = (uint16_t)(len + hdr_len);
24554 		ipha->ipha_length = htons(ip_len);
24555 
24556 		/*
24557 		 * Set the IP header checksum.	Note that mp is just
24558 		 * the header, so this is easy to pass to ip_csum.
24559 		 */
24560 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24561 
24562 		/* Attach a transmit header, if any, and ship it. */
24563 		if (pkt_type == OB_PKT) {
24564 			UPDATE_OB_PKT_COUNT(ire);
24565 		} else {
24566 			out_ill = (ill_t *)q->q_ptr;
24567 			BUMP_MIB(out_ill->ill_ip_mib,
24568 			    ipIfStatsHCOutForwDatagrams);
24569 			UPDATE_IB_PKT_COUNT(ire);
24570 		}
24571 
24572 		if (ire->ire_flags & RTF_MULTIRT) {
24573 			irb = ire->ire_bucket;
24574 			ASSERT(irb != NULL);
24575 
24576 			multirt_send = B_TRUE;
24577 
24578 			/*
24579 			 * Save the original ire; we will need to restore it
24580 			 * for the tailing frags.
24581 			 */
24582 			save_ire = ire;
24583 			IRE_REFHOLD(save_ire);
24584 		}
24585 		/*
24586 		 * Emission loop for this fragment, similar
24587 		 * to what is done for the first fragment.
24588 		 */
24589 		do {
24590 			if (multirt_send) {
24591 				/*
24592 				 * We are in a multiple send case, need to get
24593 				 * the next ire and make a copy of the packet.
24594 				 */
24595 				ASSERT(irb != NULL);
24596 				IRB_REFHOLD(irb);
24597 				for (ire1 = ire->ire_next;
24598 				    ire1 != NULL;
24599 				    ire1 = ire1->ire_next) {
24600 					if (!(ire1->ire_flags & RTF_MULTIRT))
24601 						continue;
24602 					if (ire1->ire_addr != ire->ire_addr)
24603 						continue;
24604 					if (ire1->ire_marks &
24605 					    (IRE_MARK_CONDEMNED|
24606 					    IRE_MARK_HIDDEN)) {
24607 						continue;
24608 					}
24609 					/*
24610 					 * Ensure we do not exceed the MTU
24611 					 * of the next route.
24612 					 */
24613 					if (ire1->ire_max_frag < max_frag) {
24614 						ip_multirt_bad_mtu(ire1,
24615 						    max_frag);
24616 						continue;
24617 					}
24618 
24619 					/* Got one. */
24620 					IRE_REFHOLD(ire1);
24621 					break;
24622 				}
24623 				IRB_REFRELE(irb);
24624 
24625 				if (ire1 != NULL) {
24626 					next_mp = copyb(mp);
24627 					if ((next_mp == NULL) ||
24628 					    ((mp->b_cont != NULL) &&
24629 					    ((next_mp->b_cont =
24630 					    dupmsg(mp->b_cont)) == NULL))) {
24631 						freemsg(next_mp);
24632 						next_mp = NULL;
24633 						ire_refrele(ire1);
24634 						ire1 = NULL;
24635 					}
24636 				}
24637 
24638 				/* Last multiroute ire; don't loop anymore. */
24639 				if (ire1 == NULL) {
24640 					multirt_send = B_FALSE;
24641 				}
24642 			}
24643 
24644 			/* Update transmit header */
24645 			ll_hdr_len = 0;
24646 			LOCK_IRE_FP_MP(ire);
24647 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24648 			if (ll_hdr_mp != NULL) {
24649 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24650 				ll_hdr_len = MBLKL(ll_hdr_mp);
24651 			} else {
24652 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24653 			}
24654 
24655 			if (!ll_hdr_mp) {
24656 				xmit_mp = mp;
24657 
24658 			/*
24659 			 * We have link-layer header that can fit in
24660 			 * our mblk.
24661 			 */
24662 			} else if (mp->b_datap->db_ref == 1 &&
24663 			    ll_hdr_len != 0 &&
24664 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24665 				/* M_DATA fastpath */
24666 				mp->b_rptr -= ll_hdr_len;
24667 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24668 				    ll_hdr_len);
24669 				xmit_mp = mp;
24670 
24671 			/*
24672 			 * Case of res_mp OR the fastpath mp can't fit
24673 			 * in the mblk
24674 			 */
24675 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24676 				xmit_mp->b_cont = mp;
24677 				if (DB_CRED(mp) != NULL)
24678 					mblk_setcred(xmit_mp, DB_CRED(mp));
24679 				/* Get priority marking, if any. */
24680 				if (DB_TYPE(xmit_mp) == M_DATA)
24681 					xmit_mp->b_band = mp->b_band;
24682 
24683 			/* Corner case if copyb failed */
24684 			} else {
24685 				/*
24686 				 * Exit both the replication and
24687 				 * fragmentation loops.
24688 				 */
24689 				UNLOCK_IRE_FP_MP(ire);
24690 				goto drop_pkt;
24691 			}
24692 			UNLOCK_IRE_FP_MP(ire);
24693 
24694 			mp1 = mp;
24695 			out_ill = (ill_t *)q->q_ptr;
24696 
24697 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24698 
24699 			DTRACE_PROBE4(ip4__physical__out__start,
24700 			    ill_t *, NULL, ill_t *, out_ill,
24701 			    ipha_t *, ipha, mblk_t *, xmit_mp);
24702 
24703 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
24704 			    ipst->ips_ipv4firewall_physical_out,
24705 			    NULL, out_ill, ipha, xmit_mp, mp, ipst);
24706 
24707 			DTRACE_PROBE1(ip4__physical__out__end,
24708 			    mblk_t *, xmit_mp);
24709 
24710 			if (mp != mp1 && hdr_mp == mp1)
24711 				hdr_mp = mp;
24712 			if (mp != mp1 && mp_orig == mp1)
24713 				mp_orig = mp;
24714 
24715 			if (xmit_mp != NULL) {
24716 				putnext(q, xmit_mp);
24717 
24718 				BUMP_MIB(out_ill->ill_ip_mib,
24719 				    ipIfStatsHCOutTransmits);
24720 				UPDATE_MIB(out_ill->ill_ip_mib,
24721 				    ipIfStatsHCOutOctets, ip_len);
24722 
24723 				if (pkt_type != OB_PKT) {
24724 					/*
24725 					 * Update the packet count of trailing
24726 					 * RTF_MULTIRT ires.
24727 					 */
24728 					UPDATE_OB_PKT_COUNT(ire);
24729 				}
24730 			}
24731 
24732 			/* All done if we just consumed the hdr_mp. */
24733 			if (mp == hdr_mp) {
24734 				last_frag = B_TRUE;
24735 				BUMP_MIB(out_ill->ill_ip_mib,
24736 				    ipIfStatsOutFragOKs);
24737 			}
24738 
24739 			if (multirt_send) {
24740 				/*
24741 				 * We are in a multiple send case; look for
24742 				 * the next ire and re-enter the loop.
24743 				 */
24744 				ASSERT(ire1);
24745 				ASSERT(next_mp);
24746 				/* REFRELE the current ire before looping */
24747 				ire_refrele(ire);
24748 				ire = ire1;
24749 				ire1 = NULL;
24750 				q = ire->ire_stq;
24751 				mp = next_mp;
24752 				next_mp = NULL;
24753 			}
24754 		} while (multirt_send);
24755 		/*
24756 		 * Restore the original ire; we need it for the
24757 		 * trailing frags
24758 		 */
24759 		if (save_ire != NULL) {
24760 			ASSERT(ire1 == NULL);
24761 			/* REFRELE the last iterated ire */
24762 			ire_refrele(ire);
24763 			/* save_ire has been REFHOLDed */
24764 			ire = save_ire;
24765 			q = ire->ire_stq;
24766 			save_ire = NULL;
24767 		}
24768 
24769 		if (last_frag) {
24770 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24771 			    "ip_wput_frag_end:(%S)",
24772 			    "consumed hdr_mp");
24773 
24774 			if (first_ire != NULL)
24775 				ire_refrele(first_ire);
24776 			return;
24777 		}
24778 		/* Otherwise, advance and loop. */
24779 		offset += len;
24780 	}
24781 
24782 drop_pkt:
24783 	/* Clean up following allocation failure. */
24784 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24785 	freemsg(mp);
24786 	if (mp != hdr_mp)
24787 		freeb(hdr_mp);
24788 	if (mp != mp_orig)
24789 		freemsg(mp_orig);
24790 
24791 	if (save_ire != NULL)
24792 		IRE_REFRELE(save_ire);
24793 	if (first_ire != NULL)
24794 		ire_refrele(first_ire);
24795 
24796 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24797 	    "ip_wput_frag_end:(%S)",
24798 	    "end--alloc failure");
24799 }
24800 
24801 /*
24802  * Copy the header plus those options which have the copy bit set
24803  */
24804 static mblk_t *
24805 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst)
24806 {
24807 	mblk_t	*mp;
24808 	uchar_t	*up;
24809 
24810 	/*
24811 	 * Quick check if we need to look for options without the copy bit
24812 	 * set
24813 	 */
24814 	mp = allocb(ipst->ips_ip_wroff_extra + hdr_len, BPRI_HI);
24815 	if (!mp)
24816 		return (mp);
24817 	mp->b_rptr += ipst->ips_ip_wroff_extra;
24818 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
24819 		bcopy(rptr, mp->b_rptr, hdr_len);
24820 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
24821 		return (mp);
24822 	}
24823 	up  = mp->b_rptr;
24824 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
24825 	up += IP_SIMPLE_HDR_LENGTH;
24826 	rptr += IP_SIMPLE_HDR_LENGTH;
24827 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
24828 	while (hdr_len > 0) {
24829 		uint32_t optval;
24830 		uint32_t optlen;
24831 
24832 		optval = *rptr;
24833 		if (optval == IPOPT_EOL)
24834 			break;
24835 		if (optval == IPOPT_NOP)
24836 			optlen = 1;
24837 		else
24838 			optlen = rptr[1];
24839 		if (optval & IPOPT_COPY) {
24840 			bcopy(rptr, up, optlen);
24841 			up += optlen;
24842 		}
24843 		rptr += optlen;
24844 		hdr_len -= optlen;
24845 	}
24846 	/*
24847 	 * Make sure that we drop an even number of words by filling
24848 	 * with EOL to the next word boundary.
24849 	 */
24850 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
24851 	    hdr_len & 0x3; hdr_len++)
24852 		*up++ = IPOPT_EOL;
24853 	mp->b_wptr = up;
24854 	/* Update header length */
24855 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
24856 	return (mp);
24857 }
24858 
24859 /*
24860  * Delivery to local recipients including fanout to multiple recipients.
24861  * Does not do checksumming of UDP/TCP.
24862  * Note: q should be the read side queue for either the ill or conn.
24863  * Note: rq should be the read side q for the lower (ill) stream.
24864  * We don't send packets to IPPF processing, thus the last argument
24865  * to all the fanout calls are B_FALSE.
24866  */
24867 void
24868 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
24869     int fanout_flags, zoneid_t zoneid)
24870 {
24871 	uint32_t	protocol;
24872 	mblk_t		*first_mp;
24873 	boolean_t	mctl_present;
24874 	int		ire_type;
24875 #define	rptr	((uchar_t *)ipha)
24876 	ip_stack_t	*ipst = ill->ill_ipst;
24877 
24878 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
24879 	    "ip_wput_local_start: q %p", q);
24880 
24881 	if (ire != NULL) {
24882 		ire_type = ire->ire_type;
24883 	} else {
24884 		/*
24885 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
24886 		 * packet is not multicast, we can't tell the ire type.
24887 		 */
24888 		ASSERT(CLASSD(ipha->ipha_dst));
24889 		ire_type = IRE_BROADCAST;
24890 	}
24891 
24892 	first_mp = mp;
24893 	if (first_mp->b_datap->db_type == M_CTL) {
24894 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
24895 		if (!io->ipsec_out_secure) {
24896 			/*
24897 			 * This ipsec_out_t was allocated in ip_wput
24898 			 * for multicast packets to store the ill_index.
24899 			 * As this is being delivered locally, we don't
24900 			 * need this anymore.
24901 			 */
24902 			mp = first_mp->b_cont;
24903 			freeb(first_mp);
24904 			first_mp = mp;
24905 			mctl_present = B_FALSE;
24906 		} else {
24907 			/*
24908 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
24909 			 * security properties for the looped-back packet.
24910 			 */
24911 			mctl_present = B_TRUE;
24912 			mp = first_mp->b_cont;
24913 			ASSERT(mp != NULL);
24914 			ipsec_out_to_in(first_mp);
24915 		}
24916 	} else {
24917 		mctl_present = B_FALSE;
24918 	}
24919 
24920 	DTRACE_PROBE4(ip4__loopback__in__start,
24921 	    ill_t *, ill, ill_t *, NULL,
24922 	    ipha_t *, ipha, mblk_t *, first_mp);
24923 
24924 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
24925 	    ipst->ips_ipv4firewall_loopback_in,
24926 	    ill, NULL, ipha, first_mp, mp, ipst);
24927 
24928 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
24929 
24930 	if (first_mp == NULL)
24931 		return;
24932 
24933 	ipst->ips_loopback_packets++;
24934 
24935 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
24936 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
24937 	if (!IS_SIMPLE_IPH(ipha)) {
24938 		ip_wput_local_options(ipha, ipst);
24939 	}
24940 
24941 	protocol = ipha->ipha_protocol;
24942 	switch (protocol) {
24943 	case IPPROTO_ICMP: {
24944 		ire_t		*ire_zone;
24945 		ilm_t		*ilm;
24946 		mblk_t		*mp1;
24947 		zoneid_t	last_zoneid;
24948 
24949 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(ill)) {
24950 			ASSERT(ire_type == IRE_BROADCAST);
24951 			/*
24952 			 * In the multicast case, applications may have joined
24953 			 * the group from different zones, so we need to deliver
24954 			 * the packet to each of them. Loop through the
24955 			 * multicast memberships structures (ilm) on the receive
24956 			 * ill and send a copy of the packet up each matching
24957 			 * one. However, we don't do this for multicasts sent on
24958 			 * the loopback interface (PHYI_LOOPBACK flag set) as
24959 			 * they must stay in the sender's zone.
24960 			 *
24961 			 * ilm_add_v6() ensures that ilms in the same zone are
24962 			 * contiguous in the ill_ilm list. We use this property
24963 			 * to avoid sending duplicates needed when two
24964 			 * applications in the same zone join the same group on
24965 			 * different logical interfaces: we ignore the ilm if
24966 			 * it's zoneid is the same as the last matching one.
24967 			 * In addition, the sending of the packet for
24968 			 * ire_zoneid is delayed until all of the other ilms
24969 			 * have been exhausted.
24970 			 */
24971 			last_zoneid = -1;
24972 			ILM_WALKER_HOLD(ill);
24973 			for (ilm = ill->ill_ilm; ilm != NULL;
24974 			    ilm = ilm->ilm_next) {
24975 				if ((ilm->ilm_flags & ILM_DELETED) ||
24976 				    ipha->ipha_dst != ilm->ilm_addr ||
24977 				    ilm->ilm_zoneid == last_zoneid ||
24978 				    ilm->ilm_zoneid == zoneid ||
24979 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
24980 					continue;
24981 				mp1 = ip_copymsg(first_mp);
24982 				if (mp1 == NULL)
24983 					continue;
24984 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
24985 				    mctl_present, B_FALSE, ill,
24986 				    ilm->ilm_zoneid);
24987 				last_zoneid = ilm->ilm_zoneid;
24988 			}
24989 			ILM_WALKER_RELE(ill);
24990 			/*
24991 			 * Loopback case: the sending endpoint has
24992 			 * IP_MULTICAST_LOOP disabled, therefore we don't
24993 			 * dispatch the multicast packet to the sending zone.
24994 			 */
24995 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
24996 				freemsg(first_mp);
24997 				return;
24998 			}
24999 		} else if (ire_type == IRE_BROADCAST) {
25000 			/*
25001 			 * In the broadcast case, there may be many zones
25002 			 * which need a copy of the packet delivered to them.
25003 			 * There is one IRE_BROADCAST per broadcast address
25004 			 * and per zone; we walk those using a helper function.
25005 			 * In addition, the sending of the packet for zoneid is
25006 			 * delayed until all of the other ires have been
25007 			 * processed.
25008 			 */
25009 			IRB_REFHOLD(ire->ire_bucket);
25010 			ire_zone = NULL;
25011 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25012 			    ire)) != NULL) {
25013 				mp1 = ip_copymsg(first_mp);
25014 				if (mp1 == NULL)
25015 					continue;
25016 
25017 				UPDATE_IB_PKT_COUNT(ire_zone);
25018 				ire_zone->ire_last_used_time = lbolt;
25019 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25020 				    mctl_present, B_FALSE, ill,
25021 				    ire_zone->ire_zoneid);
25022 			}
25023 			IRB_REFRELE(ire->ire_bucket);
25024 		}
25025 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25026 		    0, mctl_present, B_FALSE, ill, zoneid);
25027 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25028 		    "ip_wput_local_end: q %p (%S)",
25029 		    q, "icmp");
25030 		return;
25031 	}
25032 	case IPPROTO_IGMP:
25033 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25034 			/* Bad packet - discarded by igmp_input */
25035 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25036 			    "ip_wput_local_end: q %p (%S)",
25037 			    q, "igmp_input--bad packet");
25038 			if (mctl_present)
25039 				freeb(first_mp);
25040 			return;
25041 		}
25042 		/*
25043 		 * igmp_input() may have returned the pulled up message.
25044 		 * So first_mp and ipha need to be reinitialized.
25045 		 */
25046 		ipha = (ipha_t *)mp->b_rptr;
25047 		if (mctl_present)
25048 			first_mp->b_cont = mp;
25049 		else
25050 			first_mp = mp;
25051 		/* deliver to local raw users */
25052 		break;
25053 	case IPPROTO_ENCAP:
25054 		/*
25055 		 * This case is covered by either ip_fanout_proto, or by
25056 		 * the above security processing for self-tunneled packets.
25057 		 */
25058 		break;
25059 	case IPPROTO_UDP: {
25060 		uint16_t	*up;
25061 		uint32_t	ports;
25062 
25063 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25064 		    UDP_PORTS_OFFSET);
25065 		/* Force a 'valid' checksum. */
25066 		up[3] = 0;
25067 
25068 		ports = *(uint32_t *)up;
25069 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25070 		    (ire_type == IRE_BROADCAST),
25071 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25072 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25073 		    ill, zoneid);
25074 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25075 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25076 		return;
25077 	}
25078 	case IPPROTO_TCP: {
25079 
25080 		/*
25081 		 * For TCP, discard broadcast packets.
25082 		 */
25083 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25084 			freemsg(first_mp);
25085 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25086 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25087 			return;
25088 		}
25089 
25090 		if (mp->b_datap->db_type == M_DATA) {
25091 			/*
25092 			 * M_DATA mblk, so init mblk (chain) for no struio().
25093 			 */
25094 			mblk_t	*mp1 = mp;
25095 
25096 			do {
25097 				mp1->b_datap->db_struioflag = 0;
25098 			} while ((mp1 = mp1->b_cont) != NULL);
25099 		}
25100 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25101 		    <= mp->b_wptr);
25102 		ip_fanout_tcp(q, first_mp, ill, ipha,
25103 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25104 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25105 		    mctl_present, B_FALSE, zoneid);
25106 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25107 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25108 		return;
25109 	}
25110 	case IPPROTO_SCTP:
25111 	{
25112 		uint32_t	ports;
25113 
25114 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25115 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25116 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25117 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25118 		return;
25119 	}
25120 
25121 	default:
25122 		break;
25123 	}
25124 	/*
25125 	 * Find a client for some other protocol.  We give
25126 	 * copies to multiple clients, if more than one is
25127 	 * bound.
25128 	 */
25129 	ip_fanout_proto(q, first_mp, ill, ipha,
25130 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25131 	    mctl_present, B_FALSE, ill, zoneid);
25132 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25133 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25134 #undef	rptr
25135 }
25136 
25137 /*
25138  * Update any source route, record route, or timestamp options.
25139  * Check that we are at end of strict source route.
25140  * The options have been sanity checked by ip_wput_options().
25141  */
25142 static void
25143 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25144 {
25145 	ipoptp_t	opts;
25146 	uchar_t		*opt;
25147 	uint8_t		optval;
25148 	uint8_t		optlen;
25149 	ipaddr_t	dst;
25150 	uint32_t	ts;
25151 	ire_t		*ire;
25152 	timestruc_t	now;
25153 
25154 	ip2dbg(("ip_wput_local_options\n"));
25155 	for (optval = ipoptp_first(&opts, ipha);
25156 	    optval != IPOPT_EOL;
25157 	    optval = ipoptp_next(&opts)) {
25158 		opt = opts.ipoptp_cur;
25159 		optlen = opts.ipoptp_len;
25160 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25161 		switch (optval) {
25162 			uint32_t off;
25163 		case IPOPT_SSRR:
25164 		case IPOPT_LSRR:
25165 			off = opt[IPOPT_OFFSET];
25166 			off--;
25167 			if (optlen < IP_ADDR_LEN ||
25168 			    off > optlen - IP_ADDR_LEN) {
25169 				/* End of source route */
25170 				break;
25171 			}
25172 			/*
25173 			 * This will only happen if two consecutive entries
25174 			 * in the source route contains our address or if
25175 			 * it is a packet with a loose source route which
25176 			 * reaches us before consuming the whole source route
25177 			 */
25178 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25179 			if (optval == IPOPT_SSRR) {
25180 				return;
25181 			}
25182 			/*
25183 			 * Hack: instead of dropping the packet truncate the
25184 			 * source route to what has been used by filling the
25185 			 * rest with IPOPT_NOP.
25186 			 */
25187 			opt[IPOPT_OLEN] = (uint8_t)off;
25188 			while (off < optlen) {
25189 				opt[off++] = IPOPT_NOP;
25190 			}
25191 			break;
25192 		case IPOPT_RR:
25193 			off = opt[IPOPT_OFFSET];
25194 			off--;
25195 			if (optlen < IP_ADDR_LEN ||
25196 			    off > optlen - IP_ADDR_LEN) {
25197 				/* No more room - ignore */
25198 				ip1dbg((
25199 				    "ip_wput_forward_options: end of RR\n"));
25200 				break;
25201 			}
25202 			dst = htonl(INADDR_LOOPBACK);
25203 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25204 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25205 			break;
25206 		case IPOPT_TS:
25207 			/* Insert timestamp if there is romm */
25208 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25209 			case IPOPT_TS_TSONLY:
25210 				off = IPOPT_TS_TIMELEN;
25211 				break;
25212 			case IPOPT_TS_PRESPEC:
25213 			case IPOPT_TS_PRESPEC_RFC791:
25214 				/* Verify that the address matched */
25215 				off = opt[IPOPT_OFFSET] - 1;
25216 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25217 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25218 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25219 				    ipst);
25220 				if (ire == NULL) {
25221 					/* Not for us */
25222 					break;
25223 				}
25224 				ire_refrele(ire);
25225 				/* FALLTHRU */
25226 			case IPOPT_TS_TSANDADDR:
25227 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25228 				break;
25229 			default:
25230 				/*
25231 				 * ip_*put_options should have already
25232 				 * dropped this packet.
25233 				 */
25234 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25235 				    "unknown IT - bug in ip_wput_options?\n");
25236 				return;	/* Keep "lint" happy */
25237 			}
25238 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25239 				/* Increase overflow counter */
25240 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25241 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25242 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25243 				    (off << 4);
25244 				break;
25245 			}
25246 			off = opt[IPOPT_OFFSET] - 1;
25247 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25248 			case IPOPT_TS_PRESPEC:
25249 			case IPOPT_TS_PRESPEC_RFC791:
25250 			case IPOPT_TS_TSANDADDR:
25251 				dst = htonl(INADDR_LOOPBACK);
25252 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25253 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25254 				/* FALLTHRU */
25255 			case IPOPT_TS_TSONLY:
25256 				off = opt[IPOPT_OFFSET] - 1;
25257 				/* Compute # of milliseconds since midnight */
25258 				gethrestime(&now);
25259 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25260 				    now.tv_nsec / (NANOSEC / MILLISEC);
25261 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25262 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25263 				break;
25264 			}
25265 			break;
25266 		}
25267 	}
25268 }
25269 
25270 /*
25271  * Send out a multicast packet on interface ipif.
25272  * The sender does not have an conn.
25273  * Caller verifies that this isn't a PHYI_LOOPBACK.
25274  */
25275 void
25276 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25277 {
25278 	ipha_t	*ipha;
25279 	ire_t	*ire;
25280 	ipaddr_t	dst;
25281 	mblk_t		*first_mp;
25282 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25283 
25284 	/* igmp_sendpkt always allocates a ipsec_out_t */
25285 	ASSERT(mp->b_datap->db_type == M_CTL);
25286 	ASSERT(!ipif->ipif_isv6);
25287 	ASSERT(!IS_LOOPBACK(ipif->ipif_ill));
25288 
25289 	first_mp = mp;
25290 	mp = first_mp->b_cont;
25291 	ASSERT(mp->b_datap->db_type == M_DATA);
25292 	ipha = (ipha_t *)mp->b_rptr;
25293 
25294 	/*
25295 	 * Find an IRE which matches the destination and the outgoing
25296 	 * queue (i.e. the outgoing interface.)
25297 	 */
25298 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25299 		dst = ipif->ipif_pp_dst_addr;
25300 	else
25301 		dst = ipha->ipha_dst;
25302 	/*
25303 	 * The source address has already been initialized by the
25304 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25305 	 * be sufficient rather than MATCH_IRE_IPIF.
25306 	 *
25307 	 * This function is used for sending IGMP packets. We need
25308 	 * to make sure that we send the packet out of the interface
25309 	 * (ipif->ipif_ill) where we joined the group. This is to
25310 	 * prevent from switches doing IGMP snooping to send us multicast
25311 	 * packets for a given group on the interface we have joined.
25312 	 * If we can't find an ire, igmp_sendpkt has already initialized
25313 	 * ipsec_out_attach_if so that this will not be load spread in
25314 	 * ip_newroute_ipif.
25315 	 */
25316 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25317 	    MATCH_IRE_ILL, ipst);
25318 	if (!ire) {
25319 		/*
25320 		 * Mark this packet to make it be delivered to
25321 		 * ip_wput_ire after the new ire has been
25322 		 * created.
25323 		 */
25324 		mp->b_prev = NULL;
25325 		mp->b_next = NULL;
25326 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25327 		    zoneid, &zero_info);
25328 		return;
25329 	}
25330 
25331 	/*
25332 	 * Honor the RTF_SETSRC flag; this is the only case
25333 	 * where we force this addr whatever the current src addr is,
25334 	 * because this address is set by igmp_sendpkt(), and
25335 	 * cannot be specified by any user.
25336 	 */
25337 	if (ire->ire_flags & RTF_SETSRC) {
25338 		ipha->ipha_src = ire->ire_src_addr;
25339 	}
25340 
25341 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25342 }
25343 
25344 /*
25345  * NOTE : This function does not ire_refrele the ire argument passed in.
25346  *
25347  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25348  * failure. The nce_fp_mp can vanish any time in the case of
25349  * IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25350  * the ire_lock to access the nce_fp_mp in this case.
25351  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25352  * prepending a fastpath message IPQoS processing must precede it, we also set
25353  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25354  * (IPQoS might have set the b_band for CoS marking).
25355  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25356  * must follow it so that IPQoS can mark the dl_priority field for CoS
25357  * marking, if needed.
25358  */
25359 static mblk_t *
25360 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
25361 {
25362 	uint_t	hlen;
25363 	ipha_t *ipha;
25364 	mblk_t *mp1;
25365 	boolean_t qos_done = B_FALSE;
25366 	uchar_t	*ll_hdr;
25367 	ip_stack_t	*ipst = ire->ire_ipst;
25368 
25369 #define	rptr	((uchar_t *)ipha)
25370 
25371 	ipha = (ipha_t *)mp->b_rptr;
25372 	hlen = 0;
25373 	LOCK_IRE_FP_MP(ire);
25374 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25375 		ASSERT(DB_TYPE(mp1) == M_DATA);
25376 		/* Initiate IPPF processing */
25377 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25378 			UNLOCK_IRE_FP_MP(ire);
25379 			ip_process(proc, &mp, ill_index);
25380 			if (mp == NULL)
25381 				return (NULL);
25382 
25383 			ipha = (ipha_t *)mp->b_rptr;
25384 			LOCK_IRE_FP_MP(ire);
25385 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25386 				qos_done = B_TRUE;
25387 				goto no_fp_mp;
25388 			}
25389 			ASSERT(DB_TYPE(mp1) == M_DATA);
25390 		}
25391 		hlen = MBLKL(mp1);
25392 		/*
25393 		 * Check if we have enough room to prepend fastpath
25394 		 * header
25395 		 */
25396 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25397 			ll_hdr = rptr - hlen;
25398 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25399 			/*
25400 			 * Set the b_rptr to the start of the link layer
25401 			 * header
25402 			 */
25403 			mp->b_rptr = ll_hdr;
25404 			mp1 = mp;
25405 		} else {
25406 			mp1 = copyb(mp1);
25407 			if (mp1 == NULL)
25408 				goto unlock_err;
25409 			mp1->b_band = mp->b_band;
25410 			mp1->b_cont = mp;
25411 			/*
25412 			 * certain system generated traffic may not
25413 			 * have cred/label in ip header block. This
25414 			 * is true even for a labeled system. But for
25415 			 * labeled traffic, inherit the label in the
25416 			 * new header.
25417 			 */
25418 			if (DB_CRED(mp) != NULL)
25419 				mblk_setcred(mp1, DB_CRED(mp));
25420 			/*
25421 			 * XXX disable ICK_VALID and compute checksum
25422 			 * here; can happen if nce_fp_mp changes and
25423 			 * it can't be copied now due to insufficient
25424 			 * space. (unlikely, fp mp can change, but it
25425 			 * does not increase in length)
25426 			 */
25427 		}
25428 		UNLOCK_IRE_FP_MP(ire);
25429 	} else {
25430 no_fp_mp:
25431 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25432 		if (mp1 == NULL) {
25433 unlock_err:
25434 			UNLOCK_IRE_FP_MP(ire);
25435 			freemsg(mp);
25436 			return (NULL);
25437 		}
25438 		UNLOCK_IRE_FP_MP(ire);
25439 		mp1->b_cont = mp;
25440 		/*
25441 		 * certain system generated traffic may not
25442 		 * have cred/label in ip header block. This
25443 		 * is true even for a labeled system. But for
25444 		 * labeled traffic, inherit the label in the
25445 		 * new header.
25446 		 */
25447 		if (DB_CRED(mp) != NULL)
25448 			mblk_setcred(mp1, DB_CRED(mp));
25449 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25450 			ip_process(proc, &mp1, ill_index);
25451 			if (mp1 == NULL)
25452 				return (NULL);
25453 		}
25454 	}
25455 	return (mp1);
25456 #undef rptr
25457 }
25458 
25459 /*
25460  * Finish the outbound IPsec processing for an IPv6 packet. This function
25461  * is called from ipsec_out_process() if the IPsec packet was processed
25462  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25463  * asynchronously.
25464  */
25465 void
25466 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25467     ire_t *ire_arg)
25468 {
25469 	in6_addr_t *v6dstp;
25470 	ire_t *ire;
25471 	mblk_t *mp;
25472 	ip6_t *ip6h1;
25473 	uint_t	ill_index;
25474 	ipsec_out_t *io;
25475 	boolean_t attach_if, hwaccel;
25476 	uint32_t flags = IP6_NO_IPPOLICY;
25477 	int match_flags;
25478 	zoneid_t zoneid;
25479 	boolean_t ill_need_rele = B_FALSE;
25480 	boolean_t ire_need_rele = B_FALSE;
25481 	ip_stack_t	*ipst;
25482 
25483 	mp = ipsec_mp->b_cont;
25484 	ip6h1 = (ip6_t *)mp->b_rptr;
25485 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25486 	ASSERT(io->ipsec_out_ns != NULL);
25487 	ipst = io->ipsec_out_ns->netstack_ip;
25488 	ill_index = io->ipsec_out_ill_index;
25489 	if (io->ipsec_out_reachable) {
25490 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25491 	}
25492 	attach_if = io->ipsec_out_attach_if;
25493 	hwaccel = io->ipsec_out_accelerated;
25494 	zoneid = io->ipsec_out_zoneid;
25495 	ASSERT(zoneid != ALL_ZONES);
25496 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25497 	/* Multicast addresses should have non-zero ill_index. */
25498 	v6dstp = &ip6h->ip6_dst;
25499 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25500 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25501 	ASSERT(!attach_if || ill_index != 0);
25502 	if (ill_index != 0) {
25503 		if (ill == NULL) {
25504 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
25505 			    B_TRUE, ipst);
25506 
25507 			/* Failure case frees things for us. */
25508 			if (ill == NULL)
25509 				return;
25510 
25511 			ill_need_rele = B_TRUE;
25512 		}
25513 		/*
25514 		 * If this packet needs to go out on a particular interface
25515 		 * honor it.
25516 		 */
25517 		if (attach_if) {
25518 			match_flags = MATCH_IRE_ILL;
25519 
25520 			/*
25521 			 * Check if we need an ire that will not be
25522 			 * looked up by anybody else i.e. HIDDEN.
25523 			 */
25524 			if (ill_is_probeonly(ill)) {
25525 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25526 			}
25527 		}
25528 	}
25529 	ASSERT(mp != NULL);
25530 
25531 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25532 		boolean_t unspec_src;
25533 		ipif_t	*ipif;
25534 
25535 		/*
25536 		 * Use the ill_index to get the right ill.
25537 		 */
25538 		unspec_src = io->ipsec_out_unspec_src;
25539 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25540 		if (ipif == NULL) {
25541 			if (ill_need_rele)
25542 				ill_refrele(ill);
25543 			freemsg(ipsec_mp);
25544 			return;
25545 		}
25546 
25547 		if (ire_arg != NULL) {
25548 			ire = ire_arg;
25549 		} else {
25550 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25551 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25552 			ire_need_rele = B_TRUE;
25553 		}
25554 		if (ire != NULL) {
25555 			ipif_refrele(ipif);
25556 			/*
25557 			 * XXX Do the multicast forwarding now, as the IPsec
25558 			 * processing has been done.
25559 			 */
25560 			goto send;
25561 		}
25562 
25563 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25564 		mp->b_prev = NULL;
25565 		mp->b_next = NULL;
25566 
25567 		/*
25568 		 * If the IPsec packet was processed asynchronously,
25569 		 * drop it now.
25570 		 */
25571 		if (q == NULL) {
25572 			if (ill_need_rele)
25573 				ill_refrele(ill);
25574 			freemsg(ipsec_mp);
25575 			return;
25576 		}
25577 
25578 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
25579 		    unspec_src, zoneid);
25580 		ipif_refrele(ipif);
25581 	} else {
25582 		if (attach_if) {
25583 			ipif_t	*ipif;
25584 
25585 			ipif = ipif_get_next_ipif(NULL, ill);
25586 			if (ipif == NULL) {
25587 				if (ill_need_rele)
25588 					ill_refrele(ill);
25589 				freemsg(ipsec_mp);
25590 				return;
25591 			}
25592 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25593 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25594 			ire_need_rele = B_TRUE;
25595 			ipif_refrele(ipif);
25596 		} else {
25597 			if (ire_arg != NULL) {
25598 				ire = ire_arg;
25599 			} else {
25600 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL,
25601 				    ipst);
25602 				ire_need_rele = B_TRUE;
25603 			}
25604 		}
25605 		if (ire != NULL)
25606 			goto send;
25607 		/*
25608 		 * ire disappeared underneath.
25609 		 *
25610 		 * What we need to do here is the ip_newroute
25611 		 * logic to get the ire without doing the IPsec
25612 		 * processing. Follow the same old path. But this
25613 		 * time, ip_wput or ire_add_then_send will call us
25614 		 * directly as all the IPsec operations are done.
25615 		 */
25616 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25617 		mp->b_prev = NULL;
25618 		mp->b_next = NULL;
25619 
25620 		/*
25621 		 * If the IPsec packet was processed asynchronously,
25622 		 * drop it now.
25623 		 */
25624 		if (q == NULL) {
25625 			if (ill_need_rele)
25626 				ill_refrele(ill);
25627 			freemsg(ipsec_mp);
25628 			return;
25629 		}
25630 
25631 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25632 		    zoneid, ipst);
25633 	}
25634 	if (ill != NULL && ill_need_rele)
25635 		ill_refrele(ill);
25636 	return;
25637 send:
25638 	if (ill != NULL && ill_need_rele)
25639 		ill_refrele(ill);
25640 
25641 	/* Local delivery */
25642 	if (ire->ire_stq == NULL) {
25643 		ill_t	*out_ill;
25644 		ASSERT(q != NULL);
25645 
25646 		/* PFHooks: LOOPBACK_OUT */
25647 		out_ill = ire_to_ill(ire);
25648 
25649 		DTRACE_PROBE4(ip6__loopback__out__start,
25650 		    ill_t *, NULL, ill_t *, out_ill,
25651 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25652 
25653 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
25654 		    ipst->ips_ipv6firewall_loopback_out,
25655 		    NULL, out_ill, ip6h1, ipsec_mp, mp, ipst);
25656 
25657 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25658 
25659 		if (ipsec_mp != NULL)
25660 			ip_wput_local_v6(RD(q), out_ill,
25661 			    ip6h, ipsec_mp, ire, 0);
25662 		if (ire_need_rele)
25663 			ire_refrele(ire);
25664 		return;
25665 	}
25666 	/*
25667 	 * Everything is done. Send it out on the wire.
25668 	 * We force the insertion of a fragment header using the
25669 	 * IPH_FRAG_HDR flag in two cases:
25670 	 * - after reception of an ICMPv6 "packet too big" message
25671 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25672 	 * - for multirouted IPv6 packets, so that the receiver can
25673 	 *   discard duplicates according to their fragment identifier
25674 	 */
25675 	/* XXX fix flow control problems. */
25676 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25677 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25678 		if (hwaccel) {
25679 			/*
25680 			 * hardware acceleration does not handle these
25681 			 * "slow path" cases.
25682 			 */
25683 			/* IPsec KSTATS: should bump bean counter here. */
25684 			if (ire_need_rele)
25685 				ire_refrele(ire);
25686 			freemsg(ipsec_mp);
25687 			return;
25688 		}
25689 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25690 		    (mp->b_cont ? msgdsize(mp) :
25691 		    mp->b_wptr - (uchar_t *)ip6h)) {
25692 			/* IPsec KSTATS: should bump bean counter here. */
25693 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25694 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25695 			    msgdsize(mp)));
25696 			if (ire_need_rele)
25697 				ire_refrele(ire);
25698 			freemsg(ipsec_mp);
25699 			return;
25700 		}
25701 		ASSERT(mp->b_prev == NULL);
25702 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
25703 		    ntohs(ip6h->ip6_plen) +
25704 		    IPV6_HDR_LEN, ire->ire_max_frag));
25705 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
25706 		    ire->ire_max_frag);
25707 	} else {
25708 		UPDATE_OB_PKT_COUNT(ire);
25709 		ire->ire_last_used_time = lbolt;
25710 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
25711 	}
25712 	if (ire_need_rele)
25713 		ire_refrele(ire);
25714 	freeb(ipsec_mp);
25715 }
25716 
25717 void
25718 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
25719 {
25720 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
25721 	da_ipsec_t *hada;	/* data attributes */
25722 	ill_t *ill = (ill_t *)q->q_ptr;
25723 
25724 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
25725 
25726 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
25727 		/* IPsec KSTATS: Bump lose counter here! */
25728 		freemsg(mp);
25729 		return;
25730 	}
25731 
25732 	/*
25733 	 * It's an IPsec packet that must be
25734 	 * accelerated by the Provider, and the
25735 	 * outbound ill is IPsec acceleration capable.
25736 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
25737 	 * to the ill.
25738 	 * IPsec KSTATS: should bump packet counter here.
25739 	 */
25740 
25741 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
25742 	if (hada_mp == NULL) {
25743 		/* IPsec KSTATS: should bump packet counter here. */
25744 		freemsg(mp);
25745 		return;
25746 	}
25747 
25748 	hada_mp->b_datap->db_type = M_CTL;
25749 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
25750 	hada_mp->b_cont = mp;
25751 
25752 	hada = (da_ipsec_t *)hada_mp->b_rptr;
25753 	bzero(hada, sizeof (da_ipsec_t));
25754 	hada->da_type = IPHADA_M_CTL;
25755 
25756 	putnext(q, hada_mp);
25757 }
25758 
25759 /*
25760  * Finish the outbound IPsec processing. This function is called from
25761  * ipsec_out_process() if the IPsec packet was processed
25762  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25763  * asynchronously.
25764  */
25765 void
25766 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
25767     ire_t *ire_arg)
25768 {
25769 	uint32_t v_hlen_tos_len;
25770 	ipaddr_t	dst;
25771 	ipif_t	*ipif = NULL;
25772 	ire_t *ire;
25773 	ire_t *ire1 = NULL;
25774 	mblk_t *next_mp = NULL;
25775 	uint32_t max_frag;
25776 	boolean_t multirt_send = B_FALSE;
25777 	mblk_t *mp;
25778 	ipha_t *ipha1;
25779 	uint_t	ill_index;
25780 	ipsec_out_t *io;
25781 	boolean_t attach_if;
25782 	int match_flags;
25783 	irb_t *irb = NULL;
25784 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
25785 	zoneid_t zoneid;
25786 	ipxmit_state_t	pktxmit_state;
25787 	ip_stack_t	*ipst;
25788 
25789 #ifdef	_BIG_ENDIAN
25790 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
25791 #else
25792 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
25793 #endif
25794 
25795 	mp = ipsec_mp->b_cont;
25796 	ipha1 = (ipha_t *)mp->b_rptr;
25797 	ASSERT(mp != NULL);
25798 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
25799 	dst = ipha->ipha_dst;
25800 
25801 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25802 	ill_index = io->ipsec_out_ill_index;
25803 	attach_if = io->ipsec_out_attach_if;
25804 	zoneid = io->ipsec_out_zoneid;
25805 	ASSERT(zoneid != ALL_ZONES);
25806 	ipst = io->ipsec_out_ns->netstack_ip;
25807 	ASSERT(io->ipsec_out_ns != NULL);
25808 
25809 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25810 	if (ill_index != 0) {
25811 		if (ill == NULL) {
25812 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
25813 			    ill_index, B_FALSE, ipst);
25814 
25815 			/* Failure case frees things for us. */
25816 			if (ill == NULL)
25817 				return;
25818 
25819 			ill_need_rele = B_TRUE;
25820 		}
25821 		/*
25822 		 * If this packet needs to go out on a particular interface
25823 		 * honor it.
25824 		 */
25825 		if (attach_if) {
25826 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25827 
25828 			/*
25829 			 * Check if we need an ire that will not be
25830 			 * looked up by anybody else i.e. HIDDEN.
25831 			 */
25832 			if (ill_is_probeonly(ill)) {
25833 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25834 			}
25835 		}
25836 	}
25837 
25838 	if (CLASSD(dst)) {
25839 		boolean_t conn_dontroute;
25840 		/*
25841 		 * Use the ill_index to get the right ipif.
25842 		 */
25843 		conn_dontroute = io->ipsec_out_dontroute;
25844 		if (ill_index == 0)
25845 			ipif = ipif_lookup_group(dst, zoneid, ipst);
25846 		else
25847 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25848 		if (ipif == NULL) {
25849 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
25850 			    " multicast\n"));
25851 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
25852 			freemsg(ipsec_mp);
25853 			goto done;
25854 		}
25855 		/*
25856 		 * ipha_src has already been intialized with the
25857 		 * value of the ipif in ip_wput. All we need now is
25858 		 * an ire to send this downstream.
25859 		 */
25860 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
25861 		    MBLK_GETLABEL(mp), match_flags, ipst);
25862 		if (ire != NULL) {
25863 			ill_t *ill1;
25864 			/*
25865 			 * Do the multicast forwarding now, as the IPsec
25866 			 * processing has been done.
25867 			 */
25868 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
25869 			    (ill1 = ire_to_ill(ire))) {
25870 				if (ip_mforward(ill1, ipha, mp)) {
25871 					freemsg(ipsec_mp);
25872 					ip1dbg(("ip_wput_ipsec_out: mforward "
25873 					    "failed\n"));
25874 					ire_refrele(ire);
25875 					goto done;
25876 				}
25877 			}
25878 			goto send;
25879 		}
25880 
25881 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
25882 		mp->b_prev = NULL;
25883 		mp->b_next = NULL;
25884 
25885 		/*
25886 		 * If the IPsec packet was processed asynchronously,
25887 		 * drop it now.
25888 		 */
25889 		if (q == NULL) {
25890 			freemsg(ipsec_mp);
25891 			goto done;
25892 		}
25893 
25894 		/*
25895 		 * We may be using a wrong ipif to create the ire.
25896 		 * But it is okay as the source address is assigned
25897 		 * for the packet already. Next outbound packet would
25898 		 * create the IRE with the right IPIF in ip_wput.
25899 		 *
25900 		 * Also handle RTF_MULTIRT routes.
25901 		 */
25902 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
25903 		    zoneid, &zero_info);
25904 	} else {
25905 		if (attach_if) {
25906 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
25907 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25908 		} else {
25909 			if (ire_arg != NULL) {
25910 				ire = ire_arg;
25911 				ire_need_rele = B_FALSE;
25912 			} else {
25913 				ire = ire_cache_lookup(dst, zoneid,
25914 				    MBLK_GETLABEL(mp), ipst);
25915 			}
25916 		}
25917 		if (ire != NULL) {
25918 			goto send;
25919 		}
25920 
25921 		/*
25922 		 * ire disappeared underneath.
25923 		 *
25924 		 * What we need to do here is the ip_newroute
25925 		 * logic to get the ire without doing the IPsec
25926 		 * processing. Follow the same old path. But this
25927 		 * time, ip_wput or ire_add_then_put will call us
25928 		 * directly as all the IPsec operations are done.
25929 		 */
25930 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
25931 		mp->b_prev = NULL;
25932 		mp->b_next = NULL;
25933 
25934 		/*
25935 		 * If the IPsec packet was processed asynchronously,
25936 		 * drop it now.
25937 		 */
25938 		if (q == NULL) {
25939 			freemsg(ipsec_mp);
25940 			goto done;
25941 		}
25942 
25943 		/*
25944 		 * Since we're going through ip_newroute() again, we
25945 		 * need to make sure we don't:
25946 		 *
25947 		 *	1.) Trigger the ASSERT() with the ipha_ident
25948 		 *	    overloading.
25949 		 *	2.) Redo transport-layer checksumming, since we've
25950 		 *	    already done all that to get this far.
25951 		 *
25952 		 * The easiest way not do either of the above is to set
25953 		 * the ipha_ident field to IP_HDR_INCLUDED.
25954 		 */
25955 		ipha->ipha_ident = IP_HDR_INCLUDED;
25956 		ip_newroute(q, ipsec_mp, dst, (CONN_Q(q) ? Q_TO_CONN(q) : NULL),
25957 		    zoneid, ipst);
25958 	}
25959 	goto done;
25960 send:
25961 	if (ire->ire_stq == NULL) {
25962 		ill_t	*out_ill;
25963 		/*
25964 		 * Loopbacks go through ip_wput_local except for one case.
25965 		 * We come here if we generate a icmp_frag_needed message
25966 		 * after IPsec processing is over. When this function calls
25967 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
25968 		 * icmp_frag_needed. The message generated comes back here
25969 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
25970 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
25971 		 * source address as it is usually set in ip_wput_ire. As
25972 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
25973 		 * and we end up here. We can't enter ip_wput_ire once the
25974 		 * IPsec processing is over and hence we need to do it here.
25975 		 */
25976 		ASSERT(q != NULL);
25977 		UPDATE_OB_PKT_COUNT(ire);
25978 		ire->ire_last_used_time = lbolt;
25979 		if (ipha->ipha_src == 0)
25980 			ipha->ipha_src = ire->ire_src_addr;
25981 
25982 		/* PFHooks: LOOPBACK_OUT */
25983 		out_ill = ire_to_ill(ire);
25984 
25985 		DTRACE_PROBE4(ip4__loopback__out__start,
25986 		    ill_t *, NULL, ill_t *, out_ill,
25987 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
25988 
25989 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
25990 		    ipst->ips_ipv4firewall_loopback_out,
25991 		    NULL, out_ill, ipha1, ipsec_mp, mp, ipst);
25992 
25993 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
25994 
25995 		if (ipsec_mp != NULL)
25996 			ip_wput_local(RD(q), out_ill,
25997 			    ipha, ipsec_mp, ire, 0, zoneid);
25998 		if (ire_need_rele)
25999 			ire_refrele(ire);
26000 		goto done;
26001 	}
26002 
26003 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
26004 		/*
26005 		 * We are through with IPsec processing.
26006 		 * Fragment this and send it on the wire.
26007 		 */
26008 		if (io->ipsec_out_accelerated) {
26009 			/*
26010 			 * The packet has been accelerated but must
26011 			 * be fragmented. This should not happen
26012 			 * since AH and ESP must not accelerate
26013 			 * packets that need fragmentation, however
26014 			 * the configuration could have changed
26015 			 * since the AH or ESP processing.
26016 			 * Drop packet.
26017 			 * IPsec KSTATS: bump bean counter here.
26018 			 */
26019 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
26020 			    "fragmented accelerated packet!\n"));
26021 			freemsg(ipsec_mp);
26022 		} else {
26023 			ip_wput_ire_fragmentit(ipsec_mp, ire, zoneid, ipst);
26024 		}
26025 		if (ire_need_rele)
26026 			ire_refrele(ire);
26027 		goto done;
26028 	}
26029 
26030 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
26031 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
26032 	    (void *)ire->ire_ipif, (void *)ipif));
26033 
26034 	/*
26035 	 * Multiroute the secured packet, unless IPsec really
26036 	 * requires the packet to go out only through a particular
26037 	 * interface.
26038 	 */
26039 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
26040 		ire_t *first_ire;
26041 		irb = ire->ire_bucket;
26042 		ASSERT(irb != NULL);
26043 		/*
26044 		 * This ire has been looked up as the one that
26045 		 * goes through the given ipif;
26046 		 * make sure we do not omit any other multiroute ire
26047 		 * that may be present in the bucket before this one.
26048 		 */
26049 		IRB_REFHOLD(irb);
26050 		for (first_ire = irb->irb_ire;
26051 		    first_ire != NULL;
26052 		    first_ire = first_ire->ire_next) {
26053 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
26054 			    (first_ire->ire_addr == ire->ire_addr) &&
26055 			    !(first_ire->ire_marks &
26056 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
26057 				break;
26058 			}
26059 		}
26060 
26061 		if ((first_ire != NULL) && (first_ire != ire)) {
26062 			/*
26063 			 * Don't change the ire if the packet must
26064 			 * be fragmented if sent via this new one.
26065 			 */
26066 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26067 				IRE_REFHOLD(first_ire);
26068 				if (ire_need_rele)
26069 					ire_refrele(ire);
26070 				else
26071 					ire_need_rele = B_TRUE;
26072 				ire = first_ire;
26073 			}
26074 		}
26075 		IRB_REFRELE(irb);
26076 
26077 		multirt_send = B_TRUE;
26078 		max_frag = ire->ire_max_frag;
26079 	} else {
26080 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
26081 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
26082 			    "flag, attach_if %d\n", attach_if));
26083 		}
26084 	}
26085 
26086 	/*
26087 	 * In most cases, the emission loop below is entered only once.
26088 	 * Only in the case where the ire holds the RTF_MULTIRT
26089 	 * flag, we loop to process all RTF_MULTIRT ires in the
26090 	 * bucket, and send the packet through all crossed
26091 	 * RTF_MULTIRT routes.
26092 	 */
26093 	do {
26094 		if (multirt_send) {
26095 			/*
26096 			 * ire1 holds here the next ire to process in the
26097 			 * bucket. If multirouting is expected,
26098 			 * any non-RTF_MULTIRT ire that has the
26099 			 * right destination address is ignored.
26100 			 */
26101 			ASSERT(irb != NULL);
26102 			IRB_REFHOLD(irb);
26103 			for (ire1 = ire->ire_next;
26104 			    ire1 != NULL;
26105 			    ire1 = ire1->ire_next) {
26106 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26107 					continue;
26108 				if (ire1->ire_addr != ire->ire_addr)
26109 					continue;
26110 				if (ire1->ire_marks &
26111 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
26112 					continue;
26113 				/* No loopback here */
26114 				if (ire1->ire_stq == NULL)
26115 					continue;
26116 				/*
26117 				 * Ensure we do not exceed the MTU
26118 				 * of the next route.
26119 				 */
26120 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26121 					ip_multirt_bad_mtu(ire1, max_frag);
26122 					continue;
26123 				}
26124 
26125 				IRE_REFHOLD(ire1);
26126 				break;
26127 			}
26128 			IRB_REFRELE(irb);
26129 			if (ire1 != NULL) {
26130 				/*
26131 				 * We are in a multiple send case, need to
26132 				 * make a copy of the packet.
26133 				 */
26134 				next_mp = copymsg(ipsec_mp);
26135 				if (next_mp == NULL) {
26136 					ire_refrele(ire1);
26137 					ire1 = NULL;
26138 				}
26139 			}
26140 		}
26141 		/*
26142 		 * Everything is done. Send it out on the wire
26143 		 *
26144 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26145 		 * either send it on the wire or, in the case of
26146 		 * HW acceleration, call ipsec_hw_putnext.
26147 		 */
26148 		if (ire->ire_nce &&
26149 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26150 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26151 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26152 			/*
26153 			 * If ire's link-layer is unresolved (this
26154 			 * would only happen if the incomplete ire
26155 			 * was added to cachetable via forwarding path)
26156 			 * don't bother going to ip_xmit_v4. Just drop the
26157 			 * packet.
26158 			 * There is a slight risk here, in that, if we
26159 			 * have the forwarding path create an incomplete
26160 			 * IRE, then until the IRE is completed, any
26161 			 * transmitted IPsec packets will be dropped
26162 			 * instead of being queued waiting for resolution.
26163 			 *
26164 			 * But the likelihood of a forwarding packet and a wput
26165 			 * packet sending to the same dst at the same time
26166 			 * and there not yet be an ARP entry for it is small.
26167 			 * Furthermore, if this actually happens, it might
26168 			 * be likely that wput would generate multiple
26169 			 * packets (and forwarding would also have a train
26170 			 * of packets) for that destination. If this is
26171 			 * the case, some of them would have been dropped
26172 			 * anyway, since ARP only queues a few packets while
26173 			 * waiting for resolution
26174 			 *
26175 			 * NOTE: We should really call ip_xmit_v4,
26176 			 * and let it queue the packet and send the
26177 			 * ARP query and have ARP come back thus:
26178 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26179 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26180 			 * hw accel work. But it's too complex to get
26181 			 * the IPsec hw  acceleration approach to fit
26182 			 * well with ip_xmit_v4 doing ARP without
26183 			 * doing IPsec simplification. For now, we just
26184 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26185 			 * that we can continue with the send on the next
26186 			 * attempt.
26187 			 *
26188 			 * XXX THis should be revisited, when
26189 			 * the IPsec/IP interaction is cleaned up
26190 			 */
26191 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26192 			    " - dropping packet\n"));
26193 			freemsg(ipsec_mp);
26194 			/*
26195 			 * Call ip_xmit_v4() to trigger ARP query
26196 			 * in case the nce_state is ND_INITIAL
26197 			 */
26198 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
26199 			goto drop_pkt;
26200 		}
26201 
26202 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26203 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26204 		    mblk_t *, ipsec_mp);
26205 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26206 		    ipst->ips_ipv4firewall_physical_out,
26207 		    NULL, ire->ire_ipif->ipif_ill, ipha1, ipsec_mp, mp, ipst);
26208 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, ipsec_mp);
26209 		if (ipsec_mp == NULL)
26210 			goto drop_pkt;
26211 
26212 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26213 		pktxmit_state = ip_xmit_v4(mp, ire,
26214 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE);
26215 
26216 		if ((pktxmit_state ==  SEND_FAILED) ||
26217 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26218 
26219 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26220 drop_pkt:
26221 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26222 			    ipIfStatsOutDiscards);
26223 			if (ire_need_rele)
26224 				ire_refrele(ire);
26225 			if (ire1 != NULL) {
26226 				ire_refrele(ire1);
26227 				freemsg(next_mp);
26228 			}
26229 			goto done;
26230 		}
26231 
26232 		freeb(ipsec_mp);
26233 		if (ire_need_rele)
26234 			ire_refrele(ire);
26235 
26236 		if (ire1 != NULL) {
26237 			ire = ire1;
26238 			ire_need_rele = B_TRUE;
26239 			ASSERT(next_mp);
26240 			ipsec_mp = next_mp;
26241 			mp = ipsec_mp->b_cont;
26242 			ire1 = NULL;
26243 			next_mp = NULL;
26244 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26245 		} else {
26246 			multirt_send = B_FALSE;
26247 		}
26248 	} while (multirt_send);
26249 done:
26250 	if (ill != NULL && ill_need_rele)
26251 		ill_refrele(ill);
26252 	if (ipif != NULL)
26253 		ipif_refrele(ipif);
26254 }
26255 
26256 /*
26257  * Get the ill corresponding to the specified ire, and compare its
26258  * capabilities with the protocol and algorithms specified by the
26259  * the SA obtained from ipsec_out. If they match, annotate the
26260  * ipsec_out structure to indicate that the packet needs acceleration.
26261  *
26262  *
26263  * A packet is eligible for outbound hardware acceleration if the
26264  * following conditions are satisfied:
26265  *
26266  * 1. the packet will not be fragmented
26267  * 2. the provider supports the algorithm
26268  * 3. there is no pending control message being exchanged
26269  * 4. snoop is not attached
26270  * 5. the destination address is not a broadcast or multicast address.
26271  *
26272  * Rationale:
26273  *	- Hardware drivers do not support fragmentation with
26274  *	  the current interface.
26275  *	- snoop, multicast, and broadcast may result in exposure of
26276  *	  a cleartext datagram.
26277  * We check all five of these conditions here.
26278  *
26279  * XXX would like to nuke "ire_t *" parameter here; problem is that
26280  * IRE is only way to figure out if a v4 address is a broadcast and
26281  * thus ineligible for acceleration...
26282  */
26283 static void
26284 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26285 {
26286 	ipsec_out_t *io;
26287 	mblk_t *data_mp;
26288 	uint_t plen, overhead;
26289 	ip_stack_t	*ipst;
26290 
26291 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26292 		return;
26293 
26294 	if (ill == NULL)
26295 		return;
26296 	ipst = ill->ill_ipst;
26297 	/*
26298 	 * Destination address is a broadcast or multicast.  Punt.
26299 	 */
26300 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26301 	    IRE_LOCAL)))
26302 		return;
26303 
26304 	data_mp = ipsec_mp->b_cont;
26305 
26306 	if (ill->ill_isv6) {
26307 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26308 
26309 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26310 			return;
26311 
26312 		plen = ip6h->ip6_plen;
26313 	} else {
26314 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26315 
26316 		if (CLASSD(ipha->ipha_dst))
26317 			return;
26318 
26319 		plen = ipha->ipha_length;
26320 	}
26321 	/*
26322 	 * Is there a pending DLPI control message being exchanged
26323 	 * between IP/IPsec and the DLS Provider? If there is, it
26324 	 * could be a SADB update, and the state of the DLS Provider
26325 	 * SADB might not be in sync with the SADB maintained by
26326 	 * IPsec. To avoid dropping packets or using the wrong keying
26327 	 * material, we do not accelerate this packet.
26328 	 */
26329 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26330 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26331 		    "ill_dlpi_pending! don't accelerate packet\n"));
26332 		return;
26333 	}
26334 
26335 	/*
26336 	 * Is the Provider in promiscous mode? If it does, we don't
26337 	 * accelerate the packet since it will bounce back up to the
26338 	 * listeners in the clear.
26339 	 */
26340 	if (ill->ill_promisc_on_phys) {
26341 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26342 		    "ill in promiscous mode, don't accelerate packet\n"));
26343 		return;
26344 	}
26345 
26346 	/*
26347 	 * Will the packet require fragmentation?
26348 	 */
26349 
26350 	/*
26351 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26352 	 * as is used elsewhere.
26353 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26354 	 *	+ 2-byte trailer
26355 	 */
26356 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26357 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26358 
26359 	if ((plen + overhead) > ill->ill_max_mtu)
26360 		return;
26361 
26362 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26363 
26364 	/*
26365 	 * Can the ill accelerate this IPsec protocol and algorithm
26366 	 * specified by the SA?
26367 	 */
26368 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26369 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26370 		return;
26371 	}
26372 
26373 	/*
26374 	 * Tell AH or ESP that the outbound ill is capable of
26375 	 * accelerating this packet.
26376 	 */
26377 	io->ipsec_out_is_capab_ill = B_TRUE;
26378 }
26379 
26380 /*
26381  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26382  *
26383  * If this function returns B_TRUE, the requested SA's have been filled
26384  * into the ipsec_out_*_sa pointers.
26385  *
26386  * If the function returns B_FALSE, the packet has been "consumed", most
26387  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26388  *
26389  * The SA references created by the protocol-specific "select"
26390  * function will be released when the ipsec_mp is freed, thanks to the
26391  * ipsec_out_free destructor -- see spd.c.
26392  */
26393 static boolean_t
26394 ipsec_out_select_sa(mblk_t *ipsec_mp)
26395 {
26396 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26397 	ipsec_out_t *io;
26398 	ipsec_policy_t *pp;
26399 	ipsec_action_t *ap;
26400 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26401 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26402 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26403 
26404 	if (!io->ipsec_out_secure) {
26405 		/*
26406 		 * We came here by mistake.
26407 		 * Don't bother with ipsec processing
26408 		 * We should "discourage" this path in the future.
26409 		 */
26410 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26411 		return (B_FALSE);
26412 	}
26413 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26414 	ASSERT((io->ipsec_out_policy != NULL) ||
26415 	    (io->ipsec_out_act != NULL));
26416 
26417 	ASSERT(io->ipsec_out_failed == B_FALSE);
26418 
26419 	/*
26420 	 * IPsec processing has started.
26421 	 */
26422 	io->ipsec_out_proc_begin = B_TRUE;
26423 	ap = io->ipsec_out_act;
26424 	if (ap == NULL) {
26425 		pp = io->ipsec_out_policy;
26426 		ASSERT(pp != NULL);
26427 		ap = pp->ipsp_act;
26428 		ASSERT(ap != NULL);
26429 	}
26430 
26431 	/*
26432 	 * We have an action.  now, let's select SA's.
26433 	 * (In the future, we can cache this in the conn_t..)
26434 	 */
26435 	if (ap->ipa_want_esp) {
26436 		if (io->ipsec_out_esp_sa == NULL) {
26437 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26438 			    IPPROTO_ESP);
26439 		}
26440 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26441 	}
26442 
26443 	if (ap->ipa_want_ah) {
26444 		if (io->ipsec_out_ah_sa == NULL) {
26445 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26446 			    IPPROTO_AH);
26447 		}
26448 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26449 		/*
26450 		 * The ESP and AH processing order needs to be preserved
26451 		 * when both protocols are required (ESP should be applied
26452 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26453 		 * when both ESP and AH are required, and an AH ACQUIRE
26454 		 * is needed.
26455 		 */
26456 		if (ap->ipa_want_esp && need_ah_acquire)
26457 			need_esp_acquire = B_TRUE;
26458 	}
26459 
26460 	/*
26461 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26462 	 * Release SAs that got referenced, but will not be used until we
26463 	 * acquire _all_ of the SAs we need.
26464 	 */
26465 	if (need_ah_acquire || need_esp_acquire) {
26466 		if (io->ipsec_out_ah_sa != NULL) {
26467 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26468 			io->ipsec_out_ah_sa = NULL;
26469 		}
26470 		if (io->ipsec_out_esp_sa != NULL) {
26471 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26472 			io->ipsec_out_esp_sa = NULL;
26473 		}
26474 
26475 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26476 		return (B_FALSE);
26477 	}
26478 
26479 	return (B_TRUE);
26480 }
26481 
26482 /*
26483  * Process an IPSEC_OUT message and see what you can
26484  * do with it.
26485  * IPQoS Notes:
26486  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26487  * IPsec.
26488  * XXX would like to nuke ire_t.
26489  * XXX ill_index better be "real"
26490  */
26491 void
26492 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26493 {
26494 	ipsec_out_t *io;
26495 	ipsec_policy_t *pp;
26496 	ipsec_action_t *ap;
26497 	ipha_t *ipha;
26498 	ip6_t *ip6h;
26499 	mblk_t *mp;
26500 	ill_t *ill;
26501 	zoneid_t zoneid;
26502 	ipsec_status_t ipsec_rc;
26503 	boolean_t ill_need_rele = B_FALSE;
26504 	ip_stack_t	*ipst;
26505 	ipsec_stack_t	*ipss;
26506 
26507 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26508 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26509 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26510 	ipst = io->ipsec_out_ns->netstack_ip;
26511 	mp = ipsec_mp->b_cont;
26512 
26513 	/*
26514 	 * Initiate IPPF processing. We do it here to account for packets
26515 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26516 	 * We can check for ipsec_out_proc_begin even for such packets, as
26517 	 * they will always be false (asserted below).
26518 	 */
26519 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26520 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26521 		    io->ipsec_out_ill_index : ill_index);
26522 		if (mp == NULL) {
26523 			ip2dbg(("ipsec_out_process: packet dropped "\
26524 			    "during IPPF processing\n"));
26525 			freeb(ipsec_mp);
26526 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26527 			return;
26528 		}
26529 	}
26530 
26531 	if (!io->ipsec_out_secure) {
26532 		/*
26533 		 * We came here by mistake.
26534 		 * Don't bother with ipsec processing
26535 		 * Should "discourage" this path in the future.
26536 		 */
26537 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26538 		goto done;
26539 	}
26540 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26541 	ASSERT((io->ipsec_out_policy != NULL) ||
26542 	    (io->ipsec_out_act != NULL));
26543 	ASSERT(io->ipsec_out_failed == B_FALSE);
26544 
26545 	ipss = ipst->ips_netstack->netstack_ipsec;
26546 	if (!ipsec_loaded(ipss)) {
26547 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26548 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26549 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26550 		} else {
26551 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26552 		}
26553 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26554 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26555 		    &ipss->ipsec_dropper);
26556 		return;
26557 	}
26558 
26559 	/*
26560 	 * IPsec processing has started.
26561 	 */
26562 	io->ipsec_out_proc_begin = B_TRUE;
26563 	ap = io->ipsec_out_act;
26564 	if (ap == NULL) {
26565 		pp = io->ipsec_out_policy;
26566 		ASSERT(pp != NULL);
26567 		ap = pp->ipsp_act;
26568 		ASSERT(ap != NULL);
26569 	}
26570 
26571 	/*
26572 	 * Save the outbound ill index. When the packet comes back
26573 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26574 	 * before sending it the accelerated packet.
26575 	 */
26576 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26577 		int ifindex;
26578 		ill = ire_to_ill(ire);
26579 		ifindex = ill->ill_phyint->phyint_ifindex;
26580 		io->ipsec_out_capab_ill_index = ifindex;
26581 	}
26582 
26583 	/*
26584 	 * The order of processing is first insert a IP header if needed.
26585 	 * Then insert the ESP header and then the AH header.
26586 	 */
26587 	if ((io->ipsec_out_se_done == B_FALSE) &&
26588 	    (ap->ipa_want_se)) {
26589 		/*
26590 		 * First get the outer IP header before sending
26591 		 * it to ESP.
26592 		 */
26593 		ipha_t *oipha, *iipha;
26594 		mblk_t *outer_mp, *inner_mp;
26595 
26596 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26597 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26598 			    "ipsec_out_process: "
26599 			    "Self-Encapsulation failed: Out of memory\n");
26600 			freemsg(ipsec_mp);
26601 			if (ill != NULL) {
26602 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26603 			} else {
26604 				BUMP_MIB(&ipst->ips_ip_mib,
26605 				    ipIfStatsOutDiscards);
26606 			}
26607 			return;
26608 		}
26609 		inner_mp = ipsec_mp->b_cont;
26610 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26611 		oipha = (ipha_t *)outer_mp->b_rptr;
26612 		iipha = (ipha_t *)inner_mp->b_rptr;
26613 		*oipha = *iipha;
26614 		outer_mp->b_wptr += sizeof (ipha_t);
26615 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26616 		    sizeof (ipha_t));
26617 		oipha->ipha_protocol = IPPROTO_ENCAP;
26618 		oipha->ipha_version_and_hdr_length =
26619 		    IP_SIMPLE_HDR_VERSION;
26620 		oipha->ipha_hdr_checksum = 0;
26621 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26622 		outer_mp->b_cont = inner_mp;
26623 		ipsec_mp->b_cont = outer_mp;
26624 
26625 		io->ipsec_out_se_done = B_TRUE;
26626 		io->ipsec_out_tunnel = B_TRUE;
26627 	}
26628 
26629 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26630 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26631 	    !ipsec_out_select_sa(ipsec_mp))
26632 		return;
26633 
26634 	/*
26635 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26636 	 * to do the heavy lifting.
26637 	 */
26638 	zoneid = io->ipsec_out_zoneid;
26639 	ASSERT(zoneid != ALL_ZONES);
26640 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26641 		ASSERT(io->ipsec_out_esp_sa != NULL);
26642 		io->ipsec_out_esp_done = B_TRUE;
26643 		/*
26644 		 * Note that since hw accel can only apply one transform,
26645 		 * not two, we skip hw accel for ESP if we also have AH
26646 		 * This is an design limitation of the interface
26647 		 * which should be revisited.
26648 		 */
26649 		ASSERT(ire != NULL);
26650 		if (io->ipsec_out_ah_sa == NULL) {
26651 			ill = (ill_t *)ire->ire_stq->q_ptr;
26652 			ipsec_out_is_accelerated(ipsec_mp,
26653 			    io->ipsec_out_esp_sa, ill, ire);
26654 		}
26655 
26656 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26657 		switch (ipsec_rc) {
26658 		case IPSEC_STATUS_SUCCESS:
26659 			break;
26660 		case IPSEC_STATUS_FAILED:
26661 			if (ill != NULL) {
26662 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26663 			} else {
26664 				BUMP_MIB(&ipst->ips_ip_mib,
26665 				    ipIfStatsOutDiscards);
26666 			}
26667 			/* FALLTHRU */
26668 		case IPSEC_STATUS_PENDING:
26669 			return;
26670 		}
26671 	}
26672 
26673 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
26674 		ASSERT(io->ipsec_out_ah_sa != NULL);
26675 		io->ipsec_out_ah_done = B_TRUE;
26676 		if (ire == NULL) {
26677 			int idx = io->ipsec_out_capab_ill_index;
26678 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
26679 			    NULL, NULL, NULL, NULL, ipst);
26680 			ill_need_rele = B_TRUE;
26681 		} else {
26682 			ill = (ill_t *)ire->ire_stq->q_ptr;
26683 		}
26684 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
26685 		    ire);
26686 
26687 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
26688 		switch (ipsec_rc) {
26689 		case IPSEC_STATUS_SUCCESS:
26690 			break;
26691 		case IPSEC_STATUS_FAILED:
26692 			if (ill != NULL) {
26693 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26694 			} else {
26695 				BUMP_MIB(&ipst->ips_ip_mib,
26696 				    ipIfStatsOutDiscards);
26697 			}
26698 			/* FALLTHRU */
26699 		case IPSEC_STATUS_PENDING:
26700 			if (ill != NULL && ill_need_rele)
26701 				ill_refrele(ill);
26702 			return;
26703 		}
26704 	}
26705 	/*
26706 	 * We are done with IPsec processing. Send it over
26707 	 * the wire.
26708 	 */
26709 done:
26710 	mp = ipsec_mp->b_cont;
26711 	ipha = (ipha_t *)mp->b_rptr;
26712 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26713 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
26714 	} else {
26715 		ip6h = (ip6_t *)ipha;
26716 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
26717 	}
26718 	if (ill != NULL && ill_need_rele)
26719 		ill_refrele(ill);
26720 }
26721 
26722 /* ARGSUSED */
26723 void
26724 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
26725 {
26726 	opt_restart_t	*or;
26727 	int	err;
26728 	conn_t	*connp;
26729 
26730 	ASSERT(CONN_Q(q));
26731 	connp = Q_TO_CONN(q);
26732 
26733 	ASSERT(first_mp->b_datap->db_type == M_CTL);
26734 	or = (opt_restart_t *)first_mp->b_rptr;
26735 	/*
26736 	 * We don't need to pass any credentials here since this is just
26737 	 * a restart. The credentials are passed in when svr4_optcom_req
26738 	 * is called the first time (from ip_wput_nondata).
26739 	 */
26740 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
26741 		err = svr4_optcom_req(q, first_mp, NULL,
26742 		    &ip_opt_obj, B_FALSE);
26743 	} else {
26744 		ASSERT(or->or_type == T_OPTMGMT_REQ);
26745 		err = tpi_optcom_req(q, first_mp, NULL,
26746 		    &ip_opt_obj, B_FALSE);
26747 	}
26748 	if (err != EINPROGRESS) {
26749 		/* operation is done */
26750 		CONN_OPER_PENDING_DONE(connp);
26751 	}
26752 }
26753 
26754 /*
26755  * ioctls that go through a down/up sequence may need to wait for the down
26756  * to complete. This involves waiting for the ire and ipif refcnts to go down
26757  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
26758  */
26759 /* ARGSUSED */
26760 void
26761 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26762 {
26763 	struct iocblk *iocp;
26764 	mblk_t *mp1;
26765 	ip_ioctl_cmd_t *ipip;
26766 	int err;
26767 	sin_t	*sin;
26768 	struct lifreq *lifr;
26769 	struct ifreq *ifr;
26770 
26771 	iocp = (struct iocblk *)mp->b_rptr;
26772 	ASSERT(ipsq != NULL);
26773 	/* Existence of mp1 verified in ip_wput_nondata */
26774 	mp1 = mp->b_cont->b_cont;
26775 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26776 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
26777 		/*
26778 		 * Special case where ipsq_current_ipif is not set:
26779 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
26780 		 * ill could also have become part of a ipmp group in the
26781 		 * process, we are here as were not able to complete the
26782 		 * operation in ipif_set_values because we could not become
26783 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
26784 		 * will not be set so we need to set it.
26785 		 */
26786 		ill_t *ill = q->q_ptr;
26787 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
26788 	}
26789 	ASSERT(ipsq->ipsq_current_ipif != NULL);
26790 
26791 	if (ipip->ipi_cmd_type == IF_CMD) {
26792 		/* This a old style SIOC[GS]IF* command */
26793 		ifr = (struct ifreq *)mp1->b_rptr;
26794 		sin = (sin_t *)&ifr->ifr_addr;
26795 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
26796 		/* This a new style SIOC[GS]LIF* command */
26797 		lifr = (struct lifreq *)mp1->b_rptr;
26798 		sin = (sin_t *)&lifr->lifr_addr;
26799 	} else {
26800 		sin = NULL;
26801 	}
26802 
26803 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_current_ipif, sin, q, mp,
26804 	    ipip, mp1->b_rptr);
26805 
26806 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26807 }
26808 
26809 /*
26810  * ioctl processing
26811  *
26812  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
26813  * the ioctl command in the ioctl tables, determines the copyin data size
26814  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
26815  *
26816  * ioctl processing then continues when the M_IOCDATA makes its way down to
26817  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
26818  * associated 'conn' is refheld till the end of the ioctl and the general
26819  * ioctl processing function ip_process_ioctl() is called to extract the
26820  * arguments and process the ioctl.  To simplify extraction, ioctl commands
26821  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
26822  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
26823  * is used to extract the ioctl's arguments.
26824  *
26825  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
26826  * so goes thru the serialization primitive ipsq_try_enter. Then the
26827  * appropriate function to handle the ioctl is called based on the entry in
26828  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
26829  * which also refreleases the 'conn' that was refheld at the start of the
26830  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
26831  *
26832  * Many exclusive ioctls go thru an internal down up sequence as part of
26833  * the operation. For example an attempt to change the IP address of an
26834  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
26835  * does all the cleanup such as deleting all ires that use this address.
26836  * Then we need to wait till all references to the interface go away.
26837  */
26838 void
26839 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
26840 {
26841 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
26842 	ip_ioctl_cmd_t *ipip = arg;
26843 	ip_extract_func_t *extract_funcp;
26844 	cmd_info_t ci;
26845 	int err;
26846 	boolean_t entered_ipsq = B_FALSE;
26847 
26848 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
26849 
26850 	if (ipip == NULL)
26851 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26852 
26853 	/*
26854 	 * SIOCLIFADDIF needs to go thru a special path since the
26855 	 * ill may not exist yet. This happens in the case of lo0
26856 	 * which is created using this ioctl.
26857 	 */
26858 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
26859 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
26860 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26861 		return;
26862 	}
26863 
26864 	ci.ci_ipif = NULL;
26865 	if (ipip->ipi_cmd_type == MISC_CMD) {
26866 		/*
26867 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
26868 		 */
26869 		if (ipip->ipi_cmd == IF_UNITSEL) {
26870 			/* ioctl comes down the ill */
26871 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
26872 			ipif_refhold(ci.ci_ipif);
26873 		}
26874 		err = 0;
26875 		ci.ci_sin = NULL;
26876 		ci.ci_sin6 = NULL;
26877 		ci.ci_lifr = NULL;
26878 	} else {
26879 		switch (ipip->ipi_cmd_type) {
26880 		case IF_CMD:
26881 		case LIF_CMD:
26882 			extract_funcp = ip_extract_lifreq;
26883 			break;
26884 
26885 		case ARP_CMD:
26886 		case XARP_CMD:
26887 			extract_funcp = ip_extract_arpreq;
26888 			break;
26889 
26890 		case TUN_CMD:
26891 			extract_funcp = ip_extract_tunreq;
26892 			break;
26893 
26894 		case MSFILT_CMD:
26895 			extract_funcp = ip_extract_msfilter;
26896 			break;
26897 
26898 		default:
26899 			ASSERT(0);
26900 		}
26901 
26902 		err = (*extract_funcp)(q, mp, ipip, &ci, ip_process_ioctl);
26903 		if (err != 0) {
26904 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26905 			return;
26906 		}
26907 
26908 		/*
26909 		 * All of the extraction functions return a refheld ipif.
26910 		 */
26911 		ASSERT(ci.ci_ipif != NULL);
26912 	}
26913 
26914 	/*
26915 	 * If ipsq is non-null, we are already being called exclusively
26916 	 */
26917 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
26918 	if (!(ipip->ipi_flags & IPI_WR)) {
26919 		/*
26920 		 * A return value of EINPROGRESS means the ioctl is
26921 		 * either queued and waiting for some reason or has
26922 		 * already completed.
26923 		 */
26924 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
26925 		    ci.ci_lifr);
26926 		if (ci.ci_ipif != NULL)
26927 			ipif_refrele(ci.ci_ipif);
26928 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26929 		return;
26930 	}
26931 
26932 	ASSERT(ci.ci_ipif != NULL);
26933 
26934 	if (ipsq == NULL) {
26935 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
26936 		    ip_process_ioctl, NEW_OP, B_TRUE);
26937 		entered_ipsq = B_TRUE;
26938 	}
26939 	/*
26940 	 * Release the ipif so that ipif_down and friends that wait for
26941 	 * references to go away are not misled about the current ipif_refcnt
26942 	 * values. We are writer so we can access the ipif even after releasing
26943 	 * the ipif.
26944 	 */
26945 	ipif_refrele(ci.ci_ipif);
26946 	if (ipsq == NULL)
26947 		return;
26948 
26949 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
26950 
26951 	/*
26952 	 * For most set ioctls that come here, this serves as a single point
26953 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
26954 	 * be any new references to the ipif. This helps functions that go
26955 	 * through this path and end up trying to wait for the refcnts
26956 	 * associated with the ipif to go down to zero. Some exceptions are
26957 	 * Failover, Failback, and Groupname commands that operate on more than
26958 	 * just the ci.ci_ipif. These commands internally determine the
26959 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
26960 	 * flags on that set. Another exception is the Removeif command that
26961 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
26962 	 * ipif to operate on.
26963 	 */
26964 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
26965 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
26966 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
26967 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
26968 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
26969 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
26970 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
26971 
26972 	/*
26973 	 * A return value of EINPROGRESS means the ioctl is
26974 	 * either queued and waiting for some reason or has
26975 	 * already completed.
26976 	 */
26977 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
26978 
26979 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26980 
26981 	if (entered_ipsq)
26982 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
26983 }
26984 
26985 /*
26986  * Complete the ioctl. Typically ioctls use the mi package and need to
26987  * do mi_copyout/mi_copy_done.
26988  */
26989 void
26990 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
26991 {
26992 	conn_t	*connp = NULL;
26993 
26994 	if (err == EINPROGRESS)
26995 		return;
26996 
26997 	if (CONN_Q(q)) {
26998 		connp = Q_TO_CONN(q);
26999 		ASSERT(connp->conn_ref >= 2);
27000 	}
27001 
27002 	switch (mode) {
27003 	case COPYOUT:
27004 		if (err == 0)
27005 			mi_copyout(q, mp);
27006 		else
27007 			mi_copy_done(q, mp, err);
27008 		break;
27009 
27010 	case NO_COPYOUT:
27011 		mi_copy_done(q, mp, err);
27012 		break;
27013 
27014 	default:
27015 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
27016 		break;
27017 	}
27018 
27019 	/*
27020 	 * The refhold placed at the start of the ioctl is released here.
27021 	 */
27022 	if (connp != NULL)
27023 		CONN_OPER_PENDING_DONE(connp);
27024 
27025 	if (ipsq != NULL)
27026 		ipsq_current_finish(ipsq);
27027 }
27028 
27029 /*
27030  * This is called from ip_wput_nondata to resume a deferred TCP bind.
27031  */
27032 /* ARGSUSED */
27033 void
27034 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
27035 {
27036 	conn_t *connp = arg;
27037 	tcp_t	*tcp;
27038 
27039 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
27040 	tcp = connp->conn_tcp;
27041 
27042 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
27043 		freemsg(mp);
27044 	else
27045 		tcp_rput_other(tcp, mp);
27046 	CONN_OPER_PENDING_DONE(connp);
27047 }
27048 
27049 /* Called from ip_wput for all non data messages */
27050 /* ARGSUSED */
27051 void
27052 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27053 {
27054 	mblk_t		*mp1;
27055 	ire_t		*ire, *fake_ire;
27056 	ill_t		*ill;
27057 	struct iocblk	*iocp;
27058 	ip_ioctl_cmd_t	*ipip;
27059 	cred_t		*cr;
27060 	conn_t		*connp;
27061 	int		err;
27062 	nce_t		*nce;
27063 	ipif_t		*ipif;
27064 	ip_stack_t	*ipst;
27065 	char		*proto_str;
27066 
27067 	if (CONN_Q(q)) {
27068 		connp = Q_TO_CONN(q);
27069 		ipst = connp->conn_netstack->netstack_ip;
27070 	} else {
27071 		connp = NULL;
27072 		ipst = ILLQ_TO_IPST(q);
27073 	}
27074 
27075 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
27076 
27077 	switch (DB_TYPE(mp)) {
27078 	case M_IOCTL:
27079 		/*
27080 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
27081 		 * will arrange to copy in associated control structures.
27082 		 */
27083 		ip_sioctl_copyin_setup(q, mp);
27084 		return;
27085 	case M_IOCDATA:
27086 		/*
27087 		 * Ensure that this is associated with one of our trans-
27088 		 * parent ioctls.  If it's not ours, discard it if we're
27089 		 * running as a driver, or pass it on if we're a module.
27090 		 */
27091 		iocp = (struct iocblk *)mp->b_rptr;
27092 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27093 		if (ipip == NULL) {
27094 			if (q->q_next == NULL) {
27095 				goto nak;
27096 			} else {
27097 				putnext(q, mp);
27098 			}
27099 			return;
27100 		}
27101 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
27102 			/*
27103 			 * the ioctl is one we recognise, but is not
27104 			 * consumed by IP as a module, pass M_IOCDATA
27105 			 * for processing downstream, but only for
27106 			 * common Streams ioctls.
27107 			 */
27108 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27109 				putnext(q, mp);
27110 				return;
27111 			} else {
27112 				goto nak;
27113 			}
27114 		}
27115 
27116 		/* IOCTL continuation following copyin or copyout. */
27117 		if (mi_copy_state(q, mp, NULL) == -1) {
27118 			/*
27119 			 * The copy operation failed.  mi_copy_state already
27120 			 * cleaned up, so we're out of here.
27121 			 */
27122 			return;
27123 		}
27124 		/*
27125 		 * If we just completed a copy in, we become writer and
27126 		 * continue processing in ip_sioctl_copyin_done.  If it
27127 		 * was a copy out, we call mi_copyout again.  If there is
27128 		 * nothing more to copy out, it will complete the IOCTL.
27129 		 */
27130 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27131 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27132 				mi_copy_done(q, mp, EPROTO);
27133 				return;
27134 			}
27135 			/*
27136 			 * Check for cases that need more copying.  A return
27137 			 * value of 0 means a second copyin has been started,
27138 			 * so we return; a return value of 1 means no more
27139 			 * copying is needed, so we continue.
27140 			 */
27141 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
27142 			    MI_COPY_COUNT(mp) == 1) {
27143 				if (ip_copyin_msfilter(q, mp) == 0)
27144 					return;
27145 			}
27146 			/*
27147 			 * Refhold the conn, till the ioctl completes. This is
27148 			 * needed in case the ioctl ends up in the pending mp
27149 			 * list. Every mp in the ill_pending_mp list and
27150 			 * the ipsq_pending_mp must have a refhold on the conn
27151 			 * to resume processing. The refhold is released when
27152 			 * the ioctl completes. (normally or abnormally)
27153 			 * In all cases ip_ioctl_finish is called to finish
27154 			 * the ioctl.
27155 			 */
27156 			if (connp != NULL) {
27157 				/* This is not a reentry */
27158 				ASSERT(ipsq == NULL);
27159 				CONN_INC_REF(connp);
27160 			} else {
27161 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27162 					mi_copy_done(q, mp, EINVAL);
27163 					return;
27164 				}
27165 			}
27166 
27167 			ip_process_ioctl(ipsq, q, mp, ipip);
27168 
27169 		} else {
27170 			mi_copyout(q, mp);
27171 		}
27172 		return;
27173 nak:
27174 		iocp->ioc_error = EINVAL;
27175 		mp->b_datap->db_type = M_IOCNAK;
27176 		iocp->ioc_count = 0;
27177 		qreply(q, mp);
27178 		return;
27179 
27180 	case M_IOCNAK:
27181 		/*
27182 		 * The only way we could get here is if a resolver didn't like
27183 		 * an IOCTL we sent it.	 This shouldn't happen.
27184 		 */
27185 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27186 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27187 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27188 		freemsg(mp);
27189 		return;
27190 	case M_IOCACK:
27191 		/* /dev/ip shouldn't see this */
27192 		if (CONN_Q(q))
27193 			goto nak;
27194 
27195 		/* Finish socket ioctls passed through to ARP. */
27196 		ip_sioctl_iocack(q, mp);
27197 		return;
27198 	case M_FLUSH:
27199 		if (*mp->b_rptr & FLUSHW)
27200 			flushq(q, FLUSHALL);
27201 		if (q->q_next) {
27202 			putnext(q, mp);
27203 			return;
27204 		}
27205 		if (*mp->b_rptr & FLUSHR) {
27206 			*mp->b_rptr &= ~FLUSHW;
27207 			qreply(q, mp);
27208 			return;
27209 		}
27210 		freemsg(mp);
27211 		return;
27212 	case IRE_DB_REQ_TYPE:
27213 		if (connp == NULL) {
27214 			proto_str = "IRE_DB_REQ_TYPE";
27215 			goto protonak;
27216 		}
27217 		/* An Upper Level Protocol wants a copy of an IRE. */
27218 		ip_ire_req(q, mp);
27219 		return;
27220 	case M_CTL:
27221 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27222 			break;
27223 
27224 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27225 		    TUN_HELLO) {
27226 			ASSERT(connp != NULL);
27227 			connp->conn_flags |= IPCL_IPTUN;
27228 			freeb(mp);
27229 			return;
27230 		}
27231 
27232 		/* M_CTL messages are used by ARP to tell us things. */
27233 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27234 			break;
27235 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27236 		case AR_ENTRY_SQUERY:
27237 			ip_wput_ctl(q, mp);
27238 			return;
27239 		case AR_CLIENT_NOTIFY:
27240 			ip_arp_news(q, mp);
27241 			return;
27242 		case AR_DLPIOP_DONE:
27243 			ASSERT(q->q_next != NULL);
27244 			ill = (ill_t *)q->q_ptr;
27245 			/* qwriter_ip releases the refhold */
27246 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27247 			ill_refhold(ill);
27248 			qwriter_ip(ill, q, mp, ip_arp_done, CUR_OP, B_FALSE);
27249 			return;
27250 		case AR_ARP_CLOSING:
27251 			/*
27252 			 * ARP (above us) is closing. If no ARP bringup is
27253 			 * currently pending, ack the message so that ARP
27254 			 * can complete its close. Also mark ill_arp_closing
27255 			 * so that new ARP bringups will fail. If any
27256 			 * ARP bringup is currently in progress, we will
27257 			 * ack this when the current ARP bringup completes.
27258 			 */
27259 			ASSERT(q->q_next != NULL);
27260 			ill = (ill_t *)q->q_ptr;
27261 			mutex_enter(&ill->ill_lock);
27262 			ill->ill_arp_closing = 1;
27263 			if (!ill->ill_arp_bringup_pending) {
27264 				mutex_exit(&ill->ill_lock);
27265 				qreply(q, mp);
27266 			} else {
27267 				mutex_exit(&ill->ill_lock);
27268 				freemsg(mp);
27269 			}
27270 			return;
27271 		case AR_ARP_EXTEND:
27272 			/*
27273 			 * The ARP module above us is capable of duplicate
27274 			 * address detection.  Old ATM drivers will not send
27275 			 * this message.
27276 			 */
27277 			ASSERT(q->q_next != NULL);
27278 			ill = (ill_t *)q->q_ptr;
27279 			ill->ill_arp_extend = B_TRUE;
27280 			freemsg(mp);
27281 			return;
27282 		default:
27283 			break;
27284 		}
27285 		break;
27286 	case M_PROTO:
27287 	case M_PCPROTO:
27288 		/*
27289 		 * The only PROTO messages we expect are ULP binds and
27290 		 * copies of option negotiation acknowledgements.
27291 		 */
27292 		switch (((union T_primitives *)mp->b_rptr)->type) {
27293 		case O_T_BIND_REQ:
27294 		case T_BIND_REQ: {
27295 			/* Request can get queued in bind */
27296 			if (connp == NULL) {
27297 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27298 				goto protonak;
27299 			}
27300 			/*
27301 			 * The transports except SCTP call ip_bind_{v4,v6}()
27302 			 * directly instead of a a putnext. SCTP doesn't
27303 			 * generate any T_BIND_REQ since it has its own
27304 			 * fanout data structures. However, ESP and AH
27305 			 * come in for regular binds; all other cases are
27306 			 * bind retries.
27307 			 */
27308 			ASSERT(!IPCL_IS_SCTP(connp));
27309 
27310 			/* Don't increment refcnt if this is a re-entry */
27311 			if (ipsq == NULL)
27312 				CONN_INC_REF(connp);
27313 
27314 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27315 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27316 			if (mp == NULL)
27317 				return;
27318 			if (IPCL_IS_TCP(connp)) {
27319 				/*
27320 				 * In the case of TCP endpoint we
27321 				 * come here only for bind retries
27322 				 */
27323 				ASSERT(ipsq != NULL);
27324 				CONN_INC_REF(connp);
27325 				squeue_fill(connp->conn_sqp, mp,
27326 				    ip_resume_tcp_bind, connp,
27327 				    SQTAG_BIND_RETRY);
27328 			} else if (IPCL_IS_UDP(connp)) {
27329 				/*
27330 				 * In the case of UDP endpoint we
27331 				 * come here only for bind retries
27332 				 */
27333 				ASSERT(ipsq != NULL);
27334 				udp_resume_bind(connp, mp);
27335 			} else if (IPCL_IS_RAWIP(connp)) {
27336 				/*
27337 				 * In the case of RAWIP endpoint we
27338 				 * come here only for bind retries
27339 				 */
27340 				ASSERT(ipsq != NULL);
27341 				rawip_resume_bind(connp, mp);
27342 			} else {
27343 				/* The case of AH and ESP */
27344 				qreply(q, mp);
27345 				CONN_OPER_PENDING_DONE(connp);
27346 			}
27347 			return;
27348 		}
27349 		case T_SVR4_OPTMGMT_REQ:
27350 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27351 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27352 
27353 			if (connp == NULL) {
27354 				proto_str = "T_SVR4_OPTMGMT_REQ";
27355 				goto protonak;
27356 			}
27357 
27358 			if (!snmpcom_req(q, mp, ip_snmp_set,
27359 			    ip_snmp_get, cr)) {
27360 				/*
27361 				 * Call svr4_optcom_req so that it can
27362 				 * generate the ack. We don't come here
27363 				 * if this operation is being restarted.
27364 				 * ip_restart_optmgmt will drop the conn ref.
27365 				 * In the case of ipsec option after the ipsec
27366 				 * load is complete conn_restart_ipsec_waiter
27367 				 * drops the conn ref.
27368 				 */
27369 				ASSERT(ipsq == NULL);
27370 				CONN_INC_REF(connp);
27371 				if (ip_check_for_ipsec_opt(q, mp))
27372 					return;
27373 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj,
27374 				    B_FALSE);
27375 				if (err != EINPROGRESS) {
27376 					/* Operation is done */
27377 					CONN_OPER_PENDING_DONE(connp);
27378 				}
27379 			}
27380 			return;
27381 		case T_OPTMGMT_REQ:
27382 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27383 			/*
27384 			 * Note: No snmpcom_req support through new
27385 			 * T_OPTMGMT_REQ.
27386 			 * Call tpi_optcom_req so that it can
27387 			 * generate the ack.
27388 			 */
27389 			if (connp == NULL) {
27390 				proto_str = "T_OPTMGMT_REQ";
27391 				goto protonak;
27392 			}
27393 
27394 			ASSERT(ipsq == NULL);
27395 			/*
27396 			 * We don't come here for restart. ip_restart_optmgmt
27397 			 * will drop the conn ref. In the case of ipsec option
27398 			 * after the ipsec load is complete
27399 			 * conn_restart_ipsec_waiter drops the conn ref.
27400 			 */
27401 			CONN_INC_REF(connp);
27402 			if (ip_check_for_ipsec_opt(q, mp))
27403 				return;
27404 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj, B_FALSE);
27405 			if (err != EINPROGRESS) {
27406 				/* Operation is done */
27407 				CONN_OPER_PENDING_DONE(connp);
27408 			}
27409 			return;
27410 		case T_UNBIND_REQ:
27411 			if (connp == NULL) {
27412 				proto_str = "T_UNBIND_REQ";
27413 				goto protonak;
27414 			}
27415 			mp = ip_unbind(q, mp);
27416 			qreply(q, mp);
27417 			return;
27418 		default:
27419 			/*
27420 			 * Have to drop any DLPI messages coming down from
27421 			 * arp (such as an info_req which would cause ip
27422 			 * to receive an extra info_ack if it was passed
27423 			 * through.
27424 			 */
27425 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27426 			    (int)*(uint_t *)mp->b_rptr));
27427 			freemsg(mp);
27428 			return;
27429 		}
27430 		/* NOTREACHED */
27431 	case IRE_DB_TYPE: {
27432 		nce_t		*nce;
27433 		ill_t		*ill;
27434 		in6_addr_t	gw_addr_v6;
27435 
27436 
27437 		/*
27438 		 * This is a response back from a resolver.  It
27439 		 * consists of a message chain containing:
27440 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27441 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27442 		 * The LL_HDR_MBLK is the DLPI header to use to get
27443 		 * the attached packet, and subsequent ones for the
27444 		 * same destination, transmitted.
27445 		 */
27446 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27447 			break;
27448 		/*
27449 		 * First, check to make sure the resolution succeeded.
27450 		 * If it failed, the second mblk will be empty.
27451 		 * If it is, free the chain, dropping the packet.
27452 		 * (We must ire_delete the ire; that frees the ire mblk)
27453 		 * We're doing this now to support PVCs for ATM; it's
27454 		 * a partial xresolv implementation. When we fully implement
27455 		 * xresolv interfaces, instead of freeing everything here
27456 		 * we'll initiate neighbor discovery.
27457 		 *
27458 		 * For v4 (ARP and other external resolvers) the resolver
27459 		 * frees the message, so no check is needed. This check
27460 		 * is required, though, for a full xresolve implementation.
27461 		 * Including this code here now both shows how external
27462 		 * resolvers can NACK a resolution request using an
27463 		 * existing design that has no specific provisions for NACKs,
27464 		 * and also takes into account that the current non-ARP
27465 		 * external resolver has been coded to use this method of
27466 		 * NACKing for all IPv6 (xresolv) cases,
27467 		 * whether our xresolv implementation is complete or not.
27468 		 *
27469 		 */
27470 		ire = (ire_t *)mp->b_rptr;
27471 		ill = ire_to_ill(ire);
27472 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27473 		if (mp1->b_rptr == mp1->b_wptr) {
27474 			if (ire->ire_ipversion == IPV6_VERSION) {
27475 				/*
27476 				 * XRESOLV interface.
27477 				 */
27478 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27479 				mutex_enter(&ire->ire_lock);
27480 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27481 				mutex_exit(&ire->ire_lock);
27482 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27483 					nce = ndp_lookup_v6(ill,
27484 					    &ire->ire_addr_v6, B_FALSE);
27485 				} else {
27486 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
27487 					    B_FALSE);
27488 				}
27489 				if (nce != NULL) {
27490 					nce_resolv_failed(nce);
27491 					ndp_delete(nce);
27492 					NCE_REFRELE(nce);
27493 				}
27494 			}
27495 			mp->b_cont = NULL;
27496 			freemsg(mp1);		/* frees the pkt as well */
27497 			ASSERT(ire->ire_nce == NULL);
27498 			ire_delete((ire_t *)mp->b_rptr);
27499 			return;
27500 		}
27501 
27502 		/*
27503 		 * Split them into IRE_MBLK and pkt and feed it into
27504 		 * ire_add_then_send. Then in ire_add_then_send
27505 		 * the IRE will be added, and then the packet will be
27506 		 * run back through ip_wput. This time it will make
27507 		 * it to the wire.
27508 		 */
27509 		mp->b_cont = NULL;
27510 		mp = mp1->b_cont;		/* now, mp points to pkt */
27511 		mp1->b_cont = NULL;
27512 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27513 		if (ire->ire_ipversion == IPV6_VERSION) {
27514 			/*
27515 			 * XRESOLV interface. Find the nce and put a copy
27516 			 * of the dl_unitdata_req in nce_res_mp
27517 			 */
27518 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27519 			mutex_enter(&ire->ire_lock);
27520 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27521 			mutex_exit(&ire->ire_lock);
27522 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27523 				nce = ndp_lookup_v6(ill, &ire->ire_addr_v6,
27524 				    B_FALSE);
27525 			} else {
27526 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
27527 			}
27528 			if (nce != NULL) {
27529 				/*
27530 				 * We have to protect nce_res_mp here
27531 				 * from being accessed by other threads
27532 				 * while we change the mblk pointer.
27533 				 * Other functions will also lock the nce when
27534 				 * accessing nce_res_mp.
27535 				 *
27536 				 * The reason we change the mblk pointer
27537 				 * here rather than copying the resolved address
27538 				 * into the template is that, unlike with
27539 				 * ethernet, we have no guarantee that the
27540 				 * resolved address length will be
27541 				 * smaller than or equal to the lla length
27542 				 * with which the template was allocated,
27543 				 * (for ethernet, they're equal)
27544 				 * so we have to use the actual resolved
27545 				 * address mblk - which holds the real
27546 				 * dl_unitdata_req with the resolved address.
27547 				 *
27548 				 * Doing this is the same behavior as was
27549 				 * previously used in the v4 ARP case.
27550 				 */
27551 				mutex_enter(&nce->nce_lock);
27552 				if (nce->nce_res_mp != NULL)
27553 					freemsg(nce->nce_res_mp);
27554 				nce->nce_res_mp = mp1;
27555 				mutex_exit(&nce->nce_lock);
27556 				/*
27557 				 * We do a fastpath probe here because
27558 				 * we have resolved the address without
27559 				 * using Neighbor Discovery.
27560 				 * In the non-XRESOLV v6 case, the fastpath
27561 				 * probe is done right after neighbor
27562 				 * discovery completes.
27563 				 */
27564 				if (nce->nce_res_mp != NULL) {
27565 					int res;
27566 					nce_fastpath_list_add(nce);
27567 					res = ill_fastpath_probe(ill,
27568 					    nce->nce_res_mp);
27569 					if (res != 0 && res != EAGAIN)
27570 						nce_fastpath_list_delete(nce);
27571 				}
27572 
27573 				ire_add_then_send(q, ire, mp);
27574 				/*
27575 				 * Now we have to clean out any packets
27576 				 * that may have been queued on the nce
27577 				 * while it was waiting for address resolution
27578 				 * to complete.
27579 				 */
27580 				mutex_enter(&nce->nce_lock);
27581 				mp1 = nce->nce_qd_mp;
27582 				nce->nce_qd_mp = NULL;
27583 				mutex_exit(&nce->nce_lock);
27584 				while (mp1 != NULL) {
27585 					mblk_t *nxt_mp;
27586 					queue_t *fwdq = NULL;
27587 					ill_t   *inbound_ill;
27588 					uint_t ifindex;
27589 
27590 					nxt_mp = mp1->b_next;
27591 					mp1->b_next = NULL;
27592 					/*
27593 					 * Retrieve ifindex stored in
27594 					 * ip_rput_data_v6()
27595 					 */
27596 					ifindex =
27597 					    (uint_t)(uintptr_t)mp1->b_prev;
27598 					inbound_ill =
27599 					    ill_lookup_on_ifindex(ifindex,
27600 					    B_TRUE, NULL, NULL, NULL,
27601 					    NULL, ipst);
27602 					mp1->b_prev = NULL;
27603 					if (inbound_ill != NULL)
27604 						fwdq = inbound_ill->ill_rq;
27605 
27606 					if (fwdq != NULL) {
27607 						put(fwdq, mp1);
27608 						ill_refrele(inbound_ill);
27609 					} else
27610 						put(WR(ill->ill_rq), mp1);
27611 					mp1 = nxt_mp;
27612 				}
27613 				NCE_REFRELE(nce);
27614 			} else {	/* nce is NULL; clean up */
27615 				ire_delete(ire);
27616 				freemsg(mp);
27617 				freemsg(mp1);
27618 				return;
27619 			}
27620 		} else {
27621 			nce_t *arpce;
27622 			/*
27623 			 * Link layer resolution succeeded. Recompute the
27624 			 * ire_nce.
27625 			 */
27626 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27627 			if ((arpce = ndp_lookup_v4(ill,
27628 			    (ire->ire_gateway_addr != INADDR_ANY ?
27629 			    &ire->ire_gateway_addr : &ire->ire_addr),
27630 			    B_FALSE)) == NULL) {
27631 				freeb(ire->ire_mp);
27632 				freeb(mp1);
27633 				freemsg(mp);
27634 				return;
27635 			}
27636 			mutex_enter(&arpce->nce_lock);
27637 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27638 			if (arpce->nce_state == ND_REACHABLE) {
27639 				/*
27640 				 * Someone resolved this before us;
27641 				 * cleanup the res_mp. Since ire has
27642 				 * not been added yet, the call to ire_add_v4
27643 				 * from ire_add_then_send (when a dup is
27644 				 * detected) will clean up the ire.
27645 				 */
27646 				freeb(mp1);
27647 			} else {
27648 				ASSERT(arpce->nce_res_mp == NULL);
27649 				arpce->nce_res_mp = mp1;
27650 				arpce->nce_state = ND_REACHABLE;
27651 			}
27652 			mutex_exit(&arpce->nce_lock);
27653 			if (ire->ire_marks & IRE_MARK_NOADD) {
27654 				/*
27655 				 * this ire will not be added to the ire
27656 				 * cache table, so we can set the ire_nce
27657 				 * here, as there are no atomicity constraints.
27658 				 */
27659 				ire->ire_nce = arpce;
27660 				/*
27661 				 * We are associating this nce with the ire
27662 				 * so change the nce ref taken in
27663 				 * ndp_lookup_v4() from
27664 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
27665 				 */
27666 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
27667 			} else {
27668 				NCE_REFRELE(arpce);
27669 			}
27670 			ire_add_then_send(q, ire, mp);
27671 		}
27672 		return;	/* All is well, the packet has been sent. */
27673 	}
27674 	case IRE_ARPRESOLVE_TYPE: {
27675 
27676 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
27677 			break;
27678 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27679 		mp->b_cont = NULL;
27680 		/*
27681 		 * First, check to make sure the resolution succeeded.
27682 		 * If it failed, the second mblk will be empty.
27683 		 */
27684 		if (mp1->b_rptr == mp1->b_wptr) {
27685 			/* cleanup  the incomplete ire, free queued packets */
27686 			freemsg(mp); /* fake ire */
27687 			freeb(mp1);  /* dl_unitdata response */
27688 			return;
27689 		}
27690 
27691 		/*
27692 		 * update any incomplete nce_t found. we lookup the ctable
27693 		 * and find the nce from the ire->ire_nce because we need
27694 		 * to pass the ire to ip_xmit_v4 later, and can find both
27695 		 * ire and nce in one lookup from the ctable.
27696 		 */
27697 		fake_ire = (ire_t *)mp->b_rptr;
27698 		/*
27699 		 * By the time we come back here from ARP
27700 		 * the logical outgoing interface  of the incomplete ire
27701 		 * we added in ire_forward could have disappeared,
27702 		 * causing the incomplete ire to also have
27703 		 * dissapeared. So we need to retreive the
27704 		 * proper ipif for the ire  before looking
27705 		 * in ctable;  do the ctablelookup based on ire_ipif_seqid
27706 		 */
27707 		ill = q->q_ptr;
27708 
27709 		/* Get the outgoing ipif */
27710 		mutex_enter(&ill->ill_lock);
27711 		if (ill->ill_state_flags & ILL_CONDEMNED) {
27712 			mutex_exit(&ill->ill_lock);
27713 			freemsg(mp); /* fake ire */
27714 			freeb(mp1);  /* dl_unitdata response */
27715 			return;
27716 		}
27717 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27718 
27719 		if (ipif == NULL) {
27720 			mutex_exit(&ill->ill_lock);
27721 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27722 			freemsg(mp);
27723 			freeb(mp1);
27724 			return;
27725 		}
27726 		ipif_refhold_locked(ipif);
27727 		mutex_exit(&ill->ill_lock);
27728 		ire = ire_ctable_lookup(fake_ire->ire_addr,
27729 		    fake_ire->ire_gateway_addr, IRE_CACHE,
27730 		    ipif, fake_ire->ire_zoneid, NULL,
27731 		    (MATCH_IRE_GW|MATCH_IRE_IPIF|MATCH_IRE_ZONEONLY), ipst);
27732 		ipif_refrele(ipif);
27733 		if (ire == NULL) {
27734 			/*
27735 			 * no ire was found; check if there is an nce
27736 			 * for this lookup; if it has no ire's pointing at it
27737 			 * cleanup.
27738 			 */
27739 			if ((nce = ndp_lookup_v4(ill,
27740 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
27741 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
27742 			    B_FALSE)) != NULL) {
27743 				/*
27744 				 * cleanup:
27745 				 * We check for refcnt 2 (one for the nce
27746 				 * hash list + 1 for the ref taken by
27747 				 * ndp_lookup_v4) to check that there are
27748 				 * no ire's pointing at the nce.
27749 				 */
27750 				if (nce->nce_refcnt == 2)
27751 					ndp_delete(nce);
27752 				NCE_REFRELE(nce);
27753 			}
27754 			freeb(mp1);  /* dl_unitdata response */
27755 			freemsg(mp); /* fake ire */
27756 			return;
27757 		}
27758 		nce = ire->ire_nce;
27759 		DTRACE_PROBE2(ire__arpresolve__type,
27760 		    ire_t *, ire, nce_t *, nce);
27761 		ASSERT(nce->nce_state != ND_INITIAL);
27762 		mutex_enter(&nce->nce_lock);
27763 		nce->nce_last = TICK_TO_MSEC(lbolt64);
27764 		if (nce->nce_state == ND_REACHABLE) {
27765 			/*
27766 			 * Someone resolved this before us;
27767 			 * our response is not needed any more.
27768 			 */
27769 			mutex_exit(&nce->nce_lock);
27770 			freeb(mp1);  /* dl_unitdata response */
27771 		} else {
27772 			ASSERT(nce->nce_res_mp == NULL);
27773 			nce->nce_res_mp = mp1;
27774 			nce->nce_state = ND_REACHABLE;
27775 			mutex_exit(&nce->nce_lock);
27776 			nce_fastpath(nce);
27777 		}
27778 		/*
27779 		 * The cached nce_t has been updated to be reachable;
27780 		 * Clear the IRE_MARK_UNCACHED flag and free the fake_ire.
27781 		 */
27782 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
27783 		freemsg(mp);
27784 		/*
27785 		 * send out queued packets.
27786 		 */
27787 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
27788 
27789 		IRE_REFRELE(ire);
27790 		return;
27791 	}
27792 	default:
27793 		break;
27794 	}
27795 	if (q->q_next) {
27796 		putnext(q, mp);
27797 	} else
27798 		freemsg(mp);
27799 	return;
27800 
27801 protonak:
27802 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
27803 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
27804 		qreply(q, mp);
27805 }
27806 
27807 /*
27808  * Process IP options in an outbound packet.  Modify the destination if there
27809  * is a source route option.
27810  * Returns non-zero if something fails in which case an ICMP error has been
27811  * sent and mp freed.
27812  */
27813 static int
27814 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
27815     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
27816 {
27817 	ipoptp_t	opts;
27818 	uchar_t		*opt;
27819 	uint8_t		optval;
27820 	uint8_t		optlen;
27821 	ipaddr_t	dst;
27822 	intptr_t	code = 0;
27823 	mblk_t		*mp;
27824 	ire_t		*ire = NULL;
27825 
27826 	ip2dbg(("ip_wput_options\n"));
27827 	mp = ipsec_mp;
27828 	if (mctl_present) {
27829 		mp = ipsec_mp->b_cont;
27830 	}
27831 
27832 	dst = ipha->ipha_dst;
27833 	for (optval = ipoptp_first(&opts, ipha);
27834 	    optval != IPOPT_EOL;
27835 	    optval = ipoptp_next(&opts)) {
27836 		opt = opts.ipoptp_cur;
27837 		optlen = opts.ipoptp_len;
27838 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
27839 		    optval, optlen));
27840 		switch (optval) {
27841 			uint32_t off;
27842 		case IPOPT_SSRR:
27843 		case IPOPT_LSRR:
27844 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27845 				ip1dbg((
27846 				    "ip_wput_options: bad option offset\n"));
27847 				code = (char *)&opt[IPOPT_OLEN] -
27848 				    (char *)ipha;
27849 				goto param_prob;
27850 			}
27851 			off = opt[IPOPT_OFFSET];
27852 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
27853 			    ntohl(dst)));
27854 			/*
27855 			 * For strict: verify that dst is directly
27856 			 * reachable.
27857 			 */
27858 			if (optval == IPOPT_SSRR) {
27859 				ire = ire_ftable_lookup(dst, 0, 0,
27860 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
27861 				    MBLK_GETLABEL(mp),
27862 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
27863 				if (ire == NULL) {
27864 					ip1dbg(("ip_wput_options: SSRR not"
27865 					    " directly reachable: 0x%x\n",
27866 					    ntohl(dst)));
27867 					goto bad_src_route;
27868 				}
27869 				ire_refrele(ire);
27870 			}
27871 			break;
27872 		case IPOPT_RR:
27873 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27874 				ip1dbg((
27875 				    "ip_wput_options: bad option offset\n"));
27876 				code = (char *)&opt[IPOPT_OLEN] -
27877 				    (char *)ipha;
27878 				goto param_prob;
27879 			}
27880 			break;
27881 		case IPOPT_TS:
27882 			/*
27883 			 * Verify that length >=5 and that there is either
27884 			 * room for another timestamp or that the overflow
27885 			 * counter is not maxed out.
27886 			 */
27887 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
27888 			if (optlen < IPOPT_MINLEN_IT) {
27889 				goto param_prob;
27890 			}
27891 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27892 				ip1dbg((
27893 				    "ip_wput_options: bad option offset\n"));
27894 				code = (char *)&opt[IPOPT_OFFSET] -
27895 				    (char *)ipha;
27896 				goto param_prob;
27897 			}
27898 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
27899 			case IPOPT_TS_TSONLY:
27900 				off = IPOPT_TS_TIMELEN;
27901 				break;
27902 			case IPOPT_TS_TSANDADDR:
27903 			case IPOPT_TS_PRESPEC:
27904 			case IPOPT_TS_PRESPEC_RFC791:
27905 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
27906 				break;
27907 			default:
27908 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
27909 				    (char *)ipha;
27910 				goto param_prob;
27911 			}
27912 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
27913 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
27914 				/*
27915 				 * No room and the overflow counter is 15
27916 				 * already.
27917 				 */
27918 				goto param_prob;
27919 			}
27920 			break;
27921 		}
27922 	}
27923 
27924 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
27925 		return (0);
27926 
27927 	ip1dbg(("ip_wput_options: error processing IP options."));
27928 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
27929 
27930 param_prob:
27931 	/*
27932 	 * Since ip_wput() isn't close to finished, we fill
27933 	 * in enough of the header for credible error reporting.
27934 	 */
27935 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
27936 		/* Failed */
27937 		freemsg(ipsec_mp);
27938 		return (-1);
27939 	}
27940 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
27941 	return (-1);
27942 
27943 bad_src_route:
27944 	/*
27945 	 * Since ip_wput() isn't close to finished, we fill
27946 	 * in enough of the header for credible error reporting.
27947 	 */
27948 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
27949 		/* Failed */
27950 		freemsg(ipsec_mp);
27951 		return (-1);
27952 	}
27953 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
27954 	return (-1);
27955 }
27956 
27957 /*
27958  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
27959  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
27960  * thru /etc/system.
27961  */
27962 #define	CONN_MAXDRAINCNT	64
27963 
27964 static void
27965 conn_drain_init(ip_stack_t *ipst)
27966 {
27967 	int i;
27968 
27969 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
27970 
27971 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
27972 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
27973 		/*
27974 		 * Default value of the number of drainers is the
27975 		 * number of cpus, subject to maximum of 8 drainers.
27976 		 */
27977 		if (boot_max_ncpus != -1)
27978 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
27979 		else
27980 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
27981 	}
27982 
27983 	ipst->ips_conn_drain_list = kmem_zalloc(ipst->ips_conn_drain_list_cnt *
27984 	    sizeof (idl_t), KM_SLEEP);
27985 
27986 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
27987 		mutex_init(&ipst->ips_conn_drain_list[i].idl_lock, NULL,
27988 		    MUTEX_DEFAULT, NULL);
27989 	}
27990 }
27991 
27992 static void
27993 conn_drain_fini(ip_stack_t *ipst)
27994 {
27995 	int i;
27996 
27997 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++)
27998 		mutex_destroy(&ipst->ips_conn_drain_list[i].idl_lock);
27999 	kmem_free(ipst->ips_conn_drain_list,
28000 	    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
28001 	ipst->ips_conn_drain_list = NULL;
28002 }
28003 
28004 /*
28005  * Note: For an overview of how flowcontrol is handled in IP please see the
28006  * IP Flowcontrol notes at the top of this file.
28007  *
28008  * Flow control has blocked us from proceeding. Insert the given conn in one
28009  * of the conn drain lists. These conn wq's will be qenabled later on when
28010  * STREAMS flow control does a backenable. conn_walk_drain will enable
28011  * the first conn in each of these drain lists. Each of these qenabled conns
28012  * in turn enables the next in the list, after it runs, or when it closes,
28013  * thus sustaining the drain process.
28014  *
28015  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
28016  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
28017  * running at any time, on a given conn, since there can be only 1 service proc
28018  * running on a queue at any time.
28019  */
28020 void
28021 conn_drain_insert(conn_t *connp)
28022 {
28023 	idl_t	*idl;
28024 	uint_t	index;
28025 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28026 
28027 	mutex_enter(&connp->conn_lock);
28028 	if (connp->conn_state_flags & CONN_CLOSING) {
28029 		/*
28030 		 * The conn is closing as a result of which CONN_CLOSING
28031 		 * is set. Return.
28032 		 */
28033 		mutex_exit(&connp->conn_lock);
28034 		return;
28035 	} else if (connp->conn_idl == NULL) {
28036 		/*
28037 		 * Assign the next drain list round robin. We dont' use
28038 		 * a lock, and thus it may not be strictly round robin.
28039 		 * Atomicity of load/stores is enough to make sure that
28040 		 * conn_drain_list_index is always within bounds.
28041 		 */
28042 		index = ipst->ips_conn_drain_list_index;
28043 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
28044 		connp->conn_idl = &ipst->ips_conn_drain_list[index];
28045 		index++;
28046 		if (index == ipst->ips_conn_drain_list_cnt)
28047 			index = 0;
28048 		ipst->ips_conn_drain_list_index = index;
28049 	}
28050 	mutex_exit(&connp->conn_lock);
28051 
28052 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28053 	if ((connp->conn_drain_prev != NULL) ||
28054 	    (connp->conn_state_flags & CONN_CLOSING)) {
28055 		/*
28056 		 * The conn is already in the drain list, OR
28057 		 * the conn is closing. We need to check again for
28058 		 * the closing case again since close can happen
28059 		 * after we drop the conn_lock, and before we
28060 		 * acquire the CONN_DRAIN_LIST_LOCK.
28061 		 */
28062 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28063 		return;
28064 	} else {
28065 		idl = connp->conn_idl;
28066 	}
28067 
28068 	/*
28069 	 * The conn is not in the drain list. Insert it at the
28070 	 * tail of the drain list. The drain list is circular
28071 	 * and doubly linked. idl_conn points to the 1st element
28072 	 * in the list.
28073 	 */
28074 	if (idl->idl_conn == NULL) {
28075 		idl->idl_conn = connp;
28076 		connp->conn_drain_next = connp;
28077 		connp->conn_drain_prev = connp;
28078 	} else {
28079 		conn_t *head = idl->idl_conn;
28080 
28081 		connp->conn_drain_next = head;
28082 		connp->conn_drain_prev = head->conn_drain_prev;
28083 		head->conn_drain_prev->conn_drain_next = connp;
28084 		head->conn_drain_prev = connp;
28085 	}
28086 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28087 }
28088 
28089 /*
28090  * This conn is closing, and we are called from ip_close. OR
28091  * This conn has been serviced by ip_wsrv, and we need to do the tail
28092  * processing.
28093  * If this conn is part of the drain list, we may need to sustain the drain
28094  * process by qenabling the next conn in the drain list. We may also need to
28095  * remove this conn from the list, if it is done.
28096  */
28097 static void
28098 conn_drain_tail(conn_t *connp, boolean_t closing)
28099 {
28100 	idl_t *idl;
28101 
28102 	/*
28103 	 * connp->conn_idl is stable at this point, and no lock is needed
28104 	 * to check it. If we are called from ip_close, close has already
28105 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28106 	 * called us only because conn_idl is non-null. If we are called thru
28107 	 * service, conn_idl could be null, but it cannot change because
28108 	 * service is single-threaded per queue, and there cannot be another
28109 	 * instance of service trying to call conn_drain_insert on this conn
28110 	 * now.
28111 	 */
28112 	ASSERT(!closing || (connp->conn_idl != NULL));
28113 
28114 	/*
28115 	 * If connp->conn_idl is null, the conn has not been inserted into any
28116 	 * drain list even once since creation of the conn. Just return.
28117 	 */
28118 	if (connp->conn_idl == NULL)
28119 		return;
28120 
28121 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28122 
28123 	if (connp->conn_drain_prev == NULL) {
28124 		/* This conn is currently not in the drain list.  */
28125 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28126 		return;
28127 	}
28128 	idl = connp->conn_idl;
28129 	if (idl->idl_conn_draining == connp) {
28130 		/*
28131 		 * This conn is the current drainer. If this is the last conn
28132 		 * in the drain list, we need to do more checks, in the 'if'
28133 		 * below. Otherwwise we need to just qenable the next conn,
28134 		 * to sustain the draining, and is handled in the 'else'
28135 		 * below.
28136 		 */
28137 		if (connp->conn_drain_next == idl->idl_conn) {
28138 			/*
28139 			 * This conn is the last in this list. This round
28140 			 * of draining is complete. If idl_repeat is set,
28141 			 * it means another flow enabling has happened from
28142 			 * the driver/streams and we need to another round
28143 			 * of draining.
28144 			 * If there are more than 2 conns in the drain list,
28145 			 * do a left rotate by 1, so that all conns except the
28146 			 * conn at the head move towards the head by 1, and the
28147 			 * the conn at the head goes to the tail. This attempts
28148 			 * a more even share for all queues that are being
28149 			 * drained.
28150 			 */
28151 			if ((connp->conn_drain_next != connp) &&
28152 			    (idl->idl_conn->conn_drain_next != connp)) {
28153 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28154 			}
28155 			if (idl->idl_repeat) {
28156 				qenable(idl->idl_conn->conn_wq);
28157 				idl->idl_conn_draining = idl->idl_conn;
28158 				idl->idl_repeat = 0;
28159 			} else {
28160 				idl->idl_conn_draining = NULL;
28161 			}
28162 		} else {
28163 			/*
28164 			 * If the next queue that we are now qenable'ing,
28165 			 * is closing, it will remove itself from this list
28166 			 * and qenable the subsequent queue in ip_close().
28167 			 * Serialization is acheived thru idl_lock.
28168 			 */
28169 			qenable(connp->conn_drain_next->conn_wq);
28170 			idl->idl_conn_draining = connp->conn_drain_next;
28171 		}
28172 	}
28173 	if (!connp->conn_did_putbq || closing) {
28174 		/*
28175 		 * Remove ourself from the drain list, if we did not do
28176 		 * a putbq, or if the conn is closing.
28177 		 * Note: It is possible that q->q_first is non-null. It means
28178 		 * that these messages landed after we did a enableok() in
28179 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28180 		 * service them.
28181 		 */
28182 		if (connp->conn_drain_next == connp) {
28183 			/* Singleton in the list */
28184 			ASSERT(connp->conn_drain_prev == connp);
28185 			idl->idl_conn = NULL;
28186 			idl->idl_conn_draining = NULL;
28187 		} else {
28188 			connp->conn_drain_prev->conn_drain_next =
28189 			    connp->conn_drain_next;
28190 			connp->conn_drain_next->conn_drain_prev =
28191 			    connp->conn_drain_prev;
28192 			if (idl->idl_conn == connp)
28193 				idl->idl_conn = connp->conn_drain_next;
28194 			ASSERT(idl->idl_conn_draining != connp);
28195 
28196 		}
28197 		connp->conn_drain_next = NULL;
28198 		connp->conn_drain_prev = NULL;
28199 	}
28200 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28201 }
28202 
28203 /*
28204  * Write service routine. Shared perimeter entry point.
28205  * ip_wsrv can be called in any of the following ways.
28206  * 1. The device queue's messages has fallen below the low water mark
28207  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28208  *    the drain lists and backenable the first conn in each list.
28209  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28210  *    qenabled non-tcp upper layers. We start dequeing messages and call
28211  *    ip_wput for each message.
28212  */
28213 
28214 void
28215 ip_wsrv(queue_t *q)
28216 {
28217 	conn_t	*connp;
28218 	ill_t	*ill;
28219 	mblk_t	*mp;
28220 
28221 	if (q->q_next) {
28222 		ill = (ill_t *)q->q_ptr;
28223 		if (ill->ill_state_flags == 0) {
28224 			/*
28225 			 * The device flow control has opened up.
28226 			 * Walk through conn drain lists and qenable the
28227 			 * first conn in each list. This makes sense only
28228 			 * if the stream is fully plumbed and setup.
28229 			 * Hence the if check above.
28230 			 */
28231 			ip1dbg(("ip_wsrv: walking\n"));
28232 			conn_walk_drain(ill->ill_ipst);
28233 		}
28234 		return;
28235 	}
28236 
28237 	connp = Q_TO_CONN(q);
28238 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28239 
28240 	/*
28241 	 * 1. Set conn_draining flag to signal that service is active.
28242 	 *
28243 	 * 2. ip_output determines whether it has been called from service,
28244 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28245 	 *    has been called from service.
28246 	 *
28247 	 * 3. Message ordering is preserved by the following logic.
28248 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28249 	 *    the message at the tail, if conn_draining is set (i.e. service
28250 	 *    is running) or if q->q_first is non-null.
28251 	 *
28252 	 *    ii. If ip_output is called from service, and if ip_output cannot
28253 	 *    putnext due to flow control, it does a putbq.
28254 	 *
28255 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28256 	 *    (causing an infinite loop).
28257 	 */
28258 	ASSERT(!connp->conn_did_putbq);
28259 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28260 		connp->conn_draining = 1;
28261 		noenable(q);
28262 		while ((mp = getq(q)) != NULL) {
28263 			ASSERT(CONN_Q(q));
28264 
28265 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28266 			if (connp->conn_did_putbq) {
28267 				/* ip_wput did a putbq */
28268 				break;
28269 			}
28270 		}
28271 		/*
28272 		 * At this point, a thread coming down from top, calling
28273 		 * ip_wput, may end up queueing the message. We have not yet
28274 		 * enabled the queue, so ip_wsrv won't be called again.
28275 		 * To avoid this race, check q->q_first again (in the loop)
28276 		 * If the other thread queued the message before we call
28277 		 * enableok(), we will catch it in the q->q_first check.
28278 		 * If the other thread queues the message after we call
28279 		 * enableok(), ip_wsrv will be called again by STREAMS.
28280 		 */
28281 		connp->conn_draining = 0;
28282 		enableok(q);
28283 	}
28284 
28285 	/* Enable the next conn for draining */
28286 	conn_drain_tail(connp, B_FALSE);
28287 
28288 	connp->conn_did_putbq = 0;
28289 }
28290 
28291 /*
28292  * Walk the list of all conn's calling the function provided with the
28293  * specified argument for each.	 Note that this only walks conn's that
28294  * have been bound.
28295  * Applies to both IPv4 and IPv6.
28296  */
28297 static void
28298 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid, ip_stack_t *ipst)
28299 {
28300 	conn_walk_fanout_table(ipst->ips_ipcl_udp_fanout,
28301 	    ipst->ips_ipcl_udp_fanout_size,
28302 	    func, arg, zoneid);
28303 	conn_walk_fanout_table(ipst->ips_ipcl_conn_fanout,
28304 	    ipst->ips_ipcl_conn_fanout_size,
28305 	    func, arg, zoneid);
28306 	conn_walk_fanout_table(ipst->ips_ipcl_bind_fanout,
28307 	    ipst->ips_ipcl_bind_fanout_size,
28308 	    func, arg, zoneid);
28309 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout,
28310 	    IPPROTO_MAX, func, arg, zoneid);
28311 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout_v6,
28312 	    IPPROTO_MAX, func, arg, zoneid);
28313 }
28314 
28315 /*
28316  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28317  * of conns that need to be drained, check if drain is already in progress.
28318  * If so set the idl_repeat bit, indicating that the last conn in the list
28319  * needs to reinitiate the drain once again, for the list. If drain is not
28320  * in progress for the list, initiate the draining, by qenabling the 1st
28321  * conn in the list. The drain is self-sustaining, each qenabled conn will
28322  * in turn qenable the next conn, when it is done/blocked/closing.
28323  */
28324 static void
28325 conn_walk_drain(ip_stack_t *ipst)
28326 {
28327 	int i;
28328 	idl_t *idl;
28329 
28330 	IP_STAT(ipst, ip_conn_walk_drain);
28331 
28332 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28333 		idl = &ipst->ips_conn_drain_list[i];
28334 		mutex_enter(&idl->idl_lock);
28335 		if (idl->idl_conn == NULL) {
28336 			mutex_exit(&idl->idl_lock);
28337 			continue;
28338 		}
28339 		/*
28340 		 * If this list is not being drained currently by
28341 		 * an ip_wsrv thread, start the process.
28342 		 */
28343 		if (idl->idl_conn_draining == NULL) {
28344 			ASSERT(idl->idl_repeat == 0);
28345 			qenable(idl->idl_conn->conn_wq);
28346 			idl->idl_conn_draining = idl->idl_conn;
28347 		} else {
28348 			idl->idl_repeat = 1;
28349 		}
28350 		mutex_exit(&idl->idl_lock);
28351 	}
28352 }
28353 
28354 /*
28355  * Walk an conn hash table of `count' buckets, calling func for each entry.
28356  */
28357 static void
28358 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
28359     zoneid_t zoneid)
28360 {
28361 	conn_t	*connp;
28362 
28363 	while (count-- > 0) {
28364 		mutex_enter(&connfp->connf_lock);
28365 		for (connp = connfp->connf_head; connp != NULL;
28366 		    connp = connp->conn_next) {
28367 			if (zoneid == GLOBAL_ZONEID ||
28368 			    zoneid == connp->conn_zoneid) {
28369 				CONN_INC_REF(connp);
28370 				mutex_exit(&connfp->connf_lock);
28371 				(*func)(connp, arg);
28372 				mutex_enter(&connfp->connf_lock);
28373 				CONN_DEC_REF(connp);
28374 			}
28375 		}
28376 		mutex_exit(&connfp->connf_lock);
28377 		connfp++;
28378 	}
28379 }
28380 
28381 /* conn_walk_fanout routine invoked for ip_conn_report for each conn. */
28382 static void
28383 conn_report1(conn_t *connp, void *mp)
28384 {
28385 	char	buf1[INET6_ADDRSTRLEN];
28386 	char	buf2[INET6_ADDRSTRLEN];
28387 	uint_t	print_len, buf_len;
28388 
28389 	ASSERT(connp != NULL);
28390 
28391 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
28392 	if (buf_len <= 0)
28393 		return;
28394 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1));
28395 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2));
28396 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
28397 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
28398 	    "%5d %s/%05d %s/%05d\n",
28399 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
28400 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
28401 	    buf1, connp->conn_lport,
28402 	    buf2, connp->conn_fport);
28403 	if (print_len < buf_len) {
28404 		((mblk_t *)mp)->b_wptr += print_len;
28405 	} else {
28406 		((mblk_t *)mp)->b_wptr += buf_len;
28407 	}
28408 }
28409 
28410 /*
28411  * Named Dispatch routine to produce a formatted report on all conns
28412  * that are listed in one of the fanout tables.
28413  * This report is accessed by using the ndd utility to "get" ND variable
28414  * "ip_conn_status".
28415  */
28416 /* ARGSUSED */
28417 static int
28418 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
28419 {
28420 	conn_t *connp = Q_TO_CONN(q);
28421 
28422 	(void) mi_mpprintf(mp,
28423 	    "CONN      " MI_COL_HDRPAD_STR
28424 	    "rfq      " MI_COL_HDRPAD_STR
28425 	    "stq      " MI_COL_HDRPAD_STR
28426 	    " zone local                 remote");
28427 
28428 	/*
28429 	 * Because of the ndd constraint, at most we can have 64K buffer
28430 	 * to put in all conn info.  So to be more efficient, just
28431 	 * allocate a 64K buffer here, assuming we need that large buffer.
28432 	 * This should be OK as only privileged processes can do ndd /dev/ip.
28433 	 */
28434 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
28435 		/* The following may work even if we cannot get a large buf. */
28436 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
28437 		return (0);
28438 	}
28439 
28440 	conn_walk_fanout(conn_report1, mp->b_cont, connp->conn_zoneid,
28441 	    connp->conn_netstack->netstack_ip);
28442 	return (0);
28443 }
28444 
28445 /*
28446  * Determine if the ill and multicast aspects of that packets
28447  * "matches" the conn.
28448  */
28449 boolean_t
28450 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28451     zoneid_t zoneid)
28452 {
28453 	ill_t *in_ill;
28454 	boolean_t found;
28455 	ipif_t *ipif;
28456 	ire_t *ire;
28457 	ipaddr_t dst, src;
28458 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28459 
28460 	dst = ipha->ipha_dst;
28461 	src = ipha->ipha_src;
28462 
28463 	/*
28464 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28465 	 * unicast, broadcast and multicast reception to
28466 	 * conn_incoming_ill. conn_wantpacket itself is called
28467 	 * only for BROADCAST and multicast.
28468 	 *
28469 	 * 1) ip_rput supresses duplicate broadcasts if the ill
28470 	 *    is part of a group. Hence, we should be receiving
28471 	 *    just one copy of broadcast for the whole group.
28472 	 *    Thus, if it is part of the group the packet could
28473 	 *    come on any ill of the group and hence we need a
28474 	 *    match on the group. Otherwise, match on ill should
28475 	 *    be sufficient.
28476 	 *
28477 	 * 2) ip_rput does not suppress duplicate multicast packets.
28478 	 *    If there are two interfaces in a ill group and we have
28479 	 *    2 applications (conns) joined a multicast group G on
28480 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
28481 	 *    will give us two packets because we join G on both the
28482 	 *    interfaces rather than nominating just one interface
28483 	 *    for receiving multicast like broadcast above. So,
28484 	 *    we have to call ilg_lookup_ill to filter out duplicate
28485 	 *    copies, if ill is part of a group.
28486 	 */
28487 	in_ill = connp->conn_incoming_ill;
28488 	if (in_ill != NULL) {
28489 		if (in_ill->ill_group == NULL) {
28490 			if (in_ill != ill)
28491 				return (B_FALSE);
28492 		} else if (in_ill->ill_group != ill->ill_group) {
28493 			return (B_FALSE);
28494 		}
28495 	}
28496 
28497 	if (!CLASSD(dst)) {
28498 		if (IPCL_ZONE_MATCH(connp, zoneid))
28499 			return (B_TRUE);
28500 		/*
28501 		 * The conn is in a different zone; we need to check that this
28502 		 * broadcast address is configured in the application's zone and
28503 		 * on one ill in the group.
28504 		 */
28505 		ipif = ipif_get_next_ipif(NULL, ill);
28506 		if (ipif == NULL)
28507 			return (B_FALSE);
28508 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28509 		    connp->conn_zoneid, NULL,
28510 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
28511 		ipif_refrele(ipif);
28512 		if (ire != NULL) {
28513 			ire_refrele(ire);
28514 			return (B_TRUE);
28515 		} else {
28516 			return (B_FALSE);
28517 		}
28518 	}
28519 
28520 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28521 	    connp->conn_zoneid == zoneid) {
28522 		/*
28523 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28524 		 * disabled, therefore we don't dispatch the multicast packet to
28525 		 * the sending zone.
28526 		 */
28527 		return (B_FALSE);
28528 	}
28529 
28530 	if (IS_LOOPBACK(ill) && connp->conn_zoneid != zoneid) {
28531 		/*
28532 		 * Multicast packet on the loopback interface: we only match
28533 		 * conns who joined the group in the specified zone.
28534 		 */
28535 		return (B_FALSE);
28536 	}
28537 
28538 	if (connp->conn_multi_router) {
28539 		/* multicast packet and multicast router socket: send up */
28540 		return (B_TRUE);
28541 	}
28542 
28543 	mutex_enter(&connp->conn_lock);
28544 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28545 	mutex_exit(&connp->conn_lock);
28546 	return (found);
28547 }
28548 
28549 /*
28550  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28551  */
28552 /* ARGSUSED */
28553 static void
28554 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28555 {
28556 	ill_t *ill = (ill_t *)q->q_ptr;
28557 	mblk_t	*mp1, *mp2;
28558 	ipif_t  *ipif;
28559 	int err = 0;
28560 	conn_t *connp = NULL;
28561 	ipsq_t	*ipsq;
28562 	arc_t	*arc;
28563 
28564 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28565 
28566 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28567 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28568 
28569 	ASSERT(IAM_WRITER_ILL(ill));
28570 	mp2 = mp->b_cont;
28571 	mp->b_cont = NULL;
28572 
28573 	/*
28574 	 * We have now received the arp bringup completion message
28575 	 * from ARP. Mark the arp bringup as done. Also if the arp
28576 	 * stream has already started closing, send up the AR_ARP_CLOSING
28577 	 * ack now since ARP is waiting in close for this ack.
28578 	 */
28579 	mutex_enter(&ill->ill_lock);
28580 	ill->ill_arp_bringup_pending = 0;
28581 	if (ill->ill_arp_closing) {
28582 		mutex_exit(&ill->ill_lock);
28583 		/* Let's reuse the mp for sending the ack */
28584 		arc = (arc_t *)mp->b_rptr;
28585 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28586 		arc->arc_cmd = AR_ARP_CLOSING;
28587 		qreply(q, mp);
28588 	} else {
28589 		mutex_exit(&ill->ill_lock);
28590 		freeb(mp);
28591 	}
28592 
28593 	ipsq = ill->ill_phyint->phyint_ipsq;
28594 	ipif = ipsq->ipsq_pending_ipif;
28595 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28596 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
28597 	if (mp1 == NULL) {
28598 		/* bringup was aborted by the user */
28599 		freemsg(mp2);
28600 		return;
28601 	}
28602 
28603 	/*
28604 	 * If an IOCTL is waiting on this (ipsq_current_ioctl != 0), then we
28605 	 * must have an associated conn_t.  Otherwise, we're bringing this
28606 	 * interface back up as part of handling an asynchronous event (e.g.,
28607 	 * physical address change).
28608 	 */
28609 	if (ipsq->ipsq_current_ioctl != 0) {
28610 		ASSERT(connp != NULL);
28611 		q = CONNP_TO_WQ(connp);
28612 	} else {
28613 		ASSERT(connp == NULL);
28614 		q = ill->ill_rq;
28615 	}
28616 
28617 	/*
28618 	 * If the DL_BIND_REQ fails, it is noted
28619 	 * in arc_name_offset.
28620 	 */
28621 	err = *((int *)mp2->b_rptr);
28622 	if (err == 0) {
28623 		if (ipif->ipif_isv6) {
28624 			if ((err = ipif_up_done_v6(ipif)) != 0)
28625 				ip0dbg(("ip_arp_done: init failed\n"));
28626 		} else {
28627 			if ((err = ipif_up_done(ipif)) != 0)
28628 				ip0dbg(("ip_arp_done: init failed\n"));
28629 		}
28630 	} else {
28631 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28632 	}
28633 
28634 	freemsg(mp2);
28635 
28636 	if ((err == 0) && (ill->ill_up_ipifs)) {
28637 		err = ill_up_ipifs(ill, q, mp1);
28638 		if (err == EINPROGRESS)
28639 			return;
28640 	}
28641 
28642 	if (ill->ill_up_ipifs)
28643 		ill_group_cleanup(ill);
28644 
28645 	/*
28646 	 * The operation must complete without EINPROGRESS since
28647 	 * ipsq_pending_mp_get() has removed the mblk from ipsq_pending_mp.
28648 	 * Otherwise, the operation will be stuck forever in the ipsq.
28649 	 */
28650 	ASSERT(err != EINPROGRESS);
28651 	if (ipsq->ipsq_current_ioctl != 0)
28652 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
28653 	else
28654 		ipsq_current_finish(ipsq);
28655 }
28656 
28657 /* Allocate the private structure */
28658 static int
28659 ip_priv_alloc(void **bufp)
28660 {
28661 	void	*buf;
28662 
28663 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
28664 		return (ENOMEM);
28665 
28666 	*bufp = buf;
28667 	return (0);
28668 }
28669 
28670 /* Function to delete the private structure */
28671 void
28672 ip_priv_free(void *buf)
28673 {
28674 	ASSERT(buf != NULL);
28675 	kmem_free(buf, sizeof (ip_priv_t));
28676 }
28677 
28678 /*
28679  * The entry point for IPPF processing.
28680  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
28681  * routine just returns.
28682  *
28683  * When called, ip_process generates an ipp_packet_t structure
28684  * which holds the state information for this packet and invokes the
28685  * the classifier (via ipp_packet_process). The classification, depending on
28686  * configured filters, results in a list of actions for this packet. Invoking
28687  * an action may cause the packet to be dropped, in which case the resulting
28688  * mblk (*mpp) is NULL. proc indicates the callout position for
28689  * this packet and ill_index is the interface this packet on or will leave
28690  * on (inbound and outbound resp.).
28691  */
28692 void
28693 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
28694 {
28695 	mblk_t		*mp;
28696 	ip_priv_t	*priv;
28697 	ipp_action_id_t	aid;
28698 	int		rc = 0;
28699 	ipp_packet_t	*pp;
28700 #define	IP_CLASS	"ip"
28701 
28702 	/* If the classifier is not loaded, return  */
28703 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
28704 		return;
28705 	}
28706 
28707 	mp = *mpp;
28708 	ASSERT(mp != NULL);
28709 
28710 	/* Allocate the packet structure */
28711 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
28712 	if (rc != 0) {
28713 		*mpp = NULL;
28714 		freemsg(mp);
28715 		return;
28716 	}
28717 
28718 	/* Allocate the private structure */
28719 	rc = ip_priv_alloc((void **)&priv);
28720 	if (rc != 0) {
28721 		*mpp = NULL;
28722 		freemsg(mp);
28723 		ipp_packet_free(pp);
28724 		return;
28725 	}
28726 	priv->proc = proc;
28727 	priv->ill_index = ill_index;
28728 	ipp_packet_set_private(pp, priv, ip_priv_free);
28729 	ipp_packet_set_data(pp, mp);
28730 
28731 	/* Invoke the classifier */
28732 	rc = ipp_packet_process(&pp);
28733 	if (pp != NULL) {
28734 		mp = ipp_packet_get_data(pp);
28735 		ipp_packet_free(pp);
28736 		if (rc != 0) {
28737 			freemsg(mp);
28738 			*mpp = NULL;
28739 		}
28740 	} else {
28741 		*mpp = NULL;
28742 	}
28743 #undef	IP_CLASS
28744 }
28745 
28746 /*
28747  * Propagate a multicast group membership operation (add/drop) on
28748  * all the interfaces crossed by the related multirt routes.
28749  * The call is considered successful if the operation succeeds
28750  * on at least one interface.
28751  */
28752 static int
28753 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
28754     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
28755     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
28756     mblk_t *first_mp)
28757 {
28758 	ire_t		*ire_gw;
28759 	irb_t		*irb;
28760 	int		error = 0;
28761 	opt_restart_t	*or;
28762 	ip_stack_t	*ipst = ire->ire_ipst;
28763 
28764 	irb = ire->ire_bucket;
28765 	ASSERT(irb != NULL);
28766 
28767 	ASSERT(DB_TYPE(first_mp) == M_CTL);
28768 
28769 	or = (opt_restart_t *)first_mp->b_rptr;
28770 	IRB_REFHOLD(irb);
28771 	for (; ire != NULL; ire = ire->ire_next) {
28772 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
28773 			continue;
28774 		if (ire->ire_addr != group)
28775 			continue;
28776 
28777 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
28778 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
28779 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
28780 		/* No resolver exists for the gateway; skip this ire. */
28781 		if (ire_gw == NULL)
28782 			continue;
28783 
28784 		/*
28785 		 * This function can return EINPROGRESS. If so the operation
28786 		 * will be restarted from ip_restart_optmgmt which will
28787 		 * call ip_opt_set and option processing will restart for
28788 		 * this option. So we may end up calling 'fn' more than once.
28789 		 * This requires that 'fn' is idempotent except for the
28790 		 * return value. The operation is considered a success if
28791 		 * it succeeds at least once on any one interface.
28792 		 */
28793 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
28794 		    NULL, fmode, src, first_mp);
28795 		if (error == 0)
28796 			or->or_private = CGTP_MCAST_SUCCESS;
28797 
28798 		if (ip_debug > 0) {
28799 			ulong_t	off;
28800 			char	*ksym;
28801 			ksym = kobj_getsymname((uintptr_t)fn, &off);
28802 			ip2dbg(("ip_multirt_apply_membership: "
28803 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
28804 			    "error %d [success %u]\n",
28805 			    ksym ? ksym : "?",
28806 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
28807 			    error, or->or_private));
28808 		}
28809 
28810 		ire_refrele(ire_gw);
28811 		if (error == EINPROGRESS) {
28812 			IRB_REFRELE(irb);
28813 			return (error);
28814 		}
28815 	}
28816 	IRB_REFRELE(irb);
28817 	/*
28818 	 * Consider the call as successful if we succeeded on at least
28819 	 * one interface. Otherwise, return the last encountered error.
28820 	 */
28821 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
28822 }
28823 
28824 
28825 /*
28826  * Issue a warning regarding a route crossing an interface with an
28827  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
28828  * amount of time is logged.
28829  */
28830 static void
28831 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
28832 {
28833 	hrtime_t	current = gethrtime();
28834 	char		buf[INET_ADDRSTRLEN];
28835 	ip_stack_t	*ipst = ire->ire_ipst;
28836 
28837 	/* Convert interval in ms to hrtime in ns */
28838 	if (ipst->ips_multirt_bad_mtu_last_time +
28839 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
28840 	    current) {
28841 		cmn_err(CE_WARN, "ip: ignoring multiroute "
28842 		    "to %s, incorrect MTU %u (expected %u)\n",
28843 		    ip_dot_addr(ire->ire_addr, buf),
28844 		    ire->ire_max_frag, max_frag);
28845 
28846 		ipst->ips_multirt_bad_mtu_last_time = current;
28847 	}
28848 }
28849 
28850 
28851 /*
28852  * Get the CGTP (multirouting) filtering status.
28853  * If 0, the CGTP hooks are transparent.
28854  */
28855 /* ARGSUSED */
28856 static int
28857 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
28858 {
28859 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28860 
28861 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
28862 	return (0);
28863 }
28864 
28865 
28866 /*
28867  * Set the CGTP (multirouting) filtering status.
28868  * If the status is changed from active to transparent
28869  * or from transparent to active, forward the new status
28870  * to the filtering module (if loaded).
28871  */
28872 /* ARGSUSED */
28873 static int
28874 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
28875     cred_t *ioc_cr)
28876 {
28877 	long		new_value;
28878 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28879 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
28880 
28881 	if (secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
28882 		return (EPERM);
28883 
28884 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
28885 	    new_value < 0 || new_value > 1) {
28886 		return (EINVAL);
28887 	}
28888 
28889 	if ((!*ip_cgtp_filter_value) && new_value) {
28890 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
28891 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28892 		    " (module not loaded)" : "");
28893 	}
28894 	if (*ip_cgtp_filter_value && (!new_value)) {
28895 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
28896 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28897 		    " (module not loaded)" : "");
28898 	}
28899 
28900 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
28901 		int	res;
28902 		netstackid_t stackid;
28903 
28904 		stackid = ipst->ips_netstack->netstack_stackid;
28905 		res = ipst->ips_ip_cgtp_filter_ops->cfo_change_state(stackid,
28906 		    new_value);
28907 		if (res)
28908 			return (res);
28909 	}
28910 
28911 	*ip_cgtp_filter_value = (boolean_t)new_value;
28912 
28913 	return (0);
28914 }
28915 
28916 
28917 /*
28918  * Return the expected CGTP hooks version number.
28919  */
28920 int
28921 ip_cgtp_filter_supported(void)
28922 {
28923 	return (ip_cgtp_filter_rev);
28924 }
28925 
28926 
28927 /*
28928  * CGTP hooks can be registered by invoking this function.
28929  * Checks that the version number matches.
28930  */
28931 int
28932 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
28933 {
28934 	netstack_t *ns;
28935 	ip_stack_t *ipst;
28936 
28937 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
28938 		return (ENOTSUP);
28939 
28940 	ns = netstack_find_by_stackid(stackid);
28941 	if (ns == NULL)
28942 		return (EINVAL);
28943 	ipst = ns->netstack_ip;
28944 	ASSERT(ipst != NULL);
28945 
28946 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
28947 		netstack_rele(ns);
28948 		return (EALREADY);
28949 	}
28950 
28951 	ipst->ips_ip_cgtp_filter_ops = ops;
28952 	netstack_rele(ns);
28953 	return (0);
28954 }
28955 
28956 /*
28957  * CGTP hooks can be unregistered by invoking this function.
28958  * Returns ENXIO if there was no registration.
28959  * Returns EBUSY if the ndd variable has not been turned off.
28960  */
28961 int
28962 ip_cgtp_filter_unregister(netstackid_t stackid)
28963 {
28964 	netstack_t *ns;
28965 	ip_stack_t *ipst;
28966 
28967 	ns = netstack_find_by_stackid(stackid);
28968 	if (ns == NULL)
28969 		return (EINVAL);
28970 	ipst = ns->netstack_ip;
28971 	ASSERT(ipst != NULL);
28972 
28973 	if (ipst->ips_ip_cgtp_filter) {
28974 		netstack_rele(ns);
28975 		return (EBUSY);
28976 	}
28977 
28978 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
28979 		netstack_rele(ns);
28980 		return (ENXIO);
28981 	}
28982 	ipst->ips_ip_cgtp_filter_ops = NULL;
28983 	netstack_rele(ns);
28984 	return (0);
28985 }
28986 
28987 /*
28988  * Check whether there is a CGTP filter registration.
28989  * Returns non-zero if there is a registration, otherwise returns zero.
28990  * Note: returns zero if bad stackid.
28991  */
28992 int
28993 ip_cgtp_filter_is_registered(netstackid_t stackid)
28994 {
28995 	netstack_t *ns;
28996 	ip_stack_t *ipst;
28997 	int ret;
28998 
28999 	ns = netstack_find_by_stackid(stackid);
29000 	if (ns == NULL)
29001 		return (0);
29002 	ipst = ns->netstack_ip;
29003 	ASSERT(ipst != NULL);
29004 
29005 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
29006 		ret = 1;
29007 	else
29008 		ret = 0;
29009 
29010 	netstack_rele(ns);
29011 	return (ret);
29012 }
29013 
29014 static squeue_func_t
29015 ip_squeue_switch(int val)
29016 {
29017 	squeue_func_t rval = squeue_fill;
29018 
29019 	switch (val) {
29020 	case IP_SQUEUE_ENTER_NODRAIN:
29021 		rval = squeue_enter_nodrain;
29022 		break;
29023 	case IP_SQUEUE_ENTER:
29024 		rval = squeue_enter;
29025 		break;
29026 	default:
29027 		break;
29028 	}
29029 	return (rval);
29030 }
29031 
29032 /* ARGSUSED */
29033 static int
29034 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
29035     caddr_t addr, cred_t *cr)
29036 {
29037 	int *v = (int *)addr;
29038 	long new_value;
29039 
29040 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29041 		return (EPERM);
29042 
29043 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29044 		return (EINVAL);
29045 
29046 	ip_input_proc = ip_squeue_switch(new_value);
29047 	*v = new_value;
29048 	return (0);
29049 }
29050 
29051 /*
29052  * Handle ndd set of variables which require PRIV_SYS_NET_CONFIG such as
29053  * ip_debug.
29054  */
29055 /* ARGSUSED */
29056 static int
29057 ip_int_set(queue_t *q, mblk_t *mp, char *value,
29058     caddr_t addr, cred_t *cr)
29059 {
29060 	int *v = (int *)addr;
29061 	long new_value;
29062 
29063 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29064 		return (EPERM);
29065 
29066 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29067 		return (EINVAL);
29068 
29069 	*v = new_value;
29070 	return (0);
29071 }
29072 
29073 /*
29074  * Handle changes to ipmp_hook_emulation ndd variable.
29075  * Need to update phyint_hook_ifindex.
29076  * Also generate a nic plumb event should a new ifidex be assigned to a group.
29077  */
29078 static void
29079 ipmp_hook_emulation_changed(ip_stack_t *ipst)
29080 {
29081 	phyint_t *phyi;
29082 	phyint_t *phyi_tmp;
29083 	char *groupname;
29084 	int namelen;
29085 	ill_t	*ill;
29086 	boolean_t new_group;
29087 
29088 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29089 	/*
29090 	 * Group indicies are stored in the phyint - a common structure
29091 	 * to both IPv4 and IPv6.
29092 	 */
29093 	phyi = avl_first(&ipst->ips_phyint_g_list->phyint_list_avl_by_index);
29094 	for (; phyi != NULL;
29095 	    phyi = avl_walk(&ipst->ips_phyint_g_list->phyint_list_avl_by_index,
29096 	    phyi, AVL_AFTER)) {
29097 		/* Ignore the ones that do not have a group */
29098 		if (phyi->phyint_groupname_len == 0)
29099 			continue;
29100 
29101 		/*
29102 		 * Look for other phyint in group.
29103 		 * Clear name/namelen so the lookup doesn't find ourselves.
29104 		 */
29105 		namelen = phyi->phyint_groupname_len;
29106 		groupname = phyi->phyint_groupname;
29107 		phyi->phyint_groupname_len = 0;
29108 		phyi->phyint_groupname = NULL;
29109 
29110 		phyi_tmp = phyint_lookup_group(groupname, B_FALSE, ipst);
29111 		/* Restore */
29112 		phyi->phyint_groupname_len = namelen;
29113 		phyi->phyint_groupname = groupname;
29114 
29115 		new_group = B_FALSE;
29116 		if (ipst->ips_ipmp_hook_emulation) {
29117 			/*
29118 			 * If the group already exists and has already
29119 			 * been assigned a group ifindex, we use the existing
29120 			 * group_ifindex, otherwise we pick a new group_ifindex
29121 			 * here.
29122 			 */
29123 			if (phyi_tmp != NULL &&
29124 			    phyi_tmp->phyint_group_ifindex != 0) {
29125 				phyi->phyint_group_ifindex =
29126 				    phyi_tmp->phyint_group_ifindex;
29127 			} else {
29128 				/* XXX We need a recovery strategy here. */
29129 				if (!ip_assign_ifindex(
29130 				    &phyi->phyint_group_ifindex, ipst))
29131 					cmn_err(CE_PANIC,
29132 					    "ip_assign_ifindex() failed");
29133 				new_group = B_TRUE;
29134 			}
29135 		} else {
29136 			phyi->phyint_group_ifindex = 0;
29137 		}
29138 		if (ipst->ips_ipmp_hook_emulation)
29139 			phyi->phyint_hook_ifindex = phyi->phyint_group_ifindex;
29140 		else
29141 			phyi->phyint_hook_ifindex = phyi->phyint_ifindex;
29142 
29143 		/*
29144 		 * For IP Filter to find out the relationship between
29145 		 * names and interface indicies, we need to generate
29146 		 * a NE_PLUMB event when a new group can appear.
29147 		 * We always generate events when a new interface appears
29148 		 * (even when ipmp_hook_emulation is set) so there
29149 		 * is no need to generate NE_PLUMB events when
29150 		 * ipmp_hook_emulation is turned off.
29151 		 * And since it isn't critical for IP Filter to get
29152 		 * the NE_UNPLUMB events we skip those here.
29153 		 */
29154 		if (new_group) {
29155 			/*
29156 			 * First phyint in group - generate group PLUMB event.
29157 			 * Since we are not running inside the ipsq we do
29158 			 * the dispatch immediately.
29159 			 */
29160 			if (phyi->phyint_illv4 != NULL)
29161 				ill = phyi->phyint_illv4;
29162 			else
29163 				ill = phyi->phyint_illv6;
29164 
29165 			if (ill != NULL) {
29166 				mutex_enter(&ill->ill_lock);
29167 				ill_nic_info_plumb(ill, B_TRUE);
29168 				ill_nic_info_dispatch(ill);
29169 				mutex_exit(&ill->ill_lock);
29170 			}
29171 		}
29172 	}
29173 	rw_exit(&ipst->ips_ill_g_lock);
29174 }
29175 
29176 /* ARGSUSED */
29177 static int
29178 ipmp_hook_emulation_set(queue_t *q, mblk_t *mp, char *value,
29179     caddr_t addr, cred_t *cr)
29180 {
29181 	int *v = (int *)addr;
29182 	long new_value;
29183 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29184 
29185 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29186 		return (EINVAL);
29187 
29188 	if (*v != new_value) {
29189 		*v = new_value;
29190 		ipmp_hook_emulation_changed(ipst);
29191 	}
29192 	return (0);
29193 }
29194 
29195 static void *
29196 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
29197 {
29198 	kstat_t *ksp;
29199 
29200 	ip_stat_t template = {
29201 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
29202 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
29203 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
29204 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
29205 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
29206 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
29207 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
29208 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
29209 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
29210 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
29211 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
29212 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
29213 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
29214 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
29215 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
29216 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
29217 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
29218 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
29219 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
29220 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
29221 		{ "ip_opt",			KSTAT_DATA_UINT64 },
29222 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
29223 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
29224 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29225 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29226 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29227 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29228 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29229 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29230 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29231 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29232 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29233 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29234 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29235 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29236 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29237 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29238 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29239 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29240 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29241 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29242 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29243 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29244 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29245 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29246 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29247 	};
29248 
29249 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29250 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29251 	    KSTAT_FLAG_VIRTUAL, stackid);
29252 
29253 	if (ksp == NULL)
29254 		return (NULL);
29255 
29256 	bcopy(&template, ip_statisticsp, sizeof (template));
29257 	ksp->ks_data = (void *)ip_statisticsp;
29258 	ksp->ks_private = (void *)(uintptr_t)stackid;
29259 
29260 	kstat_install(ksp);
29261 	return (ksp);
29262 }
29263 
29264 static void
29265 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29266 {
29267 	if (ksp != NULL) {
29268 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29269 		kstat_delete_netstack(ksp, stackid);
29270 	}
29271 }
29272 
29273 static void *
29274 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29275 {
29276 	kstat_t	*ksp;
29277 
29278 	ip_named_kstat_t template = {
29279 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29280 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29281 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29282 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29283 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29284 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29285 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29286 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29287 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29288 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29289 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29290 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29291 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29292 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29293 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29294 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29295 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29296 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29297 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29298 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29299 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29300 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29301 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29302 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29303 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29304 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29305 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29306 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29307 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29308 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29309 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29310 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29311 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29312 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29313 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29314 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29315 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29316 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29317 	};
29318 
29319 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29320 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
29321 	if (ksp == NULL || ksp->ks_data == NULL)
29322 		return (NULL);
29323 
29324 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29325 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29326 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29327 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29328 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29329 
29330 	template.netToMediaEntrySize.value.i32 =
29331 	    sizeof (mib2_ipNetToMediaEntry_t);
29332 
29333 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29334 
29335 	bcopy(&template, ksp->ks_data, sizeof (template));
29336 	ksp->ks_update = ip_kstat_update;
29337 	ksp->ks_private = (void *)(uintptr_t)stackid;
29338 
29339 	kstat_install(ksp);
29340 	return (ksp);
29341 }
29342 
29343 static void
29344 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29345 {
29346 	if (ksp != NULL) {
29347 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29348 		kstat_delete_netstack(ksp, stackid);
29349 	}
29350 }
29351 
29352 static int
29353 ip_kstat_update(kstat_t *kp, int rw)
29354 {
29355 	ip_named_kstat_t *ipkp;
29356 	mib2_ipIfStatsEntry_t ipmib;
29357 	ill_walk_context_t ctx;
29358 	ill_t *ill;
29359 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29360 	netstack_t	*ns;
29361 	ip_stack_t	*ipst;
29362 
29363 	if (kp == NULL || kp->ks_data == NULL)
29364 		return (EIO);
29365 
29366 	if (rw == KSTAT_WRITE)
29367 		return (EACCES);
29368 
29369 	ns = netstack_find_by_stackid(stackid);
29370 	if (ns == NULL)
29371 		return (-1);
29372 	ipst = ns->netstack_ip;
29373 	if (ipst == NULL) {
29374 		netstack_rele(ns);
29375 		return (-1);
29376 	}
29377 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29378 
29379 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29380 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29381 	ill = ILL_START_WALK_V4(&ctx, ipst);
29382 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29383 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29384 	rw_exit(&ipst->ips_ill_g_lock);
29385 
29386 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29387 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29388 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29389 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29390 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29391 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29392 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29393 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29394 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29395 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29396 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29397 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29398 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29399 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29400 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29401 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29402 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29403 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29404 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29405 
29406 	ipkp->routingDiscards.value.ui32 =	0;
29407 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29408 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29409 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29410 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29411 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29412 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29413 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29414 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29415 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29416 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29417 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29418 
29419 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29420 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29421 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29422 
29423 	netstack_rele(ns);
29424 
29425 	return (0);
29426 }
29427 
29428 static void *
29429 icmp_kstat_init(netstackid_t stackid)
29430 {
29431 	kstat_t	*ksp;
29432 
29433 	icmp_named_kstat_t template = {
29434 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29435 		{ "inErrors",		KSTAT_DATA_UINT32 },
29436 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29437 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29438 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29439 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29440 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29441 		{ "inEchos",		KSTAT_DATA_UINT32 },
29442 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29443 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29444 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29445 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29446 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29447 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29448 		{ "outErrors",		KSTAT_DATA_UINT32 },
29449 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29450 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29451 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29452 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29453 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29454 		{ "outEchos",		KSTAT_DATA_UINT32 },
29455 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29456 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29457 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29458 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29459 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29460 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29461 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29462 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29463 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29464 		{ "outDrops",		KSTAT_DATA_UINT32 },
29465 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29466 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29467 	};
29468 
29469 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29470 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
29471 	if (ksp == NULL || ksp->ks_data == NULL)
29472 		return (NULL);
29473 
29474 	bcopy(&template, ksp->ks_data, sizeof (template));
29475 
29476 	ksp->ks_update = icmp_kstat_update;
29477 	ksp->ks_private = (void *)(uintptr_t)stackid;
29478 
29479 	kstat_install(ksp);
29480 	return (ksp);
29481 }
29482 
29483 static void
29484 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29485 {
29486 	if (ksp != NULL) {
29487 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29488 		kstat_delete_netstack(ksp, stackid);
29489 	}
29490 }
29491 
29492 static int
29493 icmp_kstat_update(kstat_t *kp, int rw)
29494 {
29495 	icmp_named_kstat_t *icmpkp;
29496 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29497 	netstack_t	*ns;
29498 	ip_stack_t	*ipst;
29499 
29500 	if ((kp == NULL) || (kp->ks_data == NULL))
29501 		return (EIO);
29502 
29503 	if (rw == KSTAT_WRITE)
29504 		return (EACCES);
29505 
29506 	ns = netstack_find_by_stackid(stackid);
29507 	if (ns == NULL)
29508 		return (-1);
29509 	ipst = ns->netstack_ip;
29510 	if (ipst == NULL) {
29511 		netstack_rele(ns);
29512 		return (-1);
29513 	}
29514 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29515 
29516 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29517 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29518 	icmpkp->inDestUnreachs.value.ui32 =
29519 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29520 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29521 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29522 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29523 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29524 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29525 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29526 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29527 	icmpkp->inTimestampReps.value.ui32 =
29528 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29529 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29530 	icmpkp->inAddrMaskReps.value.ui32 =
29531 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29532 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29533 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29534 	icmpkp->outDestUnreachs.value.ui32 =
29535 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29536 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29537 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29538 	icmpkp->outSrcQuenchs.value.ui32 =
29539 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29540 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29541 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29542 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29543 	icmpkp->outTimestamps.value.ui32 =
29544 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29545 	icmpkp->outTimestampReps.value.ui32 =
29546 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29547 	icmpkp->outAddrMasks.value.ui32 =
29548 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29549 	icmpkp->outAddrMaskReps.value.ui32 =
29550 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29551 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29552 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29553 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29554 	icmpkp->outFragNeeded.value.ui32 =
29555 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29556 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29557 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29558 	icmpkp->inBadRedirects.value.ui32 =
29559 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29560 
29561 	netstack_rele(ns);
29562 	return (0);
29563 }
29564 
29565 /*
29566  * This is the fanout function for raw socket opened for SCTP.  Note
29567  * that it is called after SCTP checks that there is no socket which
29568  * wants a packet.  Then before SCTP handles this out of the blue packet,
29569  * this function is called to see if there is any raw socket for SCTP.
29570  * If there is and it is bound to the correct address, the packet will
29571  * be sent to that socket.  Note that only one raw socket can be bound to
29572  * a port.  This is assured in ipcl_sctp_hash_insert();
29573  */
29574 void
29575 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29576     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29577     zoneid_t zoneid)
29578 {
29579 	conn_t		*connp;
29580 	queue_t		*rq;
29581 	mblk_t		*first_mp;
29582 	boolean_t	secure;
29583 	ip6_t		*ip6h;
29584 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29585 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29586 
29587 	first_mp = mp;
29588 	if (mctl_present) {
29589 		mp = first_mp->b_cont;
29590 		secure = ipsec_in_is_secure(first_mp);
29591 		ASSERT(mp != NULL);
29592 	} else {
29593 		secure = B_FALSE;
29594 	}
29595 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29596 
29597 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29598 	if (connp == NULL) {
29599 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29600 		return;
29601 	}
29602 	rq = connp->conn_rq;
29603 	if (!canputnext(rq)) {
29604 		CONN_DEC_REF(connp);
29605 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29606 		freemsg(first_mp);
29607 		return;
29608 	}
29609 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29610 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29611 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29612 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29613 		if (first_mp == NULL) {
29614 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29615 			CONN_DEC_REF(connp);
29616 			return;
29617 		}
29618 	}
29619 	/*
29620 	 * We probably should not send M_CTL message up to
29621 	 * raw socket.
29622 	 */
29623 	if (mctl_present)
29624 		freeb(first_mp);
29625 
29626 	/* Initiate IPPF processing here if needed. */
29627 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
29628 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
29629 		ip_process(IPP_LOCAL_IN, &mp,
29630 		    recv_ill->ill_phyint->phyint_ifindex);
29631 		if (mp == NULL) {
29632 			CONN_DEC_REF(connp);
29633 			return;
29634 		}
29635 	}
29636 
29637 	if (connp->conn_recvif || connp->conn_recvslla ||
29638 	    ((connp->conn_ip_recvpktinfo ||
29639 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29640 	    (flags & IP_FF_IPINFO))) {
29641 		int in_flags = 0;
29642 
29643 		/*
29644 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29645 		 * IPF_RECVIF.
29646 		 */
29647 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29648 			in_flags = IPF_RECVIF;
29649 		}
29650 		if (connp->conn_recvslla) {
29651 			in_flags |= IPF_RECVSLLA;
29652 		}
29653 		if (isv4) {
29654 			mp = ip_add_info(mp, recv_ill, in_flags,
29655 			    IPCL_ZONEID(connp), ipst);
29656 		} else {
29657 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
29658 			if (mp == NULL) {
29659 				BUMP_MIB(recv_ill->ill_ip_mib,
29660 				    ipIfStatsInDiscards);
29661 				CONN_DEC_REF(connp);
29662 				return;
29663 			}
29664 		}
29665 	}
29666 
29667 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
29668 	/*
29669 	 * We are sending the IPSEC_IN message also up. Refer
29670 	 * to comments above this function.
29671 	 * This is the SOCK_RAW, IPPROTO_SCTP case.
29672 	 */
29673 	(connp->conn_recv)(connp, mp, NULL);
29674 	CONN_DEC_REF(connp);
29675 }
29676 
29677 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
29678 {									\
29679 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
29680 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
29681 }
29682 /*
29683  * This function should be called only if all packet processing
29684  * including fragmentation is complete. Callers of this function
29685  * must set mp->b_prev to one of these values:
29686  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
29687  * prior to handing over the mp as first argument to this function.
29688  *
29689  * If the ire passed by caller is incomplete, this function
29690  * queues the packet and if necessary, sends ARP request and bails.
29691  * If the ire passed is fully resolved, we simply prepend
29692  * the link-layer header to the packet, do ipsec hw acceleration
29693  * work if necessary, and send the packet out on the wire.
29694  *
29695  * NOTE: IPsec will only call this function with fully resolved
29696  * ires if hw acceleration is involved.
29697  * TODO list :
29698  * 	a Handle M_MULTIDATA so that
29699  *	  tcp_multisend->tcp_multisend_data can
29700  *	  call ip_xmit_v4 directly
29701  *	b Handle post-ARP work for fragments so that
29702  *	  ip_wput_frag can call this function.
29703  */
29704 ipxmit_state_t
29705 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io, boolean_t flow_ctl_enabled)
29706 {
29707 	nce_t		*arpce;
29708 	queue_t		*q;
29709 	int		ill_index;
29710 	mblk_t		*nxt_mp, *first_mp;
29711 	boolean_t	xmit_drop = B_FALSE;
29712 	ip_proc_t	proc;
29713 	ill_t		*out_ill;
29714 	int		pkt_len;
29715 
29716 	arpce = ire->ire_nce;
29717 	ASSERT(arpce != NULL);
29718 
29719 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
29720 
29721 	mutex_enter(&arpce->nce_lock);
29722 	switch (arpce->nce_state) {
29723 	case ND_REACHABLE:
29724 		/* If there are other queued packets, queue this packet */
29725 		if (arpce->nce_qd_mp != NULL) {
29726 			if (mp != NULL)
29727 				nce_queue_mp_common(arpce, mp, B_FALSE);
29728 			mp = arpce->nce_qd_mp;
29729 		}
29730 		arpce->nce_qd_mp = NULL;
29731 		mutex_exit(&arpce->nce_lock);
29732 
29733 		/*
29734 		 * Flush the queue.  In the common case, where the
29735 		 * ARP is already resolved,  it will go through the
29736 		 * while loop only once.
29737 		 */
29738 		while (mp != NULL) {
29739 
29740 			nxt_mp = mp->b_next;
29741 			mp->b_next = NULL;
29742 			ASSERT(mp->b_datap->db_type != M_CTL);
29743 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
29744 			/*
29745 			 * This info is needed for IPQOS to do COS marking
29746 			 * in ip_wput_attach_llhdr->ip_process.
29747 			 */
29748 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
29749 			mp->b_prev = NULL;
29750 
29751 			/* set up ill index for outbound qos processing */
29752 			out_ill = ire_to_ill(ire);
29753 			ill_index = out_ill->ill_phyint->phyint_ifindex;
29754 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
29755 			    ill_index);
29756 			if (first_mp == NULL) {
29757 				xmit_drop = B_TRUE;
29758 				BUMP_MIB(out_ill->ill_ip_mib,
29759 				    ipIfStatsOutDiscards);
29760 				goto next_mp;
29761 			}
29762 			/* non-ipsec hw accel case */
29763 			if (io == NULL || !io->ipsec_out_accelerated) {
29764 				/* send it */
29765 				q = ire->ire_stq;
29766 				if (proc == IPP_FWD_OUT) {
29767 					UPDATE_IB_PKT_COUNT(ire);
29768 				} else {
29769 					UPDATE_OB_PKT_COUNT(ire);
29770 				}
29771 				ire->ire_last_used_time = lbolt;
29772 
29773 				if (flow_ctl_enabled || canputnext(q)) {
29774 					if (proc == IPP_FWD_OUT) {
29775 
29776 					BUMP_MIB(out_ill->ill_ip_mib,
29777 					    ipIfStatsHCOutForwDatagrams);
29778 
29779 					}
29780 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
29781 					    pkt_len);
29782 
29783 					putnext(q, first_mp);
29784 				} else {
29785 					BUMP_MIB(out_ill->ill_ip_mib,
29786 					    ipIfStatsOutDiscards);
29787 					xmit_drop = B_TRUE;
29788 					freemsg(first_mp);
29789 				}
29790 			} else {
29791 				/*
29792 				 * Safety Pup says: make sure this
29793 				 *  is going to the right interface!
29794 				 */
29795 				ill_t *ill1 =
29796 				    (ill_t *)ire->ire_stq->q_ptr;
29797 				int ifindex =
29798 				    ill1->ill_phyint->phyint_ifindex;
29799 				if (ifindex !=
29800 				    io->ipsec_out_capab_ill_index) {
29801 					xmit_drop = B_TRUE;
29802 					freemsg(mp);
29803 				} else {
29804 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
29805 					    pkt_len);
29806 					ipsec_hw_putnext(ire->ire_stq, mp);
29807 				}
29808 			}
29809 next_mp:
29810 			mp = nxt_mp;
29811 		} /* while (mp != NULL) */
29812 		if (xmit_drop)
29813 			return (SEND_FAILED);
29814 		else
29815 			return (SEND_PASSED);
29816 
29817 	case ND_INITIAL:
29818 	case ND_INCOMPLETE:
29819 
29820 		/*
29821 		 * While we do send off packets to dests that
29822 		 * use fully-resolved CGTP routes, we do not
29823 		 * handle unresolved CGTP routes.
29824 		 */
29825 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
29826 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
29827 
29828 		if (mp != NULL) {
29829 			/* queue the packet */
29830 			nce_queue_mp_common(arpce, mp, B_FALSE);
29831 		}
29832 
29833 		if (arpce->nce_state == ND_INCOMPLETE) {
29834 			mutex_exit(&arpce->nce_lock);
29835 			DTRACE_PROBE3(ip__xmit__incomplete,
29836 			    (ire_t *), ire, (mblk_t *), mp,
29837 			    (ipsec_out_t *), io);
29838 			return (LOOKUP_IN_PROGRESS);
29839 		}
29840 
29841 		arpce->nce_state = ND_INCOMPLETE;
29842 		mutex_exit(&arpce->nce_lock);
29843 		/*
29844 		 * Note that ire_add() (called from ire_forward())
29845 		 * holds a ref on the ire until ARP is completed.
29846 		 */
29847 
29848 		ire_arpresolve(ire, ire_to_ill(ire));
29849 		return (LOOKUP_IN_PROGRESS);
29850 	default:
29851 		ASSERT(0);
29852 		mutex_exit(&arpce->nce_lock);
29853 		return (LLHDR_RESLV_FAILED);
29854 	}
29855 }
29856 
29857 #undef	UPDATE_IP_MIB_OB_COUNTERS
29858 
29859 /*
29860  * Return B_TRUE if the buffers differ in length or content.
29861  * This is used for comparing extension header buffers.
29862  * Note that an extension header would be declared different
29863  * even if all that changed was the next header value in that header i.e.
29864  * what really changed is the next extension header.
29865  */
29866 boolean_t
29867 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
29868     uint_t blen)
29869 {
29870 	if (!b_valid)
29871 		blen = 0;
29872 
29873 	if (alen != blen)
29874 		return (B_TRUE);
29875 	if (alen == 0)
29876 		return (B_FALSE);	/* Both zero length */
29877 	return (bcmp(abuf, bbuf, alen));
29878 }
29879 
29880 /*
29881  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
29882  * Return B_FALSE if memory allocation fails - don't change any state!
29883  */
29884 boolean_t
29885 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29886     const void *src, uint_t srclen)
29887 {
29888 	void *dst;
29889 
29890 	if (!src_valid)
29891 		srclen = 0;
29892 
29893 	ASSERT(*dstlenp == 0);
29894 	if (src != NULL && srclen != 0) {
29895 		dst = mi_alloc(srclen, BPRI_MED);
29896 		if (dst == NULL)
29897 			return (B_FALSE);
29898 	} else {
29899 		dst = NULL;
29900 	}
29901 	if (*dstp != NULL)
29902 		mi_free(*dstp);
29903 	*dstp = dst;
29904 	*dstlenp = dst == NULL ? 0 : srclen;
29905 	return (B_TRUE);
29906 }
29907 
29908 /*
29909  * Replace what is in *dst, *dstlen with the source.
29910  * Assumes ip_allocbuf has already been called.
29911  */
29912 void
29913 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29914     const void *src, uint_t srclen)
29915 {
29916 	if (!src_valid)
29917 		srclen = 0;
29918 
29919 	ASSERT(*dstlenp == srclen);
29920 	if (src != NULL && srclen != 0)
29921 		bcopy(src, *dstp, srclen);
29922 }
29923 
29924 /*
29925  * Free the storage pointed to by the members of an ip6_pkt_t.
29926  */
29927 void
29928 ip6_pkt_free(ip6_pkt_t *ipp)
29929 {
29930 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
29931 
29932 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
29933 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
29934 		ipp->ipp_hopopts = NULL;
29935 		ipp->ipp_hopoptslen = 0;
29936 	}
29937 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
29938 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
29939 		ipp->ipp_rtdstopts = NULL;
29940 		ipp->ipp_rtdstoptslen = 0;
29941 	}
29942 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
29943 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
29944 		ipp->ipp_dstopts = NULL;
29945 		ipp->ipp_dstoptslen = 0;
29946 	}
29947 	if (ipp->ipp_fields & IPPF_RTHDR) {
29948 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
29949 		ipp->ipp_rthdr = NULL;
29950 		ipp->ipp_rthdrlen = 0;
29951 	}
29952 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
29953 	    IPPF_RTHDR);
29954 }
29955