xref: /titanic_51/usr/src/uts/common/inet/ip/ip.c (revision a4e4e13f4001644f2f960e3be0056c22b3a40fd1)
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 
7672 	/* We assume Class E default netmask to be 32 */
7673 	if (CLASSE(addr))
7674 		return (0xffffffffU);
7675 
7676 	if (addr == 0)
7677 		return (0);
7678 	maskp[0] = 0xFF;
7679 	if ((up[0] & 0x80) == 0)
7680 		return (mask);
7681 
7682 	maskp[1] = 0xFF;
7683 	if ((up[0] & 0xC0) == 0x80)
7684 		return (mask);
7685 
7686 	maskp[2] = 0xFF;
7687 	if ((up[0] & 0xE0) == 0xC0)
7688 		return (mask);
7689 
7690 	/* Otherwise return no mask */
7691 	return ((ipaddr_t)0);
7692 }
7693 
7694 /*
7695  * Select an ill for the packet by considering load spreading across
7696  * a different ill in the group if dst_ill is part of some group.
7697  */
7698 ill_t *
7699 ip_newroute_get_dst_ill(ill_t *dst_ill)
7700 {
7701 	ill_t *ill;
7702 
7703 	/*
7704 	 * We schedule irrespective of whether the source address is
7705 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7706 	 */
7707 	ill = illgrp_scheduler(dst_ill);
7708 	if (ill == NULL)
7709 		return (NULL);
7710 
7711 	/*
7712 	 * For groups with names ip_sioctl_groupname ensures that all
7713 	 * ills are of same type. For groups without names, ifgrp_insert
7714 	 * ensures this.
7715 	 */
7716 	ASSERT(dst_ill->ill_type == ill->ill_type);
7717 
7718 	return (ill);
7719 }
7720 
7721 /*
7722  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7723  */
7724 ill_t *
7725 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6,
7726     ip_stack_t *ipst)
7727 {
7728 	ill_t *ret_ill;
7729 
7730 	ASSERT(ifindex != 0);
7731 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7732 	    ipst);
7733 	if (ret_ill == NULL ||
7734 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7735 		if (isv6) {
7736 			if (ill != NULL) {
7737 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7738 			} else {
7739 				BUMP_MIB(&ipst->ips_ip6_mib,
7740 				    ipIfStatsOutDiscards);
7741 			}
7742 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7743 			    "bad ifindex %d.\n", ifindex));
7744 		} else {
7745 			if (ill != NULL) {
7746 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7747 			} else {
7748 				BUMP_MIB(&ipst->ips_ip_mib,
7749 				    ipIfStatsOutDiscards);
7750 			}
7751 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7752 			    "bad ifindex %d.\n", ifindex));
7753 		}
7754 		if (ret_ill != NULL)
7755 			ill_refrele(ret_ill);
7756 		freemsg(first_mp);
7757 		return (NULL);
7758 	}
7759 
7760 	return (ret_ill);
7761 }
7762 
7763 /*
7764  * IPv4 -
7765  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7766  * out a packet to a destination address for which we do not have specific
7767  * (or sufficient) routing information.
7768  *
7769  * NOTE : These are the scopes of some of the variables that point at IRE,
7770  *	  which needs to be followed while making any future modifications
7771  *	  to avoid memory leaks.
7772  *
7773  *	- ire and sire are the entries looked up initially by
7774  *	  ire_ftable_lookup.
7775  *	- ipif_ire is used to hold the interface ire associated with
7776  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7777  *	  it before branching out to error paths.
7778  *	- save_ire is initialized before ire_create, so that ire returned
7779  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7780  *	  before breaking out of the switch.
7781  *
7782  *	Thus on failures, we have to REFRELE only ire and sire, if they
7783  *	are not NULL.
7784  */
7785 void
7786 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, conn_t *connp,
7787     zoneid_t zoneid, ip_stack_t *ipst)
7788 {
7789 	areq_t	*areq;
7790 	ipaddr_t gw = 0;
7791 	ire_t	*ire = NULL;
7792 	mblk_t	*res_mp;
7793 	ipaddr_t *addrp;
7794 	ipaddr_t nexthop_addr;
7795 	ipif_t  *src_ipif = NULL;
7796 	ill_t	*dst_ill = NULL;
7797 	ipha_t  *ipha;
7798 	ire_t	*sire = NULL;
7799 	mblk_t	*first_mp;
7800 	ire_t	*save_ire;
7801 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7802 	ushort_t ire_marks = 0;
7803 	boolean_t mctl_present;
7804 	ipsec_out_t *io;
7805 	mblk_t	*saved_mp;
7806 	ire_t	*first_sire = NULL;
7807 	mblk_t	*copy_mp = NULL;
7808 	mblk_t	*xmit_mp = NULL;
7809 	ipaddr_t save_dst;
7810 	uint32_t multirt_flags =
7811 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7812 	boolean_t multirt_is_resolvable;
7813 	boolean_t multirt_resolve_next;
7814 	boolean_t unspec_src;
7815 	boolean_t do_attach_ill = B_FALSE;
7816 	boolean_t ip_nexthop = B_FALSE;
7817 	tsol_ire_gw_secattr_t *attrp = NULL;
7818 	tsol_gcgrp_t *gcgrp = NULL;
7819 	tsol_gcgrp_addr_t ga;
7820 
7821 	if (ip_debug > 2) {
7822 		/* ip1dbg */
7823 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7824 	}
7825 
7826 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7827 	if (mctl_present) {
7828 		io = (ipsec_out_t *)first_mp->b_rptr;
7829 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7830 		ASSERT(zoneid == io->ipsec_out_zoneid);
7831 		ASSERT(zoneid != ALL_ZONES);
7832 	}
7833 
7834 	ipha = (ipha_t *)mp->b_rptr;
7835 
7836 	/* All multicast lookups come through ip_newroute_ipif() */
7837 	if (CLASSD(dst)) {
7838 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7839 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7840 		freemsg(first_mp);
7841 		return;
7842 	}
7843 
7844 	if (mctl_present && io->ipsec_out_attach_if) {
7845 		/* ip_grab_attach_ill returns a held ill */
7846 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7847 		    io->ipsec_out_ill_index, B_FALSE, ipst);
7848 
7849 		/* Failure case frees things for us. */
7850 		if (attach_ill == NULL)
7851 			return;
7852 
7853 		/*
7854 		 * Check if we need an ire that will not be
7855 		 * looked up by anybody else i.e. HIDDEN.
7856 		 */
7857 		if (ill_is_probeonly(attach_ill))
7858 			ire_marks = IRE_MARK_HIDDEN;
7859 	}
7860 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7861 		ip_nexthop = B_TRUE;
7862 		nexthop_addr = io->ipsec_out_nexthop_addr;
7863 	}
7864 	/*
7865 	 * If this IRE is created for forwarding or it is not for
7866 	 * traffic for congestion controlled protocols, mark it as temporary.
7867 	 */
7868 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7869 		ire_marks |= IRE_MARK_TEMPORARY;
7870 
7871 	/*
7872 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7873 	 * chain until it gets the most specific information available.
7874 	 * For example, we know that there is no IRE_CACHE for this dest,
7875 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7876 	 * ire_ftable_lookup will look up the gateway, etc.
7877 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7878 	 * to the destination, of equal netmask length in the forward table,
7879 	 * will be recursively explored. If no information is available
7880 	 * for the final gateway of that route, we force the returned ire
7881 	 * to be equal to sire using MATCH_IRE_PARENT.
7882 	 * At least, in this case we have a starting point (in the buckets)
7883 	 * to look for other routes to the destination in the forward table.
7884 	 * This is actually used only for multirouting, where a list
7885 	 * of routes has to be processed in sequence.
7886 	 *
7887 	 * In the process of coming up with the most specific information,
7888 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7889 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7890 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7891 	 * Two caveats when handling incomplete ire's in ip_newroute:
7892 	 * - we should be careful when accessing its ire_nce (specifically
7893 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7894 	 * - not all legacy code path callers are prepared to handle
7895 	 *   incomplete ire's, so we should not create/add incomplete
7896 	 *   ire_cache entries here. (See discussion about temporary solution
7897 	 *   further below).
7898 	 *
7899 	 * In order to minimize packet dropping, and to preserve existing
7900 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7901 	 * gateway, and instead use the IF_RESOLVER ire to send out
7902 	 * another request to ARP (this is achieved by passing the
7903 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
7904 	 * arp response comes back in ip_wput_nondata, we will create
7905 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
7906 	 *
7907 	 * Note that this is a temporary solution; the correct solution is
7908 	 * to create an incomplete  per-dst ire_cache entry, and send the
7909 	 * packet out when the gw's nce is resolved. In order to achieve this,
7910 	 * all packet processing must have been completed prior to calling
7911 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
7912 	 * to be modified to accomodate this solution.
7913 	 */
7914 	if (ip_nexthop) {
7915 		/*
7916 		 * The first time we come here, we look for an IRE_INTERFACE
7917 		 * entry for the specified nexthop, set the dst to be the
7918 		 * nexthop address and create an IRE_CACHE entry for the
7919 		 * nexthop. The next time around, we are able to find an
7920 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7921 		 * nexthop address and create an IRE_CACHE entry for the
7922 		 * destination address via the specified nexthop.
7923 		 */
7924 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7925 		    MBLK_GETLABEL(mp), ipst);
7926 		if (ire != NULL) {
7927 			gw = nexthop_addr;
7928 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7929 		} else {
7930 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7931 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7932 			    MBLK_GETLABEL(mp),
7933 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
7934 			    ipst);
7935 			if (ire != NULL) {
7936 				dst = nexthop_addr;
7937 			}
7938 		}
7939 	} else if (attach_ill == NULL) {
7940 		ire = ire_ftable_lookup(dst, 0, 0, 0,
7941 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
7942 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
7943 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
7944 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
7945 		    ipst);
7946 	} else {
7947 		/*
7948 		 * attach_ill is set only for communicating with
7949 		 * on-link hosts. So, don't look for DEFAULT.
7950 		 */
7951 		ipif_t	*attach_ipif;
7952 
7953 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
7954 		if (attach_ipif == NULL) {
7955 			ill_refrele(attach_ill);
7956 			goto icmp_err_ret;
7957 		}
7958 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
7959 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
7960 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
7961 		    MATCH_IRE_SECATTR, ipst);
7962 		ipif_refrele(attach_ipif);
7963 	}
7964 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
7965 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
7966 
7967 	/*
7968 	 * This loop is run only once in most cases.
7969 	 * We loop to resolve further routes only when the destination
7970 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7971 	 */
7972 	do {
7973 		/* Clear the previous iteration's values */
7974 		if (src_ipif != NULL) {
7975 			ipif_refrele(src_ipif);
7976 			src_ipif = NULL;
7977 		}
7978 		if (dst_ill != NULL) {
7979 			ill_refrele(dst_ill);
7980 			dst_ill = NULL;
7981 		}
7982 
7983 		multirt_resolve_next = B_FALSE;
7984 		/*
7985 		 * We check if packets have to be multirouted.
7986 		 * In this case, given the current <ire, sire> couple,
7987 		 * we look for the next suitable <ire, sire>.
7988 		 * This check is done in ire_multirt_lookup(),
7989 		 * which applies various criteria to find the next route
7990 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
7991 		 * unchanged if it detects it has not been tried yet.
7992 		 */
7993 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7994 			ip3dbg(("ip_newroute: starting next_resolution "
7995 			    "with first_mp %p, tag %d\n",
7996 			    (void *)first_mp,
7997 			    MULTIRT_DEBUG_TAGGED(first_mp)));
7998 
7999 			ASSERT(sire != NULL);
8000 			multirt_is_resolvable =
8001 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
8002 			    MBLK_GETLABEL(mp), ipst);
8003 
8004 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
8005 			    "ire %p, sire %p\n",
8006 			    multirt_is_resolvable,
8007 			    (void *)ire, (void *)sire));
8008 
8009 			if (!multirt_is_resolvable) {
8010 				/*
8011 				 * No more multirt route to resolve; give up
8012 				 * (all routes resolved or no more
8013 				 * resolvable routes).
8014 				 */
8015 				if (ire != NULL) {
8016 					ire_refrele(ire);
8017 					ire = NULL;
8018 				}
8019 			} else {
8020 				ASSERT(sire != NULL);
8021 				ASSERT(ire != NULL);
8022 				/*
8023 				 * We simply use first_sire as a flag that
8024 				 * indicates if a resolvable multirt route
8025 				 * has already been found.
8026 				 * If it is not the case, we may have to send
8027 				 * an ICMP error to report that the
8028 				 * destination is unreachable.
8029 				 * We do not IRE_REFHOLD first_sire.
8030 				 */
8031 				if (first_sire == NULL) {
8032 					first_sire = sire;
8033 				}
8034 			}
8035 		}
8036 		if (ire == NULL) {
8037 			if (ip_debug > 3) {
8038 				/* ip2dbg */
8039 				pr_addr_dbg("ip_newroute: "
8040 				    "can't resolve %s\n", AF_INET, &dst);
8041 			}
8042 			ip3dbg(("ip_newroute: "
8043 			    "ire %p, sire %p, first_sire %p\n",
8044 			    (void *)ire, (void *)sire, (void *)first_sire));
8045 
8046 			if (sire != NULL) {
8047 				ire_refrele(sire);
8048 				sire = NULL;
8049 			}
8050 
8051 			if (first_sire != NULL) {
8052 				/*
8053 				 * At least one multirt route has been found
8054 				 * in the same call to ip_newroute();
8055 				 * there is no need to report an ICMP error.
8056 				 * first_sire was not IRE_REFHOLDed.
8057 				 */
8058 				MULTIRT_DEBUG_UNTAG(first_mp);
8059 				freemsg(first_mp);
8060 				return;
8061 			}
8062 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8063 			    RTA_DST, ipst);
8064 			if (attach_ill != NULL)
8065 				ill_refrele(attach_ill);
8066 			goto icmp_err_ret;
8067 		}
8068 
8069 		/*
8070 		 * Verify that the returned IRE does not have either
8071 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8072 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8073 		 */
8074 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8075 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8076 			if (attach_ill != NULL)
8077 				ill_refrele(attach_ill);
8078 			goto icmp_err_ret;
8079 		}
8080 		/*
8081 		 * Increment the ire_ob_pkt_count field for ire if it is an
8082 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8083 		 * increment the same for the parent IRE, sire, if it is some
8084 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, and HOST)
8085 		 */
8086 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8087 			UPDATE_OB_PKT_COUNT(ire);
8088 			ire->ire_last_used_time = lbolt;
8089 		}
8090 
8091 		if (sire != NULL) {
8092 			gw = sire->ire_gateway_addr;
8093 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8094 			    IRE_INTERFACE)) == 0);
8095 			UPDATE_OB_PKT_COUNT(sire);
8096 			sire->ire_last_used_time = lbolt;
8097 		}
8098 		/*
8099 		 * We have a route to reach the destination.
8100 		 *
8101 		 * 1) If the interface is part of ill group, try to get a new
8102 		 *    ill taking load spreading into account.
8103 		 *
8104 		 * 2) After selecting the ill, get a source address that
8105 		 *    might create good inbound load spreading.
8106 		 *    ipif_select_source does this for us.
8107 		 *
8108 		 * If the application specified the ill (ifindex), we still
8109 		 * load spread. Only if the packets needs to go out
8110 		 * specifically on a given ill e.g. binding to
8111 		 * IPIF_NOFAILOVER address, then we don't try to use a
8112 		 * different ill for load spreading.
8113 		 */
8114 		if (attach_ill == NULL) {
8115 			/*
8116 			 * Don't perform outbound load spreading in the
8117 			 * case of an RTF_MULTIRT route, as we actually
8118 			 * typically want to replicate outgoing packets
8119 			 * through particular interfaces.
8120 			 */
8121 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8122 				dst_ill = ire->ire_ipif->ipif_ill;
8123 				/* for uniformity */
8124 				ill_refhold(dst_ill);
8125 			} else {
8126 				/*
8127 				 * If we are here trying to create an IRE_CACHE
8128 				 * for an offlink destination and have the
8129 				 * IRE_CACHE for the next hop and the latter is
8130 				 * using virtual IP source address selection i.e
8131 				 * it's ire->ire_ipif is pointing to a virtual
8132 				 * network interface (vni) then
8133 				 * ip_newroute_get_dst_ll() will return the vni
8134 				 * interface as the dst_ill. Since the vni is
8135 				 * virtual i.e not associated with any physical
8136 				 * interface, it cannot be the dst_ill, hence
8137 				 * in such a case call ip_newroute_get_dst_ll()
8138 				 * with the stq_ill instead of the ire_ipif ILL.
8139 				 * The function returns a refheld ill.
8140 				 */
8141 				if ((ire->ire_type == IRE_CACHE) &&
8142 				    IS_VNI(ire->ire_ipif->ipif_ill))
8143 					dst_ill = ip_newroute_get_dst_ill(
8144 					    ire->ire_stq->q_ptr);
8145 				else
8146 					dst_ill = ip_newroute_get_dst_ill(
8147 					    ire->ire_ipif->ipif_ill);
8148 			}
8149 			if (dst_ill == NULL) {
8150 				if (ip_debug > 2) {
8151 					pr_addr_dbg("ip_newroute: "
8152 					    "no dst ill for dst"
8153 					    " %s\n", AF_INET, &dst);
8154 				}
8155 				goto icmp_err_ret;
8156 			}
8157 		} else {
8158 			dst_ill = ire->ire_ipif->ipif_ill;
8159 			/* for uniformity */
8160 			ill_refhold(dst_ill);
8161 			/*
8162 			 * We should have found a route matching ill as we
8163 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
8164 			 * Rather than asserting, when there is a mismatch,
8165 			 * we just drop the packet.
8166 			 */
8167 			if (dst_ill != attach_ill) {
8168 				ip0dbg(("ip_newroute: Packet dropped as "
8169 				    "IPIF_NOFAILOVER ill is %s, "
8170 				    "ire->ire_ipif->ipif_ill is %s\n",
8171 				    attach_ill->ill_name,
8172 				    dst_ill->ill_name));
8173 				ill_refrele(attach_ill);
8174 				goto icmp_err_ret;
8175 			}
8176 		}
8177 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
8178 		if (attach_ill != NULL) {
8179 			ill_refrele(attach_ill);
8180 			attach_ill = NULL;
8181 			do_attach_ill = B_TRUE;
8182 		}
8183 		ASSERT(dst_ill != NULL);
8184 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8185 
8186 		/*
8187 		 * Pick the best source address from dst_ill.
8188 		 *
8189 		 * 1) If it is part of a multipathing group, we would
8190 		 *    like to spread the inbound packets across different
8191 		 *    interfaces. ipif_select_source picks a random source
8192 		 *    across the different ills in the group.
8193 		 *
8194 		 * 2) If it is not part of a multipathing group, we try
8195 		 *    to pick the source address from the destination
8196 		 *    route. Clustering assumes that when we have multiple
8197 		 *    prefixes hosted on an interface, the prefix of the
8198 		 *    source address matches the prefix of the destination
8199 		 *    route. We do this only if the address is not
8200 		 *    DEPRECATED.
8201 		 *
8202 		 * 3) If the conn is in a different zone than the ire, we
8203 		 *    need to pick a source address from the right zone.
8204 		 *
8205 		 * NOTE : If we hit case (1) above, the prefix of the source
8206 		 *	  address picked may not match the prefix of the
8207 		 *	  destination routes prefix as ipif_select_source
8208 		 *	  does not look at "dst" while picking a source
8209 		 *	  address.
8210 		 *	  If we want the same behavior as (2), we will need
8211 		 *	  to change the behavior of ipif_select_source.
8212 		 */
8213 		ASSERT(src_ipif == NULL);
8214 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8215 			/*
8216 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8217 			 * Check that the ipif matching the requested source
8218 			 * address still exists.
8219 			 */
8220 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8221 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8222 		}
8223 
8224 		unspec_src = (connp != NULL && connp->conn_unspec_src);
8225 
8226 		if (src_ipif == NULL &&
8227 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
8228 			ire_marks |= IRE_MARK_USESRC_CHECK;
8229 			if ((dst_ill->ill_group != NULL) ||
8230 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8231 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8232 			    ire->ire_zoneid != ALL_ZONES) ||
8233 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8234 				/*
8235 				 * If the destination is reachable via a
8236 				 * given gateway, the selected source address
8237 				 * should be in the same subnet as the gateway.
8238 				 * Otherwise, the destination is not reachable.
8239 				 *
8240 				 * If there are no interfaces on the same subnet
8241 				 * as the destination, ipif_select_source gives
8242 				 * first non-deprecated interface which might be
8243 				 * on a different subnet than the gateway.
8244 				 * This is not desirable. Hence pass the dst_ire
8245 				 * source address to ipif_select_source.
8246 				 * It is sure that the destination is reachable
8247 				 * with the dst_ire source address subnet.
8248 				 * So passing dst_ire source address to
8249 				 * ipif_select_source will make sure that the
8250 				 * selected source will be on the same subnet
8251 				 * as dst_ire source address.
8252 				 */
8253 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8254 				src_ipif = ipif_select_source(dst_ill, saddr,
8255 				    zoneid);
8256 				if (src_ipif == NULL) {
8257 					if (ip_debug > 2) {
8258 						pr_addr_dbg("ip_newroute: "
8259 						    "no src for dst %s ",
8260 						    AF_INET, &dst);
8261 						printf("through interface %s\n",
8262 						    dst_ill->ill_name);
8263 					}
8264 					goto icmp_err_ret;
8265 				}
8266 			} else {
8267 				src_ipif = ire->ire_ipif;
8268 				ASSERT(src_ipif != NULL);
8269 				/* hold src_ipif for uniformity */
8270 				ipif_refhold(src_ipif);
8271 			}
8272 		}
8273 
8274 		/*
8275 		 * Assign a source address while we have the conn.
8276 		 * We can't have ip_wput_ire pick a source address when the
8277 		 * packet returns from arp since we need to look at
8278 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8279 		 * going through arp.
8280 		 *
8281 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8282 		 *	  it uses ip6i to store this information.
8283 		 */
8284 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
8285 			ipha->ipha_src = src_ipif->ipif_src_addr;
8286 
8287 		if (ip_debug > 3) {
8288 			/* ip2dbg */
8289 			pr_addr_dbg("ip_newroute: first hop %s\n",
8290 			    AF_INET, &gw);
8291 		}
8292 		ip2dbg(("\tire type %s (%d)\n",
8293 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8294 
8295 		/*
8296 		 * The TTL of multirouted packets is bounded by the
8297 		 * ip_multirt_ttl ndd variable.
8298 		 */
8299 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8300 			/* Force TTL of multirouted packets */
8301 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8302 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8303 				ip2dbg(("ip_newroute: forcing multirt TTL "
8304 				    "to %d (was %d), dst 0x%08x\n",
8305 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8306 				    ntohl(sire->ire_addr)));
8307 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8308 			}
8309 		}
8310 		/*
8311 		 * At this point in ip_newroute(), ire is either the
8312 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8313 		 * destination or an IRE_INTERFACE type that should be used
8314 		 * to resolve an on-subnet destination or an on-subnet
8315 		 * next-hop gateway.
8316 		 *
8317 		 * In the IRE_CACHE case, we have the following :
8318 		 *
8319 		 * 1) src_ipif - used for getting a source address.
8320 		 *
8321 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8322 		 *    means packets using this IRE_CACHE will go out on
8323 		 *    dst_ill.
8324 		 *
8325 		 * 3) The IRE sire will point to the prefix that is the
8326 		 *    longest  matching route for the destination. These
8327 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8328 		 *
8329 		 *    The newly created IRE_CACHE entry for the off-subnet
8330 		 *    destination is tied to both the prefix route and the
8331 		 *    interface route used to resolve the next-hop gateway
8332 		 *    via the ire_phandle and ire_ihandle fields,
8333 		 *    respectively.
8334 		 *
8335 		 * In the IRE_INTERFACE case, we have the following :
8336 		 *
8337 		 * 1) src_ipif - used for getting a source address.
8338 		 *
8339 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8340 		 *    means packets using the IRE_CACHE that we will build
8341 		 *    here will go out on dst_ill.
8342 		 *
8343 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8344 		 *    to be created will only be tied to the IRE_INTERFACE
8345 		 *    that was derived from the ire_ihandle field.
8346 		 *
8347 		 *    If sire is non-NULL, it means the destination is
8348 		 *    off-link and we will first create the IRE_CACHE for the
8349 		 *    gateway. Next time through ip_newroute, we will create
8350 		 *    the IRE_CACHE for the final destination as described
8351 		 *    above.
8352 		 *
8353 		 * In both cases, after the current resolution has been
8354 		 * completed (or possibly initialised, in the IRE_INTERFACE
8355 		 * case), the loop may be re-entered to attempt the resolution
8356 		 * of another RTF_MULTIRT route.
8357 		 *
8358 		 * When an IRE_CACHE entry for the off-subnet destination is
8359 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8360 		 * for further processing in emission loops.
8361 		 */
8362 		save_ire = ire;
8363 		switch (ire->ire_type) {
8364 		case IRE_CACHE: {
8365 			ire_t	*ipif_ire;
8366 
8367 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8368 			if (gw == 0)
8369 				gw = ire->ire_gateway_addr;
8370 			/*
8371 			 * We need 3 ire's to create a new cache ire for an
8372 			 * off-link destination from the cache ire of the
8373 			 * gateway.
8374 			 *
8375 			 *	1. The prefix ire 'sire' (Note that this does
8376 			 *	   not apply to the conn_nexthop_set case)
8377 			 *	2. The cache ire of the gateway 'ire'
8378 			 *	3. The interface ire 'ipif_ire'
8379 			 *
8380 			 * We have (1) and (2). We lookup (3) below.
8381 			 *
8382 			 * If there is no interface route to the gateway,
8383 			 * it is a race condition, where we found the cache
8384 			 * but the interface route has been deleted.
8385 			 */
8386 			if (ip_nexthop) {
8387 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8388 			} else {
8389 				ipif_ire =
8390 				    ire_ihandle_lookup_offlink(ire, sire);
8391 			}
8392 			if (ipif_ire == NULL) {
8393 				ip1dbg(("ip_newroute: "
8394 				    "ire_ihandle_lookup_offlink failed\n"));
8395 				goto icmp_err_ret;
8396 			}
8397 
8398 			/*
8399 			 * Check cached gateway IRE for any security
8400 			 * attributes; if found, associate the gateway
8401 			 * credentials group to the destination IRE.
8402 			 */
8403 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8404 				mutex_enter(&attrp->igsa_lock);
8405 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8406 					GCGRP_REFHOLD(gcgrp);
8407 				mutex_exit(&attrp->igsa_lock);
8408 			}
8409 
8410 			/*
8411 			 * XXX For the source of the resolver mp,
8412 			 * we are using the same DL_UNITDATA_REQ
8413 			 * (from save_ire->ire_nce->nce_res_mp)
8414 			 * though the save_ire is not pointing at the same ill.
8415 			 * This is incorrect. We need to send it up to the
8416 			 * resolver to get the right res_mp. For ethernets
8417 			 * this may be okay (ill_type == DL_ETHER).
8418 			 */
8419 
8420 			ire = ire_create(
8421 			    (uchar_t *)&dst,		/* dest address */
8422 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8423 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8424 			    (uchar_t *)&gw,		/* gateway address */
8425 			    &save_ire->ire_max_frag,
8426 			    save_ire->ire_nce,		/* src nce */
8427 			    dst_ill->ill_rq,		/* recv-from queue */
8428 			    dst_ill->ill_wq,		/* send-to queue */
8429 			    IRE_CACHE,			/* IRE type */
8430 			    src_ipif,
8431 			    (sire != NULL) ?
8432 			    sire->ire_mask : 0, 	/* Parent mask */
8433 			    (sire != NULL) ?
8434 			    sire->ire_phandle : 0,	/* Parent handle */
8435 			    ipif_ire->ire_ihandle,	/* Interface handle */
8436 			    (sire != NULL) ? (sire->ire_flags &
8437 			    (RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8438 			    (sire != NULL) ?
8439 			    &(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8440 			    NULL,
8441 			    gcgrp,
8442 			    ipst);
8443 
8444 			if (ire == NULL) {
8445 				if (gcgrp != NULL) {
8446 					GCGRP_REFRELE(gcgrp);
8447 					gcgrp = NULL;
8448 				}
8449 				ire_refrele(ipif_ire);
8450 				ire_refrele(save_ire);
8451 				break;
8452 			}
8453 
8454 			/* reference now held by IRE */
8455 			gcgrp = NULL;
8456 
8457 			ire->ire_marks |= ire_marks;
8458 
8459 			/*
8460 			 * Prevent sire and ipif_ire from getting deleted.
8461 			 * The newly created ire is tied to both of them via
8462 			 * the phandle and ihandle respectively.
8463 			 */
8464 			if (sire != NULL) {
8465 				IRB_REFHOLD(sire->ire_bucket);
8466 				/* Has it been removed already ? */
8467 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8468 					IRB_REFRELE(sire->ire_bucket);
8469 					ire_refrele(ipif_ire);
8470 					ire_refrele(save_ire);
8471 					break;
8472 				}
8473 			}
8474 
8475 			IRB_REFHOLD(ipif_ire->ire_bucket);
8476 			/* Has it been removed already ? */
8477 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8478 				IRB_REFRELE(ipif_ire->ire_bucket);
8479 				if (sire != NULL)
8480 					IRB_REFRELE(sire->ire_bucket);
8481 				ire_refrele(ipif_ire);
8482 				ire_refrele(save_ire);
8483 				break;
8484 			}
8485 
8486 			xmit_mp = first_mp;
8487 			/*
8488 			 * In the case of multirouting, a copy
8489 			 * of the packet is done before its sending.
8490 			 * The copy is used to attempt another
8491 			 * route resolution, in a next loop.
8492 			 */
8493 			if (ire->ire_flags & RTF_MULTIRT) {
8494 				copy_mp = copymsg(first_mp);
8495 				if (copy_mp != NULL) {
8496 					xmit_mp = copy_mp;
8497 					MULTIRT_DEBUG_TAG(first_mp);
8498 				}
8499 			}
8500 			ire_add_then_send(q, ire, xmit_mp);
8501 			ire_refrele(save_ire);
8502 
8503 			/* Assert that sire is not deleted yet. */
8504 			if (sire != NULL) {
8505 				ASSERT(sire->ire_ptpn != NULL);
8506 				IRB_REFRELE(sire->ire_bucket);
8507 			}
8508 
8509 			/* Assert that ipif_ire is not deleted yet. */
8510 			ASSERT(ipif_ire->ire_ptpn != NULL);
8511 			IRB_REFRELE(ipif_ire->ire_bucket);
8512 			ire_refrele(ipif_ire);
8513 
8514 			/*
8515 			 * If copy_mp is not NULL, multirouting was
8516 			 * requested. We loop to initiate a next
8517 			 * route resolution attempt, starting from sire.
8518 			 */
8519 			if (copy_mp != NULL) {
8520 				/*
8521 				 * Search for the next unresolved
8522 				 * multirt route.
8523 				 */
8524 				copy_mp = NULL;
8525 				ipif_ire = NULL;
8526 				ire = NULL;
8527 				multirt_resolve_next = B_TRUE;
8528 				continue;
8529 			}
8530 			if (sire != NULL)
8531 				ire_refrele(sire);
8532 			ipif_refrele(src_ipif);
8533 			ill_refrele(dst_ill);
8534 			return;
8535 		}
8536 		case IRE_IF_NORESOLVER: {
8537 
8538 			if (dst_ill->ill_phys_addr_length != IP_ADDR_LEN &&
8539 			    dst_ill->ill_resolver_mp == NULL) {
8540 				ip1dbg(("ip_newroute: dst_ill %p "
8541 				    "for IRE_IF_NORESOLVER ire %p has "
8542 				    "no ill_resolver_mp\n",
8543 				    (void *)dst_ill, (void *)ire));
8544 				break;
8545 			}
8546 
8547 			/*
8548 			 * TSol note: We are creating the ire cache for the
8549 			 * destination 'dst'. If 'dst' is offlink, going
8550 			 * through the first hop 'gw', the security attributes
8551 			 * of 'dst' must be set to point to the gateway
8552 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8553 			 * is possible that 'dst' is a potential gateway that is
8554 			 * referenced by some route that has some security
8555 			 * attributes. Thus in the former case, we need to do a
8556 			 * gcgrp_lookup of 'gw' while in the latter case we
8557 			 * need to do gcgrp_lookup of 'dst' itself.
8558 			 */
8559 			ga.ga_af = AF_INET;
8560 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8561 			    &ga.ga_addr);
8562 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8563 
8564 			ire = ire_create(
8565 			    (uchar_t *)&dst,		/* dest address */
8566 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8567 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8568 			    (uchar_t *)&gw,		/* gateway address */
8569 			    &save_ire->ire_max_frag,
8570 			    NULL,			/* no src nce */
8571 			    dst_ill->ill_rq,		/* recv-from queue */
8572 			    dst_ill->ill_wq,		/* send-to queue */
8573 			    IRE_CACHE,
8574 			    src_ipif,
8575 			    save_ire->ire_mask,		/* Parent mask */
8576 			    (sire != NULL) ?		/* Parent handle */
8577 			    sire->ire_phandle : 0,
8578 			    save_ire->ire_ihandle,	/* Interface handle */
8579 			    (sire != NULL) ? sire->ire_flags &
8580 			    (RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8581 			    &(save_ire->ire_uinfo),
8582 			    NULL,
8583 			    gcgrp,
8584 			    ipst);
8585 
8586 			if (ire == NULL) {
8587 				if (gcgrp != NULL) {
8588 					GCGRP_REFRELE(gcgrp);
8589 					gcgrp = NULL;
8590 				}
8591 				ire_refrele(save_ire);
8592 				break;
8593 			}
8594 
8595 			/* reference now held by IRE */
8596 			gcgrp = NULL;
8597 
8598 			ire->ire_marks |= ire_marks;
8599 
8600 			/* Prevent save_ire from getting deleted */
8601 			IRB_REFHOLD(save_ire->ire_bucket);
8602 			/* Has it been removed already ? */
8603 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8604 				IRB_REFRELE(save_ire->ire_bucket);
8605 				ire_refrele(save_ire);
8606 				break;
8607 			}
8608 
8609 			/*
8610 			 * In the case of multirouting, a copy
8611 			 * of the packet is made before it is sent.
8612 			 * The copy is used in the next
8613 			 * loop to attempt another resolution.
8614 			 */
8615 			xmit_mp = first_mp;
8616 			if ((sire != NULL) &&
8617 			    (sire->ire_flags & RTF_MULTIRT)) {
8618 				copy_mp = copymsg(first_mp);
8619 				if (copy_mp != NULL) {
8620 					xmit_mp = copy_mp;
8621 					MULTIRT_DEBUG_TAG(first_mp);
8622 				}
8623 			}
8624 			ire_add_then_send(q, ire, xmit_mp);
8625 
8626 			/* Assert that it is not deleted yet. */
8627 			ASSERT(save_ire->ire_ptpn != NULL);
8628 			IRB_REFRELE(save_ire->ire_bucket);
8629 			ire_refrele(save_ire);
8630 
8631 			if (copy_mp != NULL) {
8632 				/*
8633 				 * If we found a (no)resolver, we ignore any
8634 				 * trailing top priority IRE_CACHE in further
8635 				 * loops. This ensures that we do not omit any
8636 				 * (no)resolver.
8637 				 * This IRE_CACHE, if any, will be processed
8638 				 * by another thread entering ip_newroute().
8639 				 * IRE_CACHE entries, if any, will be processed
8640 				 * by another thread entering ip_newroute(),
8641 				 * (upon resolver response, for instance).
8642 				 * This aims to force parallel multirt
8643 				 * resolutions as soon as a packet must be sent.
8644 				 * In the best case, after the tx of only one
8645 				 * packet, all reachable routes are resolved.
8646 				 * Otherwise, the resolution of all RTF_MULTIRT
8647 				 * routes would require several emissions.
8648 				 */
8649 				multirt_flags &= ~MULTIRT_CACHEGW;
8650 
8651 				/*
8652 				 * Search for the next unresolved multirt
8653 				 * route.
8654 				 */
8655 				copy_mp = NULL;
8656 				save_ire = NULL;
8657 				ire = NULL;
8658 				multirt_resolve_next = B_TRUE;
8659 				continue;
8660 			}
8661 
8662 			/*
8663 			 * Don't need sire anymore
8664 			 */
8665 			if (sire != NULL)
8666 				ire_refrele(sire);
8667 
8668 			ipif_refrele(src_ipif);
8669 			ill_refrele(dst_ill);
8670 			return;
8671 		}
8672 		case IRE_IF_RESOLVER:
8673 			/*
8674 			 * We can't build an IRE_CACHE yet, but at least we
8675 			 * found a resolver that can help.
8676 			 */
8677 			res_mp = dst_ill->ill_resolver_mp;
8678 			if (!OK_RESOLVER_MP(res_mp))
8679 				break;
8680 
8681 			/*
8682 			 * To be at this point in the code with a non-zero gw
8683 			 * means that dst is reachable through a gateway that
8684 			 * we have never resolved.  By changing dst to the gw
8685 			 * addr we resolve the gateway first.
8686 			 * When ire_add_then_send() tries to put the IP dg
8687 			 * to dst, it will reenter ip_newroute() at which
8688 			 * time we will find the IRE_CACHE for the gw and
8689 			 * create another IRE_CACHE in case IRE_CACHE above.
8690 			 */
8691 			if (gw != INADDR_ANY) {
8692 				/*
8693 				 * The source ipif that was determined above was
8694 				 * relative to the destination address, not the
8695 				 * gateway's. If src_ipif was not taken out of
8696 				 * the IRE_IF_RESOLVER entry, we'll need to call
8697 				 * ipif_select_source() again.
8698 				 */
8699 				if (src_ipif != ire->ire_ipif) {
8700 					ipif_refrele(src_ipif);
8701 					src_ipif = ipif_select_source(dst_ill,
8702 					    gw, zoneid);
8703 					if (src_ipif == NULL) {
8704 						if (ip_debug > 2) {
8705 							pr_addr_dbg(
8706 							    "ip_newroute: no "
8707 							    "src for gw %s ",
8708 							    AF_INET, &gw);
8709 							printf("through "
8710 							    "interface %s\n",
8711 							    dst_ill->ill_name);
8712 						}
8713 						goto icmp_err_ret;
8714 					}
8715 				}
8716 				save_dst = dst;
8717 				dst = gw;
8718 				gw = INADDR_ANY;
8719 			}
8720 
8721 			/*
8722 			 * We obtain a partial IRE_CACHE which we will pass
8723 			 * along with the resolver query.  When the response
8724 			 * comes back it will be there ready for us to add.
8725 			 * The ire_max_frag is atomically set under the
8726 			 * irebucket lock in ire_add_v[46].
8727 			 */
8728 
8729 			ire = ire_create_mp(
8730 			    (uchar_t *)&dst,		/* dest address */
8731 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8732 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8733 			    (uchar_t *)&gw,		/* gateway address */
8734 			    NULL,			/* ire_max_frag */
8735 			    NULL,			/* no src nce */
8736 			    dst_ill->ill_rq,		/* recv-from queue */
8737 			    dst_ill->ill_wq,		/* send-to queue */
8738 			    IRE_CACHE,
8739 			    src_ipif,			/* Interface ipif */
8740 			    save_ire->ire_mask,		/* Parent mask */
8741 			    0,
8742 			    save_ire->ire_ihandle,	/* Interface handle */
8743 			    0,				/* flags if any */
8744 			    &(save_ire->ire_uinfo),
8745 			    NULL,
8746 			    NULL,
8747 			    ipst);
8748 
8749 			if (ire == NULL) {
8750 				ire_refrele(save_ire);
8751 				break;
8752 			}
8753 
8754 			if ((sire != NULL) &&
8755 			    (sire->ire_flags & RTF_MULTIRT)) {
8756 				copy_mp = copymsg(first_mp);
8757 				if (copy_mp != NULL)
8758 					MULTIRT_DEBUG_TAG(copy_mp);
8759 			}
8760 
8761 			ire->ire_marks |= ire_marks;
8762 
8763 			/*
8764 			 * Construct message chain for the resolver
8765 			 * of the form:
8766 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8767 			 * Packet could contain a IPSEC_OUT mp.
8768 			 *
8769 			 * NOTE : ire will be added later when the response
8770 			 * comes back from ARP. If the response does not
8771 			 * come back, ARP frees the packet. For this reason,
8772 			 * we can't REFHOLD the bucket of save_ire to prevent
8773 			 * deletions. We may not be able to REFRELE the bucket
8774 			 * if the response never comes back. Thus, before
8775 			 * adding the ire, ire_add_v4 will make sure that the
8776 			 * interface route does not get deleted. This is the
8777 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8778 			 * where we can always prevent deletions because of
8779 			 * the synchronous nature of adding IRES i.e
8780 			 * ire_add_then_send is called after creating the IRE.
8781 			 */
8782 			ASSERT(ire->ire_mp != NULL);
8783 			ire->ire_mp->b_cont = first_mp;
8784 			/* Have saved_mp handy, for cleanup if canput fails */
8785 			saved_mp = mp;
8786 			mp = copyb(res_mp);
8787 			if (mp == NULL) {
8788 				/* Prepare for cleanup */
8789 				mp = saved_mp; /* pkt */
8790 				ire_delete(ire); /* ire_mp */
8791 				ire = NULL;
8792 				ire_refrele(save_ire);
8793 				if (copy_mp != NULL) {
8794 					MULTIRT_DEBUG_UNTAG(copy_mp);
8795 					freemsg(copy_mp);
8796 					copy_mp = NULL;
8797 				}
8798 				break;
8799 			}
8800 			linkb(mp, ire->ire_mp);
8801 
8802 			/*
8803 			 * Fill in the source and dest addrs for the resolver.
8804 			 * NOTE: this depends on memory layouts imposed by
8805 			 * ill_init().
8806 			 */
8807 			areq = (areq_t *)mp->b_rptr;
8808 			addrp = (ipaddr_t *)((char *)areq +
8809 			    areq->areq_sender_addr_offset);
8810 			if (do_attach_ill) {
8811 				/*
8812 				 * This is bind to no failover case.
8813 				 * arp packet also must go out on attach_ill.
8814 				 */
8815 				ASSERT(ipha->ipha_src != NULL);
8816 				*addrp = ipha->ipha_src;
8817 			} else {
8818 				*addrp = save_ire->ire_src_addr;
8819 			}
8820 
8821 			ire_refrele(save_ire);
8822 			addrp = (ipaddr_t *)((char *)areq +
8823 			    areq->areq_target_addr_offset);
8824 			*addrp = dst;
8825 			/* Up to the resolver. */
8826 			if (canputnext(dst_ill->ill_rq) &&
8827 			    !(dst_ill->ill_arp_closing)) {
8828 				putnext(dst_ill->ill_rq, mp);
8829 				ire = NULL;
8830 				if (copy_mp != NULL) {
8831 					/*
8832 					 * If we found a resolver, we ignore
8833 					 * any trailing top priority IRE_CACHE
8834 					 * in the further loops. This ensures
8835 					 * that we do not omit any resolver.
8836 					 * IRE_CACHE entries, if any, will be
8837 					 * processed next time we enter
8838 					 * ip_newroute().
8839 					 */
8840 					multirt_flags &= ~MULTIRT_CACHEGW;
8841 					/*
8842 					 * Search for the next unresolved
8843 					 * multirt route.
8844 					 */
8845 					first_mp = copy_mp;
8846 					copy_mp = NULL;
8847 					/* Prepare the next resolution loop. */
8848 					mp = first_mp;
8849 					EXTRACT_PKT_MP(mp, first_mp,
8850 					    mctl_present);
8851 					if (mctl_present)
8852 						io = (ipsec_out_t *)
8853 						    first_mp->b_rptr;
8854 					ipha = (ipha_t *)mp->b_rptr;
8855 
8856 					ASSERT(sire != NULL);
8857 
8858 					dst = save_dst;
8859 					multirt_resolve_next = B_TRUE;
8860 					continue;
8861 				}
8862 
8863 				if (sire != NULL)
8864 					ire_refrele(sire);
8865 
8866 				/*
8867 				 * The response will come back in ip_wput
8868 				 * with db_type IRE_DB_TYPE.
8869 				 */
8870 				ipif_refrele(src_ipif);
8871 				ill_refrele(dst_ill);
8872 				return;
8873 			} else {
8874 				/* Prepare for cleanup */
8875 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8876 				    mp);
8877 				mp->b_cont = NULL;
8878 				freeb(mp); /* areq */
8879 				/*
8880 				 * this is an ire that is not added to the
8881 				 * cache. ire_freemblk will handle the release
8882 				 * of any resources associated with the ire.
8883 				 */
8884 				ire_delete(ire); /* ire_mp */
8885 				mp = saved_mp; /* pkt */
8886 				ire = NULL;
8887 				if (copy_mp != NULL) {
8888 					MULTIRT_DEBUG_UNTAG(copy_mp);
8889 					freemsg(copy_mp);
8890 					copy_mp = NULL;
8891 				}
8892 				break;
8893 			}
8894 		default:
8895 			break;
8896 		}
8897 	} while (multirt_resolve_next);
8898 
8899 	ip1dbg(("ip_newroute: dropped\n"));
8900 	/* Did this packet originate externally? */
8901 	if (mp->b_prev) {
8902 		mp->b_next = NULL;
8903 		mp->b_prev = NULL;
8904 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
8905 	} else {
8906 		if (dst_ill != NULL) {
8907 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
8908 		} else {
8909 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
8910 		}
8911 	}
8912 	ASSERT(copy_mp == NULL);
8913 	MULTIRT_DEBUG_UNTAG(first_mp);
8914 	freemsg(first_mp);
8915 	if (ire != NULL)
8916 		ire_refrele(ire);
8917 	if (sire != NULL)
8918 		ire_refrele(sire);
8919 	if (src_ipif != NULL)
8920 		ipif_refrele(src_ipif);
8921 	if (dst_ill != NULL)
8922 		ill_refrele(dst_ill);
8923 	return;
8924 
8925 icmp_err_ret:
8926 	ip1dbg(("ip_newroute: no route\n"));
8927 	if (src_ipif != NULL)
8928 		ipif_refrele(src_ipif);
8929 	if (dst_ill != NULL)
8930 		ill_refrele(dst_ill);
8931 	if (sire != NULL)
8932 		ire_refrele(sire);
8933 	/* Did this packet originate externally? */
8934 	if (mp->b_prev) {
8935 		mp->b_next = NULL;
8936 		mp->b_prev = NULL;
8937 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
8938 		q = WR(q);
8939 	} else {
8940 		/*
8941 		 * There is no outgoing ill, so just increment the
8942 		 * system MIB.
8943 		 */
8944 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
8945 		/*
8946 		 * Since ip_wput() isn't close to finished, we fill
8947 		 * in enough of the header for credible error reporting.
8948 		 */
8949 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
8950 			/* Failed */
8951 			MULTIRT_DEBUG_UNTAG(first_mp);
8952 			freemsg(first_mp);
8953 			if (ire != NULL)
8954 				ire_refrele(ire);
8955 			return;
8956 		}
8957 	}
8958 
8959 	/*
8960 	 * At this point we will have ire only if RTF_BLACKHOLE
8961 	 * or RTF_REJECT flags are set on the IRE. It will not
8962 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8963 	 */
8964 	if (ire != NULL) {
8965 		if (ire->ire_flags & RTF_BLACKHOLE) {
8966 			ire_refrele(ire);
8967 			MULTIRT_DEBUG_UNTAG(first_mp);
8968 			freemsg(first_mp);
8969 			return;
8970 		}
8971 		ire_refrele(ire);
8972 	}
8973 	if (ip_source_routed(ipha, ipst)) {
8974 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
8975 		    zoneid, ipst);
8976 		return;
8977 	}
8978 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
8979 }
8980 
8981 ip_opt_info_t zero_info;
8982 
8983 /*
8984  * IPv4 -
8985  * ip_newroute_ipif is called by ip_wput_multicast and
8986  * ip_rput_forward_multicast whenever we need to send
8987  * out a packet to a destination address for which we do not have specific
8988  * routing information. It is used when the packet will be sent out
8989  * on a specific interface. It is also called by ip_wput() when IP_BOUND_IF
8990  * socket option is set or icmp error message wants to go out on a particular
8991  * interface for a unicast packet.
8992  *
8993  * In most cases, the destination address is resolved thanks to the ipif
8994  * intrinsic resolver. However, there are some cases where the call to
8995  * ip_newroute_ipif must take into account the potential presence of
8996  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
8997  * that uses the interface. This is specified through flags,
8998  * which can be a combination of:
8999  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
9000  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
9001  *   and flags. Additionally, the packet source address has to be set to
9002  *   the specified address. The caller is thus expected to set this flag
9003  *   if the packet has no specific source address yet.
9004  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
9005  *   flag, the resulting ire will inherit the flag. All unresolved routes
9006  *   to the destination must be explored in the same call to
9007  *   ip_newroute_ipif().
9008  */
9009 static void
9010 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
9011     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
9012 {
9013 	areq_t	*areq;
9014 	ire_t	*ire = NULL;
9015 	mblk_t	*res_mp;
9016 	ipaddr_t *addrp;
9017 	mblk_t *first_mp;
9018 	ire_t	*save_ire = NULL;
9019 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
9020 	ipif_t	*src_ipif = NULL;
9021 	ushort_t ire_marks = 0;
9022 	ill_t	*dst_ill = NULL;
9023 	boolean_t mctl_present;
9024 	ipsec_out_t *io;
9025 	ipha_t *ipha;
9026 	int	ihandle = 0;
9027 	mblk_t	*saved_mp;
9028 	ire_t   *fire = NULL;
9029 	mblk_t  *copy_mp = NULL;
9030 	boolean_t multirt_resolve_next;
9031 	boolean_t unspec_src;
9032 	ipaddr_t ipha_dst;
9033 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
9034 
9035 	/*
9036 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
9037 	 * here for uniformity
9038 	 */
9039 	ipif_refhold(ipif);
9040 
9041 	/*
9042 	 * This loop is run only once in most cases.
9043 	 * We loop to resolve further routes only when the destination
9044 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
9045 	 */
9046 	do {
9047 		if (dst_ill != NULL) {
9048 			ill_refrele(dst_ill);
9049 			dst_ill = NULL;
9050 		}
9051 		if (src_ipif != NULL) {
9052 			ipif_refrele(src_ipif);
9053 			src_ipif = NULL;
9054 		}
9055 		multirt_resolve_next = B_FALSE;
9056 
9057 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9058 		    ipif->ipif_ill->ill_name));
9059 
9060 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
9061 		if (mctl_present)
9062 			io = (ipsec_out_t *)first_mp->b_rptr;
9063 
9064 		ipha = (ipha_t *)mp->b_rptr;
9065 
9066 		/*
9067 		 * Save the packet destination address, we may need it after
9068 		 * the packet has been consumed.
9069 		 */
9070 		ipha_dst = ipha->ipha_dst;
9071 
9072 		/*
9073 		 * If the interface is a pt-pt interface we look for an
9074 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9075 		 * local_address and the pt-pt destination address. Otherwise
9076 		 * we just match the local address.
9077 		 * NOTE: dst could be different than ipha->ipha_dst in case
9078 		 * of sending igmp multicast packets over a point-to-point
9079 		 * connection.
9080 		 * Thus we must be careful enough to check ipha_dst to be a
9081 		 * multicast address, otherwise it will take xmit_if path for
9082 		 * multicast packets resulting into kernel stack overflow by
9083 		 * repeated calls to ip_newroute_ipif from ire_send().
9084 		 */
9085 		if (CLASSD(ipha_dst) &&
9086 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9087 			goto err_ret;
9088 		}
9089 
9090 		/*
9091 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9092 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9093 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9094 		 * propagate its flags to the new ire.
9095 		 */
9096 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9097 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9098 			ip2dbg(("ip_newroute_ipif: "
9099 			    "ipif_lookup_multi_ire("
9100 			    "ipif %p, dst %08x) = fire %p\n",
9101 			    (void *)ipif, ntohl(dst), (void *)fire));
9102 		}
9103 
9104 		if (mctl_present && io->ipsec_out_attach_if) {
9105 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
9106 			    io->ipsec_out_ill_index, B_FALSE, ipst);
9107 
9108 			/* Failure case frees things for us. */
9109 			if (attach_ill == NULL) {
9110 				ipif_refrele(ipif);
9111 				if (fire != NULL)
9112 					ire_refrele(fire);
9113 				return;
9114 			}
9115 
9116 			/*
9117 			 * Check if we need an ire that will not be
9118 			 * looked up by anybody else i.e. HIDDEN.
9119 			 */
9120 			if (ill_is_probeonly(attach_ill)) {
9121 				ire_marks = IRE_MARK_HIDDEN;
9122 			}
9123 			/*
9124 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
9125 			 * case.
9126 			 */
9127 			dst_ill = ipif->ipif_ill;
9128 			/* attach_ill has been refheld by ip_grab_attach_ill */
9129 			ASSERT(dst_ill == attach_ill);
9130 		} else {
9131 			/*
9132 			 * If the interface belongs to an interface group,
9133 			 * make sure the next possible interface in the group
9134 			 * is used.  This encourages load spreading among
9135 			 * peers in an interface group.
9136 			 * Note: load spreading is disabled for RTF_MULTIRT
9137 			 * routes.
9138 			 */
9139 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9140 			    (fire->ire_flags & RTF_MULTIRT)) {
9141 				/*
9142 				 * Don't perform outbound load spreading
9143 				 * in the case of an RTF_MULTIRT issued route,
9144 				 * we actually typically want to replicate
9145 				 * outgoing packets through particular
9146 				 * interfaces.
9147 				 */
9148 				dst_ill = ipif->ipif_ill;
9149 				ill_refhold(dst_ill);
9150 			} else {
9151 				dst_ill = ip_newroute_get_dst_ill(
9152 				    ipif->ipif_ill);
9153 			}
9154 			if (dst_ill == NULL) {
9155 				if (ip_debug > 2) {
9156 					pr_addr_dbg("ip_newroute_ipif: "
9157 					    "no dst ill for dst %s\n",
9158 					    AF_INET, &dst);
9159 				}
9160 				goto err_ret;
9161 			}
9162 		}
9163 
9164 		/*
9165 		 * Pick a source address preferring non-deprecated ones.
9166 		 * Unlike ip_newroute, we don't do any source address
9167 		 * selection here since for multicast it really does not help
9168 		 * in inbound load spreading as in the unicast case.
9169 		 */
9170 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9171 		    (fire->ire_flags & RTF_SETSRC)) {
9172 			/*
9173 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9174 			 * on that interface. This ire has RTF_SETSRC flag, so
9175 			 * the source address of the packet must be changed.
9176 			 * Check that the ipif matching the requested source
9177 			 * address still exists.
9178 			 */
9179 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9180 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9181 		}
9182 
9183 		unspec_src = (connp != NULL && connp->conn_unspec_src);
9184 
9185 		if (((!ipif->ipif_isv6 && ipif->ipif_lcl_addr == INADDR_ANY) ||
9186 		    (ipif->ipif_flags & (IPIF_DEPRECATED|IPIF_UP)) != IPIF_UP ||
9187 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9188 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9189 		    (src_ipif == NULL) &&
9190 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
9191 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9192 			if (src_ipif == NULL) {
9193 				if (ip_debug > 2) {
9194 					/* ip1dbg */
9195 					pr_addr_dbg("ip_newroute_ipif: "
9196 					    "no src for dst %s",
9197 					    AF_INET, &dst);
9198 				}
9199 				ip1dbg((" through interface %s\n",
9200 				    dst_ill->ill_name));
9201 				goto err_ret;
9202 			}
9203 			ipif_refrele(ipif);
9204 			ipif = src_ipif;
9205 			ipif_refhold(ipif);
9206 		}
9207 		if (src_ipif == NULL) {
9208 			src_ipif = ipif;
9209 			ipif_refhold(src_ipif);
9210 		}
9211 
9212 		/*
9213 		 * Assign a source address while we have the conn.
9214 		 * We can't have ip_wput_ire pick a source address when the
9215 		 * packet returns from arp since conn_unspec_src might be set
9216 		 * and we lose the conn when going through arp.
9217 		 */
9218 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
9219 			ipha->ipha_src = src_ipif->ipif_src_addr;
9220 
9221 		/*
9222 		 * In the case of IP_BOUND_IF and IP_PKTINFO, it is possible
9223 		 * that the outgoing interface does not have an interface ire.
9224 		 */
9225 		if (CLASSD(ipha_dst) && (connp == NULL ||
9226 		    connp->conn_outgoing_ill == NULL) &&
9227 		    infop->ip_opt_ill_index == 0) {
9228 			/* ipif_to_ire returns an held ire */
9229 			ire = ipif_to_ire(ipif);
9230 			if (ire == NULL)
9231 				goto err_ret;
9232 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9233 				goto err_ret;
9234 			/*
9235 			 * ihandle is needed when the ire is added to
9236 			 * cache table.
9237 			 */
9238 			save_ire = ire;
9239 			ihandle = save_ire->ire_ihandle;
9240 
9241 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9242 			    "flags %04x\n",
9243 			    (void *)ire, (void *)ipif, flags));
9244 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9245 			    (fire->ire_flags & RTF_MULTIRT)) {
9246 				/*
9247 				 * As requested by flags, an IRE_OFFSUBNET was
9248 				 * looked up on that interface. This ire has
9249 				 * RTF_MULTIRT flag, so the resolution loop will
9250 				 * be re-entered to resolve additional routes on
9251 				 * other interfaces. For that purpose, a copy of
9252 				 * the packet is performed at this point.
9253 				 */
9254 				fire->ire_last_used_time = lbolt;
9255 				copy_mp = copymsg(first_mp);
9256 				if (copy_mp) {
9257 					MULTIRT_DEBUG_TAG(copy_mp);
9258 				}
9259 			}
9260 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9261 			    (fire->ire_flags & RTF_SETSRC)) {
9262 				/*
9263 				 * As requested by flags, an IRE_OFFSUBET was
9264 				 * looked up on that interface. This ire has
9265 				 * RTF_SETSRC flag, so the source address of the
9266 				 * packet must be changed.
9267 				 */
9268 				ipha->ipha_src = fire->ire_src_addr;
9269 			}
9270 		} else {
9271 			ASSERT((connp == NULL) ||
9272 			    (connp->conn_outgoing_ill != NULL) ||
9273 			    (connp->conn_dontroute) ||
9274 			    infop->ip_opt_ill_index != 0);
9275 			/*
9276 			 * The only ways we can come here are:
9277 			 * 1) IP_BOUND_IF socket option is set
9278 			 * 2) SO_DONTROUTE socket option is set
9279 			 * 3) IP_PKTINFO option is passed in as ancillary data.
9280 			 * In all cases, the new ire will not be added
9281 			 * into cache table.
9282 			 */
9283 			ire_marks |= IRE_MARK_NOADD;
9284 		}
9285 
9286 		switch (ipif->ipif_net_type) {
9287 		case IRE_IF_NORESOLVER: {
9288 			/* We have what we need to build an IRE_CACHE. */
9289 
9290 			if ((dst_ill->ill_phys_addr_length != IP_ADDR_LEN) &&
9291 			    (dst_ill->ill_resolver_mp == NULL)) {
9292 				ip1dbg(("ip_newroute_ipif: dst_ill %p "
9293 				    "for IRE_IF_NORESOLVER ire %p has "
9294 				    "no ill_resolver_mp\n",
9295 				    (void *)dst_ill, (void *)ire));
9296 				break;
9297 			}
9298 
9299 			/*
9300 			 * The new ire inherits the IRE_OFFSUBNET flags
9301 			 * and source address, if this was requested.
9302 			 */
9303 			ire = ire_create(
9304 			    (uchar_t *)&dst,		/* dest address */
9305 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9306 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9307 			    NULL,			/* gateway address */
9308 			    &ipif->ipif_mtu,
9309 			    NULL,			/* no src nce */
9310 			    dst_ill->ill_rq,		/* recv-from queue */
9311 			    dst_ill->ill_wq,		/* send-to queue */
9312 			    IRE_CACHE,
9313 			    src_ipif,
9314 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9315 			    (fire != NULL) ?		/* Parent handle */
9316 			    fire->ire_phandle : 0,
9317 			    ihandle,			/* Interface handle */
9318 			    (fire != NULL) ?
9319 			    (fire->ire_flags &
9320 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9321 			    (save_ire == NULL ? &ire_uinfo_null :
9322 			    &save_ire->ire_uinfo),
9323 			    NULL,
9324 			    NULL,
9325 			    ipst);
9326 
9327 			if (ire == NULL) {
9328 				if (save_ire != NULL)
9329 					ire_refrele(save_ire);
9330 				break;
9331 			}
9332 
9333 			ire->ire_marks |= ire_marks;
9334 
9335 			/*
9336 			 * If IRE_MARK_NOADD is set then we need to convert
9337 			 * the max_fragp to a useable value now. This is
9338 			 * normally done in ire_add_v[46]. We also need to
9339 			 * associate the ire with an nce (normally would be
9340 			 * done in ip_wput_nondata()).
9341 			 *
9342 			 * Note that IRE_MARK_NOADD packets created here
9343 			 * do not have a non-null ire_mp pointer. The null
9344 			 * value of ire_bucket indicates that they were
9345 			 * never added.
9346 			 */
9347 			if (ire->ire_marks & IRE_MARK_NOADD) {
9348 				uint_t  max_frag;
9349 
9350 				max_frag = *ire->ire_max_fragp;
9351 				ire->ire_max_fragp = NULL;
9352 				ire->ire_max_frag = max_frag;
9353 
9354 				if ((ire->ire_nce = ndp_lookup_v4(
9355 				    ire_to_ill(ire),
9356 				    (ire->ire_gateway_addr != INADDR_ANY ?
9357 				    &ire->ire_gateway_addr : &ire->ire_addr),
9358 				    B_FALSE)) == NULL) {
9359 					if (save_ire != NULL)
9360 						ire_refrele(save_ire);
9361 					break;
9362 				}
9363 				ASSERT(ire->ire_nce->nce_state ==
9364 				    ND_REACHABLE);
9365 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9366 			}
9367 
9368 			/* Prevent save_ire from getting deleted */
9369 			if (save_ire != NULL) {
9370 				IRB_REFHOLD(save_ire->ire_bucket);
9371 				/* Has it been removed already ? */
9372 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9373 					IRB_REFRELE(save_ire->ire_bucket);
9374 					ire_refrele(save_ire);
9375 					break;
9376 				}
9377 			}
9378 
9379 			ire_add_then_send(q, ire, first_mp);
9380 
9381 			/* Assert that save_ire is not deleted yet. */
9382 			if (save_ire != NULL) {
9383 				ASSERT(save_ire->ire_ptpn != NULL);
9384 				IRB_REFRELE(save_ire->ire_bucket);
9385 				ire_refrele(save_ire);
9386 				save_ire = NULL;
9387 			}
9388 			if (fire != NULL) {
9389 				ire_refrele(fire);
9390 				fire = NULL;
9391 			}
9392 
9393 			/*
9394 			 * the resolution loop is re-entered if this
9395 			 * was requested through flags and if we
9396 			 * actually are in a multirouting case.
9397 			 */
9398 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9399 				boolean_t need_resolve =
9400 				    ire_multirt_need_resolve(ipha_dst,
9401 				    MBLK_GETLABEL(copy_mp), ipst);
9402 				if (!need_resolve) {
9403 					MULTIRT_DEBUG_UNTAG(copy_mp);
9404 					freemsg(copy_mp);
9405 					copy_mp = NULL;
9406 				} else {
9407 					/*
9408 					 * ipif_lookup_group() calls
9409 					 * ire_lookup_multi() that uses
9410 					 * ire_ftable_lookup() to find
9411 					 * an IRE_INTERFACE for the group.
9412 					 * In the multirt case,
9413 					 * ire_lookup_multi() then invokes
9414 					 * ire_multirt_lookup() to find
9415 					 * the next resolvable ire.
9416 					 * As a result, we obtain an new
9417 					 * interface, derived from the
9418 					 * next ire.
9419 					 */
9420 					ipif_refrele(ipif);
9421 					ipif = ipif_lookup_group(ipha_dst,
9422 					    zoneid, ipst);
9423 					ip2dbg(("ip_newroute_ipif: "
9424 					    "multirt dst %08x, ipif %p\n",
9425 					    htonl(dst), (void *)ipif));
9426 					if (ipif != NULL) {
9427 						mp = copy_mp;
9428 						copy_mp = NULL;
9429 						multirt_resolve_next = B_TRUE;
9430 						continue;
9431 					} else {
9432 						freemsg(copy_mp);
9433 					}
9434 				}
9435 			}
9436 			if (ipif != NULL)
9437 				ipif_refrele(ipif);
9438 			ill_refrele(dst_ill);
9439 			ipif_refrele(src_ipif);
9440 			return;
9441 		}
9442 		case IRE_IF_RESOLVER:
9443 			/*
9444 			 * We can't build an IRE_CACHE yet, but at least
9445 			 * we found a resolver that can help.
9446 			 */
9447 			res_mp = dst_ill->ill_resolver_mp;
9448 			if (!OK_RESOLVER_MP(res_mp))
9449 				break;
9450 
9451 			/*
9452 			 * We obtain a partial IRE_CACHE which we will pass
9453 			 * along with the resolver query.  When the response
9454 			 * comes back it will be there ready for us to add.
9455 			 * The new ire inherits the IRE_OFFSUBNET flags
9456 			 * and source address, if this was requested.
9457 			 * The ire_max_frag is atomically set under the
9458 			 * irebucket lock in ire_add_v[46]. Only in the
9459 			 * case of IRE_MARK_NOADD, we set it here itself.
9460 			 */
9461 			ire = ire_create_mp(
9462 			    (uchar_t *)&dst,		/* dest address */
9463 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9464 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9465 			    NULL,			/* gateway address */
9466 			    (ire_marks & IRE_MARK_NOADD) ?
9467 			    ipif->ipif_mtu : 0,		/* max_frag */
9468 			    NULL,			/* no src nce */
9469 			    dst_ill->ill_rq,		/* recv-from queue */
9470 			    dst_ill->ill_wq,		/* send-to queue */
9471 			    IRE_CACHE,
9472 			    src_ipif,
9473 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9474 			    (fire != NULL) ?		/* Parent handle */
9475 			    fire->ire_phandle : 0,
9476 			    ihandle,			/* Interface handle */
9477 			    (fire != NULL) ?		/* flags if any */
9478 			    (fire->ire_flags &
9479 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9480 			    (save_ire == NULL ? &ire_uinfo_null :
9481 			    &save_ire->ire_uinfo),
9482 			    NULL,
9483 			    NULL,
9484 			    ipst);
9485 
9486 			if (save_ire != NULL) {
9487 				ire_refrele(save_ire);
9488 				save_ire = NULL;
9489 			}
9490 			if (ire == NULL)
9491 				break;
9492 
9493 			ire->ire_marks |= ire_marks;
9494 			/*
9495 			 * Construct message chain for the resolver of the
9496 			 * form:
9497 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9498 			 *
9499 			 * NOTE : ire will be added later when the response
9500 			 * comes back from ARP. If the response does not
9501 			 * come back, ARP frees the packet. For this reason,
9502 			 * we can't REFHOLD the bucket of save_ire to prevent
9503 			 * deletions. We may not be able to REFRELE the
9504 			 * bucket if the response never comes back.
9505 			 * Thus, before adding the ire, ire_add_v4 will make
9506 			 * sure that the interface route does not get deleted.
9507 			 * This is the only case unlike ip_newroute_v6,
9508 			 * ip_newroute_ipif_v6 where we can always prevent
9509 			 * deletions because ire_add_then_send is called after
9510 			 * creating the IRE.
9511 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9512 			 * does not add this IRE into the IRE CACHE.
9513 			 */
9514 			ASSERT(ire->ire_mp != NULL);
9515 			ire->ire_mp->b_cont = first_mp;
9516 			/* Have saved_mp handy, for cleanup if canput fails */
9517 			saved_mp = mp;
9518 			mp = copyb(res_mp);
9519 			if (mp == NULL) {
9520 				/* Prepare for cleanup */
9521 				mp = saved_mp; /* pkt */
9522 				ire_delete(ire); /* ire_mp */
9523 				ire = NULL;
9524 				if (copy_mp != NULL) {
9525 					MULTIRT_DEBUG_UNTAG(copy_mp);
9526 					freemsg(copy_mp);
9527 					copy_mp = NULL;
9528 				}
9529 				break;
9530 			}
9531 			linkb(mp, ire->ire_mp);
9532 
9533 			/*
9534 			 * Fill in the source and dest addrs for the resolver.
9535 			 * NOTE: this depends on memory layouts imposed by
9536 			 * ill_init().
9537 			 */
9538 			areq = (areq_t *)mp->b_rptr;
9539 			addrp = (ipaddr_t *)((char *)areq +
9540 			    areq->areq_sender_addr_offset);
9541 			*addrp = ire->ire_src_addr;
9542 			addrp = (ipaddr_t *)((char *)areq +
9543 			    areq->areq_target_addr_offset);
9544 			*addrp = dst;
9545 			/* Up to the resolver. */
9546 			if (canputnext(dst_ill->ill_rq) &&
9547 			    !(dst_ill->ill_arp_closing)) {
9548 				putnext(dst_ill->ill_rq, mp);
9549 				/*
9550 				 * The response will come back in ip_wput
9551 				 * with db_type IRE_DB_TYPE.
9552 				 */
9553 			} else {
9554 				mp->b_cont = NULL;
9555 				freeb(mp); /* areq */
9556 				ire_delete(ire); /* ire_mp */
9557 				saved_mp->b_next = NULL;
9558 				saved_mp->b_prev = NULL;
9559 				freemsg(first_mp); /* pkt */
9560 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9561 			}
9562 
9563 			if (fire != NULL) {
9564 				ire_refrele(fire);
9565 				fire = NULL;
9566 			}
9567 
9568 
9569 			/*
9570 			 * The resolution loop is re-entered if this was
9571 			 * requested through flags and we actually are
9572 			 * in a multirouting case.
9573 			 */
9574 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9575 				boolean_t need_resolve =
9576 				    ire_multirt_need_resolve(ipha_dst,
9577 				    MBLK_GETLABEL(copy_mp), ipst);
9578 				if (!need_resolve) {
9579 					MULTIRT_DEBUG_UNTAG(copy_mp);
9580 					freemsg(copy_mp);
9581 					copy_mp = NULL;
9582 				} else {
9583 					/*
9584 					 * ipif_lookup_group() calls
9585 					 * ire_lookup_multi() that uses
9586 					 * ire_ftable_lookup() to find
9587 					 * an IRE_INTERFACE for the group.
9588 					 * In the multirt case,
9589 					 * ire_lookup_multi() then invokes
9590 					 * ire_multirt_lookup() to find
9591 					 * the next resolvable ire.
9592 					 * As a result, we obtain an new
9593 					 * interface, derived from the
9594 					 * next ire.
9595 					 */
9596 					ipif_refrele(ipif);
9597 					ipif = ipif_lookup_group(ipha_dst,
9598 					    zoneid, ipst);
9599 					if (ipif != NULL) {
9600 						mp = copy_mp;
9601 						copy_mp = NULL;
9602 						multirt_resolve_next = B_TRUE;
9603 						continue;
9604 					} else {
9605 						freemsg(copy_mp);
9606 					}
9607 				}
9608 			}
9609 			if (ipif != NULL)
9610 				ipif_refrele(ipif);
9611 			ill_refrele(dst_ill);
9612 			ipif_refrele(src_ipif);
9613 			return;
9614 		default:
9615 			break;
9616 		}
9617 	} while (multirt_resolve_next);
9618 
9619 err_ret:
9620 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9621 	if (fire != NULL)
9622 		ire_refrele(fire);
9623 	ipif_refrele(ipif);
9624 	/* Did this packet originate externally? */
9625 	if (dst_ill != NULL)
9626 		ill_refrele(dst_ill);
9627 	if (src_ipif != NULL)
9628 		ipif_refrele(src_ipif);
9629 	if (mp->b_prev || mp->b_next) {
9630 		mp->b_next = NULL;
9631 		mp->b_prev = NULL;
9632 	} else {
9633 		/*
9634 		 * Since ip_wput() isn't close to finished, we fill
9635 		 * in enough of the header for credible error reporting.
9636 		 */
9637 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9638 			/* Failed */
9639 			freemsg(first_mp);
9640 			if (ire != NULL)
9641 				ire_refrele(ire);
9642 			return;
9643 		}
9644 	}
9645 	/*
9646 	 * At this point we will have ire only if RTF_BLACKHOLE
9647 	 * or RTF_REJECT flags are set on the IRE. It will not
9648 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9649 	 */
9650 	if (ire != NULL) {
9651 		if (ire->ire_flags & RTF_BLACKHOLE) {
9652 			ire_refrele(ire);
9653 			freemsg(first_mp);
9654 			return;
9655 		}
9656 		ire_refrele(ire);
9657 	}
9658 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9659 }
9660 
9661 /* Name/Value Table Lookup Routine */
9662 char *
9663 ip_nv_lookup(nv_t *nv, int value)
9664 {
9665 	if (!nv)
9666 		return (NULL);
9667 	for (; nv->nv_name; nv++) {
9668 		if (nv->nv_value == value)
9669 			return (nv->nv_name);
9670 	}
9671 	return ("unknown");
9672 }
9673 
9674 /*
9675  * This is a module open, i.e. this is a control stream for access
9676  * to a DLPI device.  We allocate an ill_t as the instance data in
9677  * this case.
9678  */
9679 int
9680 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9681 {
9682 	ill_t	*ill;
9683 	int	err;
9684 	zoneid_t zoneid;
9685 	netstack_t *ns;
9686 	ip_stack_t *ipst;
9687 
9688 	/*
9689 	 * Prevent unprivileged processes from pushing IP so that
9690 	 * they can't send raw IP.
9691 	 */
9692 	if (secpolicy_net_rawaccess(credp) != 0)
9693 		return (EPERM);
9694 
9695 	ns = netstack_find_by_cred(credp);
9696 	ASSERT(ns != NULL);
9697 	ipst = ns->netstack_ip;
9698 	ASSERT(ipst != NULL);
9699 
9700 	/*
9701 	 * For exclusive stacks we set the zoneid to zero
9702 	 * to make IP operate as if in the global zone.
9703 	 */
9704 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9705 		zoneid = GLOBAL_ZONEID;
9706 	else
9707 		zoneid = crgetzoneid(credp);
9708 
9709 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9710 	q->q_ptr = WR(q)->q_ptr = ill;
9711 	ill->ill_ipst = ipst;
9712 	ill->ill_zoneid = zoneid;
9713 
9714 	/*
9715 	 * ill_init initializes the ill fields and then sends down
9716 	 * down a DL_INFO_REQ after calling qprocson.
9717 	 */
9718 	err = ill_init(q, ill);
9719 	if (err != 0) {
9720 		mi_free(ill);
9721 		netstack_rele(ipst->ips_netstack);
9722 		q->q_ptr = NULL;
9723 		WR(q)->q_ptr = NULL;
9724 		return (err);
9725 	}
9726 
9727 	/* ill_init initializes the ipsq marking this thread as writer */
9728 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
9729 	/* Wait for the DL_INFO_ACK */
9730 	mutex_enter(&ill->ill_lock);
9731 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9732 		/*
9733 		 * Return value of 0 indicates a pending signal.
9734 		 */
9735 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9736 		if (err == 0) {
9737 			mutex_exit(&ill->ill_lock);
9738 			(void) ip_close(q, 0);
9739 			return (EINTR);
9740 		}
9741 	}
9742 	mutex_exit(&ill->ill_lock);
9743 
9744 	/*
9745 	 * ip_rput_other could have set an error  in ill_error on
9746 	 * receipt of M_ERROR.
9747 	 */
9748 
9749 	err = ill->ill_error;
9750 	if (err != 0) {
9751 		(void) ip_close(q, 0);
9752 		return (err);
9753 	}
9754 
9755 	ill->ill_credp = credp;
9756 	crhold(credp);
9757 
9758 	mutex_enter(&ipst->ips_ip_mi_lock);
9759 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
9760 	    credp);
9761 	mutex_exit(&ipst->ips_ip_mi_lock);
9762 	if (err) {
9763 		(void) ip_close(q, 0);
9764 		return (err);
9765 	}
9766 	return (0);
9767 }
9768 
9769 /* For /dev/ip aka AF_INET open */
9770 int
9771 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9772 {
9773 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
9774 }
9775 
9776 /* For /dev/ip6 aka AF_INET6 open */
9777 int
9778 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9779 {
9780 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
9781 }
9782 
9783 /* IP open routine. */
9784 int
9785 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9786     boolean_t isv6)
9787 {
9788 	conn_t 		*connp;
9789 	major_t		maj;
9790 	zoneid_t	zoneid;
9791 	netstack_t	*ns;
9792 	ip_stack_t	*ipst;
9793 
9794 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9795 
9796 	/* Allow reopen. */
9797 	if (q->q_ptr != NULL)
9798 		return (0);
9799 
9800 	if (sflag & MODOPEN) {
9801 		/* This is a module open */
9802 		return (ip_modopen(q, devp, flag, sflag, credp));
9803 	}
9804 
9805 	ns = netstack_find_by_cred(credp);
9806 	ASSERT(ns != NULL);
9807 	ipst = ns->netstack_ip;
9808 	ASSERT(ipst != NULL);
9809 
9810 	/*
9811 	 * For exclusive stacks we set the zoneid to zero
9812 	 * to make IP operate as if in the global zone.
9813 	 */
9814 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9815 		zoneid = GLOBAL_ZONEID;
9816 	else
9817 		zoneid = crgetzoneid(credp);
9818 
9819 	/*
9820 	 * We are opening as a device. This is an IP client stream, and we
9821 	 * allocate an conn_t as the instance data.
9822 	 */
9823 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
9824 
9825 	/*
9826 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
9827 	 * done by netstack_find_by_cred()
9828 	 */
9829 	netstack_rele(ipst->ips_netstack);
9830 
9831 	connp->conn_zoneid = zoneid;
9832 
9833 	connp->conn_upq = q;
9834 	q->q_ptr = WR(q)->q_ptr = connp;
9835 
9836 	if (flag & SO_SOCKSTR)
9837 		connp->conn_flags |= IPCL_SOCKET;
9838 
9839 	/* Minor tells us which /dev entry was opened */
9840 	if (isv6) {
9841 		connp->conn_flags |= IPCL_ISV6;
9842 		connp->conn_af_isv6 = B_TRUE;
9843 		ip_setpktversion(connp, isv6, B_FALSE, ipst);
9844 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9845 	} else {
9846 		connp->conn_af_isv6 = B_FALSE;
9847 		connp->conn_pkt_isv6 = B_FALSE;
9848 	}
9849 
9850 	if ((connp->conn_dev = inet_minor_alloc(ip_minor_arena)) == 0) {
9851 		/* CONN_DEC_REF takes care of netstack_rele() */
9852 		q->q_ptr = WR(q)->q_ptr = NULL;
9853 		CONN_DEC_REF(connp);
9854 		return (EBUSY);
9855 	}
9856 
9857 	maj = getemajor(*devp);
9858 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9859 
9860 	/*
9861 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9862 	 */
9863 	connp->conn_cred = credp;
9864 
9865 	/*
9866 	 * Handle IP_RTS_REQUEST and other ioctls which use conn_recv
9867 	 */
9868 	connp->conn_recv = ip_conn_input;
9869 
9870 	crhold(connp->conn_cred);
9871 
9872 	/*
9873 	 * If the caller has the process-wide flag set, then default to MAC
9874 	 * exempt mode.  This allows read-down to unlabeled hosts.
9875 	 */
9876 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9877 		connp->conn_mac_exempt = B_TRUE;
9878 
9879 	connp->conn_rq = q;
9880 	connp->conn_wq = WR(q);
9881 
9882 	/* Non-zero default values */
9883 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9884 
9885 	/*
9886 	 * Make the conn globally visible to walkers
9887 	 */
9888 	ASSERT(connp->conn_ref == 1);
9889 	mutex_enter(&connp->conn_lock);
9890 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9891 	mutex_exit(&connp->conn_lock);
9892 
9893 	qprocson(q);
9894 
9895 	return (0);
9896 }
9897 
9898 /*
9899  * Change the output format (IPv4 vs. IPv6) for a conn_t.
9900  * Note that there is no race since either ip_output function works - it
9901  * is just an optimization to enter the best ip_output routine directly.
9902  */
9903 void
9904 ip_setpktversion(conn_t *connp, boolean_t isv6, boolean_t bump_mib,
9905     ip_stack_t *ipst)
9906 {
9907 	if (isv6)  {
9908 		if (bump_mib) {
9909 			BUMP_MIB(&ipst->ips_ip6_mib,
9910 			    ipIfStatsOutSwitchIPVersion);
9911 		}
9912 		connp->conn_send = ip_output_v6;
9913 		connp->conn_pkt_isv6 = B_TRUE;
9914 	} else {
9915 		if (bump_mib) {
9916 			BUMP_MIB(&ipst->ips_ip_mib,
9917 			    ipIfStatsOutSwitchIPVersion);
9918 		}
9919 		connp->conn_send = ip_output;
9920 		connp->conn_pkt_isv6 = B_FALSE;
9921 	}
9922 
9923 }
9924 
9925 /*
9926  * See if IPsec needs loading because of the options in mp.
9927  */
9928 static boolean_t
9929 ipsec_opt_present(mblk_t *mp)
9930 {
9931 	uint8_t *optcp, *next_optcp, *opt_endcp;
9932 	struct opthdr *opt;
9933 	struct T_opthdr *topt;
9934 	int opthdr_len;
9935 	t_uscalar_t optname, optlevel;
9936 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9937 	ipsec_req_t *ipsr;
9938 
9939 	/*
9940 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9941 	 * return TRUE.
9942 	 */
9943 
9944 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9945 	opt_endcp = optcp + tor->OPT_length;
9946 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9947 		opthdr_len = sizeof (struct T_opthdr);
9948 	} else {		/* O_OPTMGMT_REQ */
9949 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9950 		opthdr_len = sizeof (struct opthdr);
9951 	}
9952 	for (; optcp < opt_endcp; optcp = next_optcp) {
9953 		if (optcp + opthdr_len > opt_endcp)
9954 			return (B_FALSE);	/* Not enough option header. */
9955 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9956 			topt = (struct T_opthdr *)optcp;
9957 			optlevel = topt->level;
9958 			optname = topt->name;
9959 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9960 		} else {
9961 			opt = (struct opthdr *)optcp;
9962 			optlevel = opt->level;
9963 			optname = opt->name;
9964 			next_optcp = optcp + opthdr_len +
9965 			    _TPI_ALIGN_OPT(opt->len);
9966 		}
9967 		if ((next_optcp < optcp) || /* wraparound pointer space */
9968 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9969 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9970 			return (B_FALSE); /* bad option buffer */
9971 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9972 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9973 			/*
9974 			 * Check to see if it's an all-bypass or all-zeroes
9975 			 * IPsec request.  Don't bother loading IPsec if
9976 			 * the socket doesn't want to use it.  (A good example
9977 			 * is a bypass request.)
9978 			 *
9979 			 * Basically, if any of the non-NEVER bits are set,
9980 			 * load IPsec.
9981 			 */
9982 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
9983 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
9984 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
9985 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
9986 			    != 0)
9987 				return (B_TRUE);
9988 		}
9989 	}
9990 	return (B_FALSE);
9991 }
9992 
9993 /*
9994  * If conn is is waiting for ipsec to finish loading, kick it.
9995  */
9996 /* ARGSUSED */
9997 static void
9998 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
9999 {
10000 	t_scalar_t	optreq_prim;
10001 	mblk_t		*mp;
10002 	cred_t		*cr;
10003 	int		err = 0;
10004 
10005 	/*
10006 	 * This function is called, after ipsec loading is complete.
10007 	 * Since IP checks exclusively and atomically (i.e it prevents
10008 	 * ipsec load from completing until ip_optcom_req completes)
10009 	 * whether ipsec load is complete, there cannot be a race with IP
10010 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
10011 	 */
10012 	mutex_enter(&connp->conn_lock);
10013 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
10014 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
10015 		mp = connp->conn_ipsec_opt_mp;
10016 		connp->conn_ipsec_opt_mp = NULL;
10017 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
10018 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
10019 		mutex_exit(&connp->conn_lock);
10020 
10021 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
10022 
10023 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
10024 		if (optreq_prim == T_OPTMGMT_REQ) {
10025 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10026 			    &ip_opt_obj, B_FALSE);
10027 		} else {
10028 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
10029 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10030 			    &ip_opt_obj, B_FALSE);
10031 		}
10032 		if (err != EINPROGRESS)
10033 			CONN_OPER_PENDING_DONE(connp);
10034 		return;
10035 	}
10036 	mutex_exit(&connp->conn_lock);
10037 }
10038 
10039 /*
10040  * Called from the ipsec_loader thread, outside any perimeter, to tell
10041  * ip qenable any of the queues waiting for the ipsec loader to
10042  * complete.
10043  */
10044 void
10045 ip_ipsec_load_complete(ipsec_stack_t *ipss)
10046 {
10047 	netstack_t *ns = ipss->ipsec_netstack;
10048 
10049 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
10050 }
10051 
10052 /*
10053  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10054  * determines the grp on which it has to become exclusive, queues the mp
10055  * and sq draining restarts the optmgmt
10056  */
10057 static boolean_t
10058 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10059 {
10060 	conn_t *connp = Q_TO_CONN(q);
10061 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
10062 
10063 	/*
10064 	 * Take IPsec requests and treat them special.
10065 	 */
10066 	if (ipsec_opt_present(mp)) {
10067 		/* First check if IPsec is loaded. */
10068 		mutex_enter(&ipss->ipsec_loader_lock);
10069 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
10070 			mutex_exit(&ipss->ipsec_loader_lock);
10071 			return (B_FALSE);
10072 		}
10073 		mutex_enter(&connp->conn_lock);
10074 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10075 
10076 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10077 		connp->conn_ipsec_opt_mp = mp;
10078 		mutex_exit(&connp->conn_lock);
10079 		mutex_exit(&ipss->ipsec_loader_lock);
10080 
10081 		ipsec_loader_loadnow(ipss);
10082 		return (B_TRUE);
10083 	}
10084 	return (B_FALSE);
10085 }
10086 
10087 /*
10088  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10089  * all of them are copied to the conn_t. If the req is "zero", the policy is
10090  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10091  * fields.
10092  * We keep only the latest setting of the policy and thus policy setting
10093  * is not incremental/cumulative.
10094  *
10095  * Requests to set policies with multiple alternative actions will
10096  * go through a different API.
10097  */
10098 int
10099 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10100 {
10101 	uint_t ah_req = 0;
10102 	uint_t esp_req = 0;
10103 	uint_t se_req = 0;
10104 	ipsec_selkey_t sel;
10105 	ipsec_act_t *actp = NULL;
10106 	uint_t nact;
10107 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
10108 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
10109 	ipsec_policy_root_t *pr;
10110 	ipsec_policy_head_t *ph;
10111 	int fam;
10112 	boolean_t is_pol_reset;
10113 	int error = 0;
10114 	netstack_t	*ns = connp->conn_netstack;
10115 	ip_stack_t	*ipst = ns->netstack_ip;
10116 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10117 
10118 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10119 
10120 	/*
10121 	 * The IP_SEC_OPT option does not allow variable length parameters,
10122 	 * hence a request cannot be NULL.
10123 	 */
10124 	if (req == NULL)
10125 		return (EINVAL);
10126 
10127 	ah_req = req->ipsr_ah_req;
10128 	esp_req = req->ipsr_esp_req;
10129 	se_req = req->ipsr_self_encap_req;
10130 
10131 	/*
10132 	 * Are we dealing with a request to reset the policy (i.e.
10133 	 * zero requests).
10134 	 */
10135 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10136 	    (esp_req & REQ_MASK) == 0 &&
10137 	    (se_req & REQ_MASK) == 0);
10138 
10139 	if (!is_pol_reset) {
10140 		/*
10141 		 * If we couldn't load IPsec, fail with "protocol
10142 		 * not supported".
10143 		 * IPsec may not have been loaded for a request with zero
10144 		 * policies, so we don't fail in this case.
10145 		 */
10146 		mutex_enter(&ipss->ipsec_loader_lock);
10147 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10148 			mutex_exit(&ipss->ipsec_loader_lock);
10149 			return (EPROTONOSUPPORT);
10150 		}
10151 		mutex_exit(&ipss->ipsec_loader_lock);
10152 
10153 		/*
10154 		 * Test for valid requests. Invalid algorithms
10155 		 * need to be tested by IPsec code because new
10156 		 * algorithms can be added dynamically.
10157 		 */
10158 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10159 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10160 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10161 			return (EINVAL);
10162 		}
10163 
10164 		/*
10165 		 * Only privileged users can issue these
10166 		 * requests.
10167 		 */
10168 		if (((ah_req & IPSEC_PREF_NEVER) ||
10169 		    (esp_req & IPSEC_PREF_NEVER) ||
10170 		    (se_req & IPSEC_PREF_NEVER)) &&
10171 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10172 			return (EPERM);
10173 		}
10174 
10175 		/*
10176 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10177 		 * are mutually exclusive.
10178 		 */
10179 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10180 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10181 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10182 			/* Both of them are set */
10183 			return (EINVAL);
10184 		}
10185 	}
10186 
10187 	mutex_enter(&connp->conn_lock);
10188 
10189 	/*
10190 	 * If we have already cached policies in ip_bind_connected*(), don't
10191 	 * let them change now. We cache policies for connections
10192 	 * whose src,dst [addr, port] is known.
10193 	 */
10194 	if (connp->conn_policy_cached) {
10195 		mutex_exit(&connp->conn_lock);
10196 		return (EINVAL);
10197 	}
10198 
10199 	/*
10200 	 * We have a zero policies, reset the connection policy if already
10201 	 * set. This will cause the connection to inherit the
10202 	 * global policy, if any.
10203 	 */
10204 	if (is_pol_reset) {
10205 		if (connp->conn_policy != NULL) {
10206 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10207 			connp->conn_policy = NULL;
10208 		}
10209 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10210 		connp->conn_in_enforce_policy = B_FALSE;
10211 		connp->conn_out_enforce_policy = B_FALSE;
10212 		mutex_exit(&connp->conn_lock);
10213 		return (0);
10214 	}
10215 
10216 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10217 	    ipst->ips_netstack);
10218 	if (ph == NULL)
10219 		goto enomem;
10220 
10221 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10222 	if (actp == NULL)
10223 		goto enomem;
10224 
10225 	/*
10226 	 * Always allocate IPv4 policy entries, since they can also
10227 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10228 	 */
10229 	bzero(&sel, sizeof (sel));
10230 	sel.ipsl_valid = IPSL_IPV4;
10231 
10232 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10233 	    ipst->ips_netstack);
10234 	if (pin4 == NULL)
10235 		goto enomem;
10236 
10237 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10238 	    ipst->ips_netstack);
10239 	if (pout4 == NULL)
10240 		goto enomem;
10241 
10242 	if (connp->conn_af_isv6) {
10243 		/*
10244 		 * We're looking at a v6 socket, also allocate the
10245 		 * v6-specific entries...
10246 		 */
10247 		sel.ipsl_valid = IPSL_IPV6;
10248 		pin6 = ipsec_policy_create(&sel, actp, nact,
10249 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10250 		if (pin6 == NULL)
10251 			goto enomem;
10252 
10253 		pout6 = ipsec_policy_create(&sel, actp, nact,
10254 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10255 		if (pout6 == NULL)
10256 			goto enomem;
10257 
10258 		/*
10259 		 * .. and file them away in the right place.
10260 		 */
10261 		fam = IPSEC_AF_V6;
10262 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10263 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10264 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10265 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10266 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10267 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10268 	}
10269 
10270 	ipsec_actvec_free(actp, nact);
10271 
10272 	/*
10273 	 * File the v4 policies.
10274 	 */
10275 	fam = IPSEC_AF_V4;
10276 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10277 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10278 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10279 
10280 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10281 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10282 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10283 
10284 	/*
10285 	 * If the requests need security, set enforce_policy.
10286 	 * If the requests are IPSEC_PREF_NEVER, one should
10287 	 * still set conn_out_enforce_policy so that an ipsec_out
10288 	 * gets attached in ip_wput. This is needed so that
10289 	 * for connections that we don't cache policy in ip_bind,
10290 	 * if global policy matches in ip_wput_attach_policy, we
10291 	 * don't wrongly inherit global policy. Similarly, we need
10292 	 * to set conn_in_enforce_policy also so that we don't verify
10293 	 * policy wrongly.
10294 	 */
10295 	if ((ah_req & REQ_MASK) != 0 ||
10296 	    (esp_req & REQ_MASK) != 0 ||
10297 	    (se_req & REQ_MASK) != 0) {
10298 		connp->conn_in_enforce_policy = B_TRUE;
10299 		connp->conn_out_enforce_policy = B_TRUE;
10300 		connp->conn_flags |= IPCL_CHECK_POLICY;
10301 	}
10302 
10303 	mutex_exit(&connp->conn_lock);
10304 	return (error);
10305 #undef REQ_MASK
10306 
10307 	/*
10308 	 * Common memory-allocation-failure exit path.
10309 	 */
10310 enomem:
10311 	mutex_exit(&connp->conn_lock);
10312 	if (actp != NULL)
10313 		ipsec_actvec_free(actp, nact);
10314 	if (pin4 != NULL)
10315 		IPPOL_REFRELE(pin4, ipst->ips_netstack);
10316 	if (pout4 != NULL)
10317 		IPPOL_REFRELE(pout4, ipst->ips_netstack);
10318 	if (pin6 != NULL)
10319 		IPPOL_REFRELE(pin6, ipst->ips_netstack);
10320 	if (pout6 != NULL)
10321 		IPPOL_REFRELE(pout6, ipst->ips_netstack);
10322 	return (ENOMEM);
10323 }
10324 
10325 /*
10326  * Only for options that pass in an IP addr. Currently only V4 options
10327  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10328  * So this function assumes level is IPPROTO_IP
10329  */
10330 int
10331 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10332     mblk_t *first_mp)
10333 {
10334 	ipif_t *ipif = NULL;
10335 	int error;
10336 	ill_t *ill;
10337 	int zoneid;
10338 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10339 
10340 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10341 
10342 	if (addr != INADDR_ANY || checkonly) {
10343 		ASSERT(connp != NULL);
10344 		zoneid = IPCL_ZONEID(connp);
10345 		if (option == IP_NEXTHOP) {
10346 			ipif = ipif_lookup_onlink_addr(addr,
10347 			    connp->conn_zoneid, ipst);
10348 		} else {
10349 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10350 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10351 			    &error, ipst);
10352 		}
10353 		if (ipif == NULL) {
10354 			if (error == EINPROGRESS)
10355 				return (error);
10356 			else if ((option == IP_MULTICAST_IF) ||
10357 			    (option == IP_NEXTHOP))
10358 				return (EHOSTUNREACH);
10359 			else
10360 				return (EINVAL);
10361 		} else if (checkonly) {
10362 			if (option == IP_MULTICAST_IF) {
10363 				ill = ipif->ipif_ill;
10364 				/* not supported by the virtual network iface */
10365 				if (IS_VNI(ill)) {
10366 					ipif_refrele(ipif);
10367 					return (EINVAL);
10368 				}
10369 			}
10370 			ipif_refrele(ipif);
10371 			return (0);
10372 		}
10373 		ill = ipif->ipif_ill;
10374 		mutex_enter(&connp->conn_lock);
10375 		mutex_enter(&ill->ill_lock);
10376 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10377 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10378 			mutex_exit(&ill->ill_lock);
10379 			mutex_exit(&connp->conn_lock);
10380 			ipif_refrele(ipif);
10381 			return (option == IP_MULTICAST_IF ?
10382 			    EHOSTUNREACH : EINVAL);
10383 		}
10384 	} else {
10385 		mutex_enter(&connp->conn_lock);
10386 	}
10387 
10388 	/* None of the options below are supported on the VNI */
10389 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10390 		mutex_exit(&ill->ill_lock);
10391 		mutex_exit(&connp->conn_lock);
10392 		ipif_refrele(ipif);
10393 		return (EINVAL);
10394 	}
10395 
10396 	switch (option) {
10397 	case IP_DONTFAILOVER_IF:
10398 		/*
10399 		 * This option is used by in.mpathd to ensure
10400 		 * that IPMP probe packets only go out on the
10401 		 * test interfaces. in.mpathd sets this option
10402 		 * on the non-failover interfaces.
10403 		 * For backward compatibility, this option
10404 		 * implicitly sets IP_MULTICAST_IF, as used
10405 		 * be done in bind(), so that ip_wput gets
10406 		 * this ipif to send mcast packets.
10407 		 */
10408 		if (ipif != NULL) {
10409 			ASSERT(addr != INADDR_ANY);
10410 			connp->conn_nofailover_ill = ipif->ipif_ill;
10411 			connp->conn_multicast_ipif = ipif;
10412 		} else {
10413 			ASSERT(addr == INADDR_ANY);
10414 			connp->conn_nofailover_ill = NULL;
10415 			connp->conn_multicast_ipif = NULL;
10416 		}
10417 		break;
10418 
10419 	case IP_MULTICAST_IF:
10420 		connp->conn_multicast_ipif = ipif;
10421 		break;
10422 	case IP_NEXTHOP:
10423 		connp->conn_nexthop_v4 = addr;
10424 		connp->conn_nexthop_set = B_TRUE;
10425 		break;
10426 	}
10427 
10428 	if (ipif != NULL) {
10429 		mutex_exit(&ill->ill_lock);
10430 		mutex_exit(&connp->conn_lock);
10431 		ipif_refrele(ipif);
10432 		return (0);
10433 	}
10434 	mutex_exit(&connp->conn_lock);
10435 	/* We succeded in cleared the option */
10436 	return (0);
10437 }
10438 
10439 /*
10440  * For options that pass in an ifindex specifying the ill. V6 options always
10441  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10442  */
10443 int
10444 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10445     int level, int option, mblk_t *first_mp)
10446 {
10447 	ill_t *ill = NULL;
10448 	int error = 0;
10449 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10450 
10451 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10452 	if (ifindex != 0) {
10453 		ASSERT(connp != NULL);
10454 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10455 		    first_mp, ip_restart_optmgmt, &error, ipst);
10456 		if (ill != NULL) {
10457 			if (checkonly) {
10458 				/* not supported by the virtual network iface */
10459 				if (IS_VNI(ill)) {
10460 					ill_refrele(ill);
10461 					return (EINVAL);
10462 				}
10463 				ill_refrele(ill);
10464 				return (0);
10465 			}
10466 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
10467 			    0, NULL)) {
10468 				ill_refrele(ill);
10469 				ill = NULL;
10470 				mutex_enter(&connp->conn_lock);
10471 				goto setit;
10472 			}
10473 			mutex_enter(&connp->conn_lock);
10474 			mutex_enter(&ill->ill_lock);
10475 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10476 				mutex_exit(&ill->ill_lock);
10477 				mutex_exit(&connp->conn_lock);
10478 				ill_refrele(ill);
10479 				ill = NULL;
10480 				mutex_enter(&connp->conn_lock);
10481 			}
10482 			goto setit;
10483 		} else if (error == EINPROGRESS) {
10484 			return (error);
10485 		} else {
10486 			error = 0;
10487 		}
10488 	}
10489 	mutex_enter(&connp->conn_lock);
10490 setit:
10491 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10492 
10493 	/*
10494 	 * The options below assume that the ILL (if any) transmits and/or
10495 	 * receives traffic. Neither of which is true for the virtual network
10496 	 * interface, so fail setting these on a VNI.
10497 	 */
10498 	if (IS_VNI(ill)) {
10499 		ASSERT(ill != NULL);
10500 		mutex_exit(&ill->ill_lock);
10501 		mutex_exit(&connp->conn_lock);
10502 		ill_refrele(ill);
10503 		return (EINVAL);
10504 	}
10505 
10506 	if (level == IPPROTO_IP) {
10507 		switch (option) {
10508 		case IP_BOUND_IF:
10509 			connp->conn_incoming_ill = ill;
10510 			connp->conn_outgoing_ill = ill;
10511 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10512 			    0 : ifindex;
10513 			break;
10514 
10515 		case IP_MULTICAST_IF:
10516 			/*
10517 			 * This option is an internal special. The socket
10518 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10519 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10520 			 * specifies an ifindex and we try first on V6 ill's.
10521 			 * If we don't find one, we they try using on v4 ill's
10522 			 * intenally and we come here.
10523 			 */
10524 			if (!checkonly && ill != NULL) {
10525 				ipif_t	*ipif;
10526 				ipif = ill->ill_ipif;
10527 
10528 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10529 					mutex_exit(&ill->ill_lock);
10530 					mutex_exit(&connp->conn_lock);
10531 					ill_refrele(ill);
10532 					ill = NULL;
10533 					mutex_enter(&connp->conn_lock);
10534 				} else {
10535 					connp->conn_multicast_ipif = ipif;
10536 				}
10537 			}
10538 			break;
10539 
10540 		case IP_DHCPINIT_IF:
10541 			if (connp->conn_dhcpinit_ill != NULL) {
10542 				/*
10543 				 * We've locked the conn so conn_cleanup_ill()
10544 				 * cannot clear conn_dhcpinit_ill -- so it's
10545 				 * safe to access the ill.
10546 				 */
10547 				ill_t *oill = connp->conn_dhcpinit_ill;
10548 
10549 				ASSERT(oill->ill_dhcpinit != 0);
10550 				atomic_dec_32(&oill->ill_dhcpinit);
10551 				connp->conn_dhcpinit_ill = NULL;
10552 			}
10553 
10554 			if (ill != NULL) {
10555 				connp->conn_dhcpinit_ill = ill;
10556 				atomic_inc_32(&ill->ill_dhcpinit);
10557 			}
10558 			break;
10559 		}
10560 	} else {
10561 		switch (option) {
10562 		case IPV6_BOUND_IF:
10563 			connp->conn_incoming_ill = ill;
10564 			connp->conn_outgoing_ill = ill;
10565 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10566 			    0 : ifindex;
10567 			break;
10568 
10569 		case IPV6_BOUND_PIF:
10570 			/*
10571 			 * Limit all transmit to this ill.
10572 			 * Unlike IPV6_BOUND_IF, using this option
10573 			 * prevents load spreading and failover from
10574 			 * happening when the interface is part of the
10575 			 * group. That's why we don't need to remember
10576 			 * the ifindex in orig_bound_ifindex as in
10577 			 * IPV6_BOUND_IF.
10578 			 */
10579 			connp->conn_outgoing_pill = ill;
10580 			break;
10581 
10582 		case IPV6_DONTFAILOVER_IF:
10583 			/*
10584 			 * This option is used by in.mpathd to ensure
10585 			 * that IPMP probe packets only go out on the
10586 			 * test interfaces. in.mpathd sets this option
10587 			 * on the non-failover interfaces.
10588 			 */
10589 			connp->conn_nofailover_ill = ill;
10590 			/*
10591 			 * For backward compatibility, this option
10592 			 * implicitly sets ip_multicast_ill as used in
10593 			 * IPV6_MULTICAST_IF so that ip_wput gets
10594 			 * this ill to send mcast packets.
10595 			 */
10596 			connp->conn_multicast_ill = ill;
10597 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
10598 			    0 : ifindex;
10599 			break;
10600 
10601 		case IPV6_MULTICAST_IF:
10602 			/*
10603 			 * Set conn_multicast_ill to be the IPv6 ill.
10604 			 * Set conn_multicast_ipif to be an IPv4 ipif
10605 			 * for ifindex to make IPv4 mapped addresses
10606 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10607 			 * Even if no IPv6 ill exists for the ifindex
10608 			 * we need to check for an IPv4 ifindex in order
10609 			 * for this to work with mapped addresses. In that
10610 			 * case only set conn_multicast_ipif.
10611 			 */
10612 			if (!checkonly) {
10613 				if (ifindex == 0) {
10614 					connp->conn_multicast_ill = NULL;
10615 					connp->conn_orig_multicast_ifindex = 0;
10616 					connp->conn_multicast_ipif = NULL;
10617 				} else if (ill != NULL) {
10618 					connp->conn_multicast_ill = ill;
10619 					connp->conn_orig_multicast_ifindex =
10620 					    ifindex;
10621 				}
10622 			}
10623 			break;
10624 		}
10625 	}
10626 
10627 	if (ill != NULL) {
10628 		mutex_exit(&ill->ill_lock);
10629 		mutex_exit(&connp->conn_lock);
10630 		ill_refrele(ill);
10631 		return (0);
10632 	}
10633 	mutex_exit(&connp->conn_lock);
10634 	/*
10635 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10636 	 * locate the ill and could not set the option (ifindex != 0)
10637 	 */
10638 	return (ifindex == 0 ? 0 : EINVAL);
10639 }
10640 
10641 /* This routine sets socket options. */
10642 /* ARGSUSED */
10643 int
10644 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10645     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10646     void *dummy, cred_t *cr, mblk_t *first_mp)
10647 {
10648 	int		*i1 = (int *)invalp;
10649 	conn_t		*connp = Q_TO_CONN(q);
10650 	int		error = 0;
10651 	boolean_t	checkonly;
10652 	ire_t		*ire;
10653 	boolean_t	found;
10654 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10655 
10656 	switch (optset_context) {
10657 
10658 	case SETFN_OPTCOM_CHECKONLY:
10659 		checkonly = B_TRUE;
10660 		/*
10661 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10662 		 * inlen != 0 implies value supplied and
10663 		 * 	we have to "pretend" to set it.
10664 		 * inlen == 0 implies that there is no
10665 		 * 	value part in T_CHECK request and just validation
10666 		 * done elsewhere should be enough, we just return here.
10667 		 */
10668 		if (inlen == 0) {
10669 			*outlenp = 0;
10670 			return (0);
10671 		}
10672 		break;
10673 	case SETFN_OPTCOM_NEGOTIATE:
10674 	case SETFN_UD_NEGOTIATE:
10675 	case SETFN_CONN_NEGOTIATE:
10676 		checkonly = B_FALSE;
10677 		break;
10678 	default:
10679 		/*
10680 		 * We should never get here
10681 		 */
10682 		*outlenp = 0;
10683 		return (EINVAL);
10684 	}
10685 
10686 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10687 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10688 
10689 	/*
10690 	 * For fixed length options, no sanity check
10691 	 * of passed in length is done. It is assumed *_optcom_req()
10692 	 * routines do the right thing.
10693 	 */
10694 
10695 	switch (level) {
10696 	case SOL_SOCKET:
10697 		/*
10698 		 * conn_lock protects the bitfields, and is used to
10699 		 * set the fields atomically.
10700 		 */
10701 		switch (name) {
10702 		case SO_BROADCAST:
10703 			if (!checkonly) {
10704 				/* TODO: use value someplace? */
10705 				mutex_enter(&connp->conn_lock);
10706 				connp->conn_broadcast = *i1 ? 1 : 0;
10707 				mutex_exit(&connp->conn_lock);
10708 			}
10709 			break;	/* goto sizeof (int) option return */
10710 		case SO_USELOOPBACK:
10711 			if (!checkonly) {
10712 				/* TODO: use value someplace? */
10713 				mutex_enter(&connp->conn_lock);
10714 				connp->conn_loopback = *i1 ? 1 : 0;
10715 				mutex_exit(&connp->conn_lock);
10716 			}
10717 			break;	/* goto sizeof (int) option return */
10718 		case SO_DONTROUTE:
10719 			if (!checkonly) {
10720 				mutex_enter(&connp->conn_lock);
10721 				connp->conn_dontroute = *i1 ? 1 : 0;
10722 				mutex_exit(&connp->conn_lock);
10723 			}
10724 			break;	/* goto sizeof (int) option return */
10725 		case SO_REUSEADDR:
10726 			if (!checkonly) {
10727 				mutex_enter(&connp->conn_lock);
10728 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10729 				mutex_exit(&connp->conn_lock);
10730 			}
10731 			break;	/* goto sizeof (int) option return */
10732 		case SO_PROTOTYPE:
10733 			if (!checkonly) {
10734 				mutex_enter(&connp->conn_lock);
10735 				connp->conn_proto = *i1;
10736 				mutex_exit(&connp->conn_lock);
10737 			}
10738 			break;	/* goto sizeof (int) option return */
10739 		case SO_ALLZONES:
10740 			if (!checkonly) {
10741 				mutex_enter(&connp->conn_lock);
10742 				if (IPCL_IS_BOUND(connp)) {
10743 					mutex_exit(&connp->conn_lock);
10744 					return (EINVAL);
10745 				}
10746 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10747 				mutex_exit(&connp->conn_lock);
10748 			}
10749 			break;	/* goto sizeof (int) option return */
10750 		case SO_ANON_MLP:
10751 			if (!checkonly) {
10752 				mutex_enter(&connp->conn_lock);
10753 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10754 				mutex_exit(&connp->conn_lock);
10755 			}
10756 			break;	/* goto sizeof (int) option return */
10757 		case SO_MAC_EXEMPT:
10758 			if (secpolicy_net_mac_aware(cr) != 0 ||
10759 			    IPCL_IS_BOUND(connp))
10760 				return (EACCES);
10761 			if (!checkonly) {
10762 				mutex_enter(&connp->conn_lock);
10763 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10764 				mutex_exit(&connp->conn_lock);
10765 			}
10766 			break;	/* goto sizeof (int) option return */
10767 		default:
10768 			/*
10769 			 * "soft" error (negative)
10770 			 * option not handled at this level
10771 			 * Note: Do not modify *outlenp
10772 			 */
10773 			return (-EINVAL);
10774 		}
10775 		break;
10776 	case IPPROTO_IP:
10777 		switch (name) {
10778 		case IP_NEXTHOP:
10779 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
10780 				return (EPERM);
10781 			/* FALLTHRU */
10782 		case IP_MULTICAST_IF:
10783 		case IP_DONTFAILOVER_IF: {
10784 			ipaddr_t addr = *i1;
10785 
10786 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10787 			    first_mp);
10788 			if (error != 0)
10789 				return (error);
10790 			break;	/* goto sizeof (int) option return */
10791 		}
10792 
10793 		case IP_MULTICAST_TTL:
10794 			/* Recorded in transport above IP */
10795 			*outvalp = *invalp;
10796 			*outlenp = sizeof (uchar_t);
10797 			return (0);
10798 		case IP_MULTICAST_LOOP:
10799 			if (!checkonly) {
10800 				mutex_enter(&connp->conn_lock);
10801 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10802 				mutex_exit(&connp->conn_lock);
10803 			}
10804 			*outvalp = *invalp;
10805 			*outlenp = sizeof (uchar_t);
10806 			return (0);
10807 		case IP_ADD_MEMBERSHIP:
10808 		case MCAST_JOIN_GROUP:
10809 		case IP_DROP_MEMBERSHIP:
10810 		case MCAST_LEAVE_GROUP: {
10811 			struct ip_mreq *mreqp;
10812 			struct group_req *greqp;
10813 			ire_t *ire;
10814 			boolean_t done = B_FALSE;
10815 			ipaddr_t group, ifaddr;
10816 			struct sockaddr_in *sin;
10817 			uint32_t *ifindexp;
10818 			boolean_t mcast_opt = B_TRUE;
10819 			mcast_record_t fmode;
10820 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10821 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10822 
10823 			switch (name) {
10824 			case IP_ADD_MEMBERSHIP:
10825 				mcast_opt = B_FALSE;
10826 				/* FALLTHRU */
10827 			case MCAST_JOIN_GROUP:
10828 				fmode = MODE_IS_EXCLUDE;
10829 				optfn = ip_opt_add_group;
10830 				break;
10831 
10832 			case IP_DROP_MEMBERSHIP:
10833 				mcast_opt = B_FALSE;
10834 				/* FALLTHRU */
10835 			case MCAST_LEAVE_GROUP:
10836 				fmode = MODE_IS_INCLUDE;
10837 				optfn = ip_opt_delete_group;
10838 				break;
10839 			}
10840 
10841 			if (mcast_opt) {
10842 				greqp = (struct group_req *)i1;
10843 				sin = (struct sockaddr_in *)&greqp->gr_group;
10844 				if (sin->sin_family != AF_INET) {
10845 					*outlenp = 0;
10846 					return (ENOPROTOOPT);
10847 				}
10848 				group = (ipaddr_t)sin->sin_addr.s_addr;
10849 				ifaddr = INADDR_ANY;
10850 				ifindexp = &greqp->gr_interface;
10851 			} else {
10852 				mreqp = (struct ip_mreq *)i1;
10853 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10854 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10855 				ifindexp = NULL;
10856 			}
10857 
10858 			/*
10859 			 * In the multirouting case, we need to replicate
10860 			 * the request on all interfaces that will take part
10861 			 * in replication.  We do so because multirouting is
10862 			 * reflective, thus we will probably receive multi-
10863 			 * casts on those interfaces.
10864 			 * The ip_multirt_apply_membership() succeeds if the
10865 			 * operation succeeds on at least one interface.
10866 			 */
10867 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10868 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10869 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10870 			if (ire != NULL) {
10871 				if (ire->ire_flags & RTF_MULTIRT) {
10872 					error = ip_multirt_apply_membership(
10873 					    optfn, ire, connp, checkonly, group,
10874 					    fmode, INADDR_ANY, first_mp);
10875 					done = B_TRUE;
10876 				}
10877 				ire_refrele(ire);
10878 			}
10879 			if (!done) {
10880 				error = optfn(connp, checkonly, group, ifaddr,
10881 				    ifindexp, fmode, INADDR_ANY, first_mp);
10882 			}
10883 			if (error) {
10884 				/*
10885 				 * EINPROGRESS is a soft error, needs retry
10886 				 * so don't make *outlenp zero.
10887 				 */
10888 				if (error != EINPROGRESS)
10889 					*outlenp = 0;
10890 				return (error);
10891 			}
10892 			/* OK return - copy input buffer into output buffer */
10893 			if (invalp != outvalp) {
10894 				/* don't trust bcopy for identical src/dst */
10895 				bcopy(invalp, outvalp, inlen);
10896 			}
10897 			*outlenp = inlen;
10898 			return (0);
10899 		}
10900 		case IP_BLOCK_SOURCE:
10901 		case IP_UNBLOCK_SOURCE:
10902 		case IP_ADD_SOURCE_MEMBERSHIP:
10903 		case IP_DROP_SOURCE_MEMBERSHIP:
10904 		case MCAST_BLOCK_SOURCE:
10905 		case MCAST_UNBLOCK_SOURCE:
10906 		case MCAST_JOIN_SOURCE_GROUP:
10907 		case MCAST_LEAVE_SOURCE_GROUP: {
10908 			struct ip_mreq_source *imreqp;
10909 			struct group_source_req *gsreqp;
10910 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10911 			uint32_t ifindex = 0;
10912 			mcast_record_t fmode;
10913 			struct sockaddr_in *sin;
10914 			ire_t *ire;
10915 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10916 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10917 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10918 
10919 			switch (name) {
10920 			case IP_BLOCK_SOURCE:
10921 				mcast_opt = B_FALSE;
10922 				/* FALLTHRU */
10923 			case MCAST_BLOCK_SOURCE:
10924 				fmode = MODE_IS_EXCLUDE;
10925 				optfn = ip_opt_add_group;
10926 				break;
10927 
10928 			case IP_UNBLOCK_SOURCE:
10929 				mcast_opt = B_FALSE;
10930 				/* FALLTHRU */
10931 			case MCAST_UNBLOCK_SOURCE:
10932 				fmode = MODE_IS_EXCLUDE;
10933 				optfn = ip_opt_delete_group;
10934 				break;
10935 
10936 			case IP_ADD_SOURCE_MEMBERSHIP:
10937 				mcast_opt = B_FALSE;
10938 				/* FALLTHRU */
10939 			case MCAST_JOIN_SOURCE_GROUP:
10940 				fmode = MODE_IS_INCLUDE;
10941 				optfn = ip_opt_add_group;
10942 				break;
10943 
10944 			case IP_DROP_SOURCE_MEMBERSHIP:
10945 				mcast_opt = B_FALSE;
10946 				/* FALLTHRU */
10947 			case MCAST_LEAVE_SOURCE_GROUP:
10948 				fmode = MODE_IS_INCLUDE;
10949 				optfn = ip_opt_delete_group;
10950 				break;
10951 			}
10952 
10953 			if (mcast_opt) {
10954 				gsreqp = (struct group_source_req *)i1;
10955 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10956 					*outlenp = 0;
10957 					return (ENOPROTOOPT);
10958 				}
10959 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10960 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10961 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10962 				src = (ipaddr_t)sin->sin_addr.s_addr;
10963 				ifindex = gsreqp->gsr_interface;
10964 			} else {
10965 				imreqp = (struct ip_mreq_source *)i1;
10966 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10967 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10968 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10969 			}
10970 
10971 			/*
10972 			 * In the multirouting case, we need to replicate
10973 			 * the request as noted in the mcast cases above.
10974 			 */
10975 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10976 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10977 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10978 			if (ire != NULL) {
10979 				if (ire->ire_flags & RTF_MULTIRT) {
10980 					error = ip_multirt_apply_membership(
10981 					    optfn, ire, connp, checkonly, grp,
10982 					    fmode, src, first_mp);
10983 					done = B_TRUE;
10984 				}
10985 				ire_refrele(ire);
10986 			}
10987 			if (!done) {
10988 				error = optfn(connp, checkonly, grp, ifaddr,
10989 				    &ifindex, fmode, src, first_mp);
10990 			}
10991 			if (error != 0) {
10992 				/*
10993 				 * EINPROGRESS is a soft error, needs retry
10994 				 * so don't make *outlenp zero.
10995 				 */
10996 				if (error != EINPROGRESS)
10997 					*outlenp = 0;
10998 				return (error);
10999 			}
11000 			/* OK return - copy input buffer into output buffer */
11001 			if (invalp != outvalp) {
11002 				bcopy(invalp, outvalp, inlen);
11003 			}
11004 			*outlenp = inlen;
11005 			return (0);
11006 		}
11007 		case IP_SEC_OPT:
11008 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11009 			if (error != 0) {
11010 				*outlenp = 0;
11011 				return (error);
11012 			}
11013 			break;
11014 		case IP_HDRINCL:
11015 		case IP_OPTIONS:
11016 		case T_IP_OPTIONS:
11017 		case IP_TOS:
11018 		case T_IP_TOS:
11019 		case IP_TTL:
11020 		case IP_RECVDSTADDR:
11021 		case IP_RECVOPTS:
11022 			/* OK return - copy input buffer into output buffer */
11023 			if (invalp != outvalp) {
11024 				/* don't trust bcopy for identical src/dst */
11025 				bcopy(invalp, outvalp, inlen);
11026 			}
11027 			*outlenp = inlen;
11028 			return (0);
11029 		case IP_RECVIF:
11030 			/* Retrieve the inbound interface index */
11031 			if (!checkonly) {
11032 				mutex_enter(&connp->conn_lock);
11033 				connp->conn_recvif = *i1 ? 1 : 0;
11034 				mutex_exit(&connp->conn_lock);
11035 			}
11036 			break;	/* goto sizeof (int) option return */
11037 		case IP_RECVPKTINFO:
11038 			if (!checkonly) {
11039 				mutex_enter(&connp->conn_lock);
11040 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11041 				mutex_exit(&connp->conn_lock);
11042 			}
11043 			break;	/* goto sizeof (int) option return */
11044 		case IP_RECVSLLA:
11045 			/* Retrieve the source link layer address */
11046 			if (!checkonly) {
11047 				mutex_enter(&connp->conn_lock);
11048 				connp->conn_recvslla = *i1 ? 1 : 0;
11049 				mutex_exit(&connp->conn_lock);
11050 			}
11051 			break;	/* goto sizeof (int) option return */
11052 		case MRT_INIT:
11053 		case MRT_DONE:
11054 		case MRT_ADD_VIF:
11055 		case MRT_DEL_VIF:
11056 		case MRT_ADD_MFC:
11057 		case MRT_DEL_MFC:
11058 		case MRT_ASSERT:
11059 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
11060 				*outlenp = 0;
11061 				return (error);
11062 			}
11063 			error = ip_mrouter_set((int)name, q, checkonly,
11064 			    (uchar_t *)invalp, inlen, first_mp);
11065 			if (error) {
11066 				*outlenp = 0;
11067 				return (error);
11068 			}
11069 			/* OK return - copy input buffer into output buffer */
11070 			if (invalp != outvalp) {
11071 				/* don't trust bcopy for identical src/dst */
11072 				bcopy(invalp, outvalp, inlen);
11073 			}
11074 			*outlenp = inlen;
11075 			return (0);
11076 		case IP_BOUND_IF:
11077 		case IP_DHCPINIT_IF:
11078 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11079 			    level, name, first_mp);
11080 			if (error != 0)
11081 				return (error);
11082 			break; 		/* goto sizeof (int) option return */
11083 
11084 		case IP_UNSPEC_SRC:
11085 			/* Allow sending with a zero source address */
11086 			if (!checkonly) {
11087 				mutex_enter(&connp->conn_lock);
11088 				connp->conn_unspec_src = *i1 ? 1 : 0;
11089 				mutex_exit(&connp->conn_lock);
11090 			}
11091 			break;	/* goto sizeof (int) option return */
11092 		default:
11093 			/*
11094 			 * "soft" error (negative)
11095 			 * option not handled at this level
11096 			 * Note: Do not modify *outlenp
11097 			 */
11098 			return (-EINVAL);
11099 		}
11100 		break;
11101 	case IPPROTO_IPV6:
11102 		switch (name) {
11103 		case IPV6_BOUND_IF:
11104 		case IPV6_BOUND_PIF:
11105 		case IPV6_DONTFAILOVER_IF:
11106 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11107 			    level, name, first_mp);
11108 			if (error != 0)
11109 				return (error);
11110 			break; 		/* goto sizeof (int) option return */
11111 
11112 		case IPV6_MULTICAST_IF:
11113 			/*
11114 			 * The only possible errors are EINPROGRESS and
11115 			 * EINVAL. EINPROGRESS will be restarted and is not
11116 			 * a hard error. We call this option on both V4 and V6
11117 			 * If both return EINVAL, then this call returns
11118 			 * EINVAL. If at least one of them succeeds we
11119 			 * return success.
11120 			 */
11121 			found = B_FALSE;
11122 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11123 			    level, name, first_mp);
11124 			if (error == EINPROGRESS)
11125 				return (error);
11126 			if (error == 0)
11127 				found = B_TRUE;
11128 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11129 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11130 			if (error == 0)
11131 				found = B_TRUE;
11132 			if (!found)
11133 				return (error);
11134 			break; 		/* goto sizeof (int) option return */
11135 
11136 		case IPV6_MULTICAST_HOPS:
11137 			/* Recorded in transport above IP */
11138 			break;	/* goto sizeof (int) option return */
11139 		case IPV6_MULTICAST_LOOP:
11140 			if (!checkonly) {
11141 				mutex_enter(&connp->conn_lock);
11142 				connp->conn_multicast_loop = *i1;
11143 				mutex_exit(&connp->conn_lock);
11144 			}
11145 			break;	/* goto sizeof (int) option return */
11146 		case IPV6_JOIN_GROUP:
11147 		case MCAST_JOIN_GROUP:
11148 		case IPV6_LEAVE_GROUP:
11149 		case MCAST_LEAVE_GROUP: {
11150 			struct ipv6_mreq *ip_mreqp;
11151 			struct group_req *greqp;
11152 			ire_t *ire;
11153 			boolean_t done = B_FALSE;
11154 			in6_addr_t groupv6;
11155 			uint32_t ifindex;
11156 			boolean_t mcast_opt = B_TRUE;
11157 			mcast_record_t fmode;
11158 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11159 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11160 
11161 			switch (name) {
11162 			case IPV6_JOIN_GROUP:
11163 				mcast_opt = B_FALSE;
11164 				/* FALLTHRU */
11165 			case MCAST_JOIN_GROUP:
11166 				fmode = MODE_IS_EXCLUDE;
11167 				optfn = ip_opt_add_group_v6;
11168 				break;
11169 
11170 			case IPV6_LEAVE_GROUP:
11171 				mcast_opt = B_FALSE;
11172 				/* FALLTHRU */
11173 			case MCAST_LEAVE_GROUP:
11174 				fmode = MODE_IS_INCLUDE;
11175 				optfn = ip_opt_delete_group_v6;
11176 				break;
11177 			}
11178 
11179 			if (mcast_opt) {
11180 				struct sockaddr_in *sin;
11181 				struct sockaddr_in6 *sin6;
11182 				greqp = (struct group_req *)i1;
11183 				if (greqp->gr_group.ss_family == AF_INET) {
11184 					sin = (struct sockaddr_in *)
11185 					    &(greqp->gr_group);
11186 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11187 					    &groupv6);
11188 				} else {
11189 					sin6 = (struct sockaddr_in6 *)
11190 					    &(greqp->gr_group);
11191 					groupv6 = sin6->sin6_addr;
11192 				}
11193 				ifindex = greqp->gr_interface;
11194 			} else {
11195 				ip_mreqp = (struct ipv6_mreq *)i1;
11196 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11197 				ifindex = ip_mreqp->ipv6mr_interface;
11198 			}
11199 			/*
11200 			 * In the multirouting case, we need to replicate
11201 			 * the request on all interfaces that will take part
11202 			 * in replication.  We do so because multirouting is
11203 			 * reflective, thus we will probably receive multi-
11204 			 * casts on those interfaces.
11205 			 * The ip_multirt_apply_membership_v6() succeeds if
11206 			 * the operation succeeds on at least one interface.
11207 			 */
11208 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11209 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11210 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11211 			if (ire != NULL) {
11212 				if (ire->ire_flags & RTF_MULTIRT) {
11213 					error = ip_multirt_apply_membership_v6(
11214 					    optfn, ire, connp, checkonly,
11215 					    &groupv6, fmode, &ipv6_all_zeros,
11216 					    first_mp);
11217 					done = B_TRUE;
11218 				}
11219 				ire_refrele(ire);
11220 			}
11221 			if (!done) {
11222 				error = optfn(connp, checkonly, &groupv6,
11223 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11224 			}
11225 			if (error) {
11226 				/*
11227 				 * EINPROGRESS is a soft error, needs retry
11228 				 * so don't make *outlenp zero.
11229 				 */
11230 				if (error != EINPROGRESS)
11231 					*outlenp = 0;
11232 				return (error);
11233 			}
11234 			/* OK return - copy input buffer into output buffer */
11235 			if (invalp != outvalp) {
11236 				/* don't trust bcopy for identical src/dst */
11237 				bcopy(invalp, outvalp, inlen);
11238 			}
11239 			*outlenp = inlen;
11240 			return (0);
11241 		}
11242 		case MCAST_BLOCK_SOURCE:
11243 		case MCAST_UNBLOCK_SOURCE:
11244 		case MCAST_JOIN_SOURCE_GROUP:
11245 		case MCAST_LEAVE_SOURCE_GROUP: {
11246 			struct group_source_req *gsreqp;
11247 			in6_addr_t v6grp, v6src;
11248 			uint32_t ifindex;
11249 			mcast_record_t fmode;
11250 			ire_t *ire;
11251 			boolean_t done = B_FALSE;
11252 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11253 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11254 
11255 			switch (name) {
11256 			case MCAST_BLOCK_SOURCE:
11257 				fmode = MODE_IS_EXCLUDE;
11258 				optfn = ip_opt_add_group_v6;
11259 				break;
11260 			case MCAST_UNBLOCK_SOURCE:
11261 				fmode = MODE_IS_EXCLUDE;
11262 				optfn = ip_opt_delete_group_v6;
11263 				break;
11264 			case MCAST_JOIN_SOURCE_GROUP:
11265 				fmode = MODE_IS_INCLUDE;
11266 				optfn = ip_opt_add_group_v6;
11267 				break;
11268 			case MCAST_LEAVE_SOURCE_GROUP:
11269 				fmode = MODE_IS_INCLUDE;
11270 				optfn = ip_opt_delete_group_v6;
11271 				break;
11272 			}
11273 
11274 			gsreqp = (struct group_source_req *)i1;
11275 			ifindex = gsreqp->gsr_interface;
11276 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11277 				struct sockaddr_in *s;
11278 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11279 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11280 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11281 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11282 			} else {
11283 				struct sockaddr_in6 *s6;
11284 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11285 				v6grp = s6->sin6_addr;
11286 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11287 				v6src = s6->sin6_addr;
11288 			}
11289 
11290 			/*
11291 			 * In the multirouting case, we need to replicate
11292 			 * the request as noted in the mcast cases above.
11293 			 */
11294 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11295 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11296 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11297 			if (ire != NULL) {
11298 				if (ire->ire_flags & RTF_MULTIRT) {
11299 					error = ip_multirt_apply_membership_v6(
11300 					    optfn, ire, connp, checkonly,
11301 					    &v6grp, fmode, &v6src, first_mp);
11302 					done = B_TRUE;
11303 				}
11304 				ire_refrele(ire);
11305 			}
11306 			if (!done) {
11307 				error = optfn(connp, checkonly, &v6grp,
11308 				    ifindex, fmode, &v6src, first_mp);
11309 			}
11310 			if (error != 0) {
11311 				/*
11312 				 * EINPROGRESS is a soft error, needs retry
11313 				 * so don't make *outlenp zero.
11314 				 */
11315 				if (error != EINPROGRESS)
11316 					*outlenp = 0;
11317 				return (error);
11318 			}
11319 			/* OK return - copy input buffer into output buffer */
11320 			if (invalp != outvalp) {
11321 				bcopy(invalp, outvalp, inlen);
11322 			}
11323 			*outlenp = inlen;
11324 			return (0);
11325 		}
11326 		case IPV6_UNICAST_HOPS:
11327 			/* Recorded in transport above IP */
11328 			break;	/* goto sizeof (int) option return */
11329 		case IPV6_UNSPEC_SRC:
11330 			/* Allow sending with a zero source address */
11331 			if (!checkonly) {
11332 				mutex_enter(&connp->conn_lock);
11333 				connp->conn_unspec_src = *i1 ? 1 : 0;
11334 				mutex_exit(&connp->conn_lock);
11335 			}
11336 			break;	/* goto sizeof (int) option return */
11337 		case IPV6_RECVPKTINFO:
11338 			if (!checkonly) {
11339 				mutex_enter(&connp->conn_lock);
11340 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11341 				mutex_exit(&connp->conn_lock);
11342 			}
11343 			break;	/* goto sizeof (int) option return */
11344 		case IPV6_RECVTCLASS:
11345 			if (!checkonly) {
11346 				if (*i1 < 0 || *i1 > 1) {
11347 					return (EINVAL);
11348 				}
11349 				mutex_enter(&connp->conn_lock);
11350 				connp->conn_ipv6_recvtclass = *i1;
11351 				mutex_exit(&connp->conn_lock);
11352 			}
11353 			break;
11354 		case IPV6_RECVPATHMTU:
11355 			if (!checkonly) {
11356 				if (*i1 < 0 || *i1 > 1) {
11357 					return (EINVAL);
11358 				}
11359 				mutex_enter(&connp->conn_lock);
11360 				connp->conn_ipv6_recvpathmtu = *i1;
11361 				mutex_exit(&connp->conn_lock);
11362 			}
11363 			break;
11364 		case IPV6_RECVHOPLIMIT:
11365 			if (!checkonly) {
11366 				mutex_enter(&connp->conn_lock);
11367 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11368 				mutex_exit(&connp->conn_lock);
11369 			}
11370 			break;	/* goto sizeof (int) option return */
11371 		case IPV6_RECVHOPOPTS:
11372 			if (!checkonly) {
11373 				mutex_enter(&connp->conn_lock);
11374 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11375 				mutex_exit(&connp->conn_lock);
11376 			}
11377 			break;	/* goto sizeof (int) option return */
11378 		case IPV6_RECVDSTOPTS:
11379 			if (!checkonly) {
11380 				mutex_enter(&connp->conn_lock);
11381 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11382 				mutex_exit(&connp->conn_lock);
11383 			}
11384 			break;	/* goto sizeof (int) option return */
11385 		case IPV6_RECVRTHDR:
11386 			if (!checkonly) {
11387 				mutex_enter(&connp->conn_lock);
11388 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11389 				mutex_exit(&connp->conn_lock);
11390 			}
11391 			break;	/* goto sizeof (int) option return */
11392 		case IPV6_RECVRTHDRDSTOPTS:
11393 			if (!checkonly) {
11394 				mutex_enter(&connp->conn_lock);
11395 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11396 				mutex_exit(&connp->conn_lock);
11397 			}
11398 			break;	/* goto sizeof (int) option return */
11399 		case IPV6_PKTINFO:
11400 			if (inlen == 0)
11401 				return (-EINVAL);	/* clearing option */
11402 			error = ip6_set_pktinfo(cr, connp,
11403 			    (struct in6_pktinfo *)invalp, first_mp);
11404 			if (error != 0)
11405 				*outlenp = 0;
11406 			else
11407 				*outlenp = inlen;
11408 			return (error);
11409 		case IPV6_NEXTHOP: {
11410 			struct sockaddr_in6 *sin6;
11411 
11412 			/* Verify that the nexthop is reachable */
11413 			if (inlen == 0)
11414 				return (-EINVAL);	/* clearing option */
11415 
11416 			sin6 = (struct sockaddr_in6 *)invalp;
11417 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11418 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11419 			    NULL, MATCH_IRE_DEFAULT, ipst);
11420 
11421 			if (ire == NULL) {
11422 				*outlenp = 0;
11423 				return (EHOSTUNREACH);
11424 			}
11425 			ire_refrele(ire);
11426 			return (-EINVAL);
11427 		}
11428 		case IPV6_SEC_OPT:
11429 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11430 			if (error != 0) {
11431 				*outlenp = 0;
11432 				return (error);
11433 			}
11434 			break;
11435 		case IPV6_SRC_PREFERENCES: {
11436 			/*
11437 			 * This is implemented strictly in the ip module
11438 			 * (here and in tcp_opt_*() to accomodate tcp
11439 			 * sockets).  Modules above ip pass this option
11440 			 * down here since ip is the only one that needs to
11441 			 * be aware of source address preferences.
11442 			 *
11443 			 * This socket option only affects connected
11444 			 * sockets that haven't already bound to a specific
11445 			 * IPv6 address.  In other words, sockets that
11446 			 * don't call bind() with an address other than the
11447 			 * unspecified address and that call connect().
11448 			 * ip_bind_connected_v6() passes these preferences
11449 			 * to the ipif_select_source_v6() function.
11450 			 */
11451 			if (inlen != sizeof (uint32_t))
11452 				return (EINVAL);
11453 			error = ip6_set_src_preferences(connp,
11454 			    *(uint32_t *)invalp);
11455 			if (error != 0) {
11456 				*outlenp = 0;
11457 				return (error);
11458 			} else {
11459 				*outlenp = sizeof (uint32_t);
11460 			}
11461 			break;
11462 		}
11463 		case IPV6_V6ONLY:
11464 			if (*i1 < 0 || *i1 > 1) {
11465 				return (EINVAL);
11466 			}
11467 			mutex_enter(&connp->conn_lock);
11468 			connp->conn_ipv6_v6only = *i1;
11469 			mutex_exit(&connp->conn_lock);
11470 			break;
11471 		default:
11472 			return (-EINVAL);
11473 		}
11474 		break;
11475 	default:
11476 		/*
11477 		 * "soft" error (negative)
11478 		 * option not handled at this level
11479 		 * Note: Do not modify *outlenp
11480 		 */
11481 		return (-EINVAL);
11482 	}
11483 	/*
11484 	 * Common case of return from an option that is sizeof (int)
11485 	 */
11486 	*(int *)outvalp = *i1;
11487 	*outlenp = sizeof (int);
11488 	return (0);
11489 }
11490 
11491 /*
11492  * This routine gets default values of certain options whose default
11493  * values are maintained by protocol specific code
11494  */
11495 /* ARGSUSED */
11496 int
11497 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11498 {
11499 	int *i1 = (int *)ptr;
11500 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11501 
11502 	switch (level) {
11503 	case IPPROTO_IP:
11504 		switch (name) {
11505 		case IP_MULTICAST_TTL:
11506 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11507 			return (sizeof (uchar_t));
11508 		case IP_MULTICAST_LOOP:
11509 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11510 			return (sizeof (uchar_t));
11511 		default:
11512 			return (-1);
11513 		}
11514 	case IPPROTO_IPV6:
11515 		switch (name) {
11516 		case IPV6_UNICAST_HOPS:
11517 			*i1 = ipst->ips_ipv6_def_hops;
11518 			return (sizeof (int));
11519 		case IPV6_MULTICAST_HOPS:
11520 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11521 			return (sizeof (int));
11522 		case IPV6_MULTICAST_LOOP:
11523 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11524 			return (sizeof (int));
11525 		case IPV6_V6ONLY:
11526 			*i1 = 1;
11527 			return (sizeof (int));
11528 		default:
11529 			return (-1);
11530 		}
11531 	default:
11532 		return (-1);
11533 	}
11534 	/* NOTREACHED */
11535 }
11536 
11537 /*
11538  * Given a destination address and a pointer to where to put the information
11539  * this routine fills in the mtuinfo.
11540  */
11541 int
11542 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11543     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11544 {
11545 	ire_t *ire;
11546 	ip_stack_t	*ipst = ns->netstack_ip;
11547 
11548 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11549 		return (-1);
11550 
11551 	bzero(mtuinfo, sizeof (*mtuinfo));
11552 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11553 	mtuinfo->ip6m_addr.sin6_port = port;
11554 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11555 
11556 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11557 	if (ire != NULL) {
11558 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11559 		ire_refrele(ire);
11560 	} else {
11561 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11562 	}
11563 	return (sizeof (struct ip6_mtuinfo));
11564 }
11565 
11566 /*
11567  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11568  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11569  * isn't.  This doesn't matter as the error checking is done properly for the
11570  * other MRT options coming in through ip_opt_set.
11571  */
11572 int
11573 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11574 {
11575 	conn_t		*connp = Q_TO_CONN(q);
11576 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11577 
11578 	switch (level) {
11579 	case IPPROTO_IP:
11580 		switch (name) {
11581 		case MRT_VERSION:
11582 		case MRT_ASSERT:
11583 			(void) ip_mrouter_get(name, q, ptr);
11584 			return (sizeof (int));
11585 		case IP_SEC_OPT:
11586 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11587 		case IP_NEXTHOP:
11588 			if (connp->conn_nexthop_set) {
11589 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11590 				return (sizeof (ipaddr_t));
11591 			} else
11592 				return (0);
11593 		case IP_RECVPKTINFO:
11594 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11595 			return (sizeof (int));
11596 		default:
11597 			break;
11598 		}
11599 		break;
11600 	case IPPROTO_IPV6:
11601 		switch (name) {
11602 		case IPV6_SEC_OPT:
11603 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11604 		case IPV6_SRC_PREFERENCES: {
11605 			return (ip6_get_src_preferences(connp,
11606 			    (uint32_t *)ptr));
11607 		}
11608 		case IPV6_V6ONLY:
11609 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11610 			return (sizeof (int));
11611 		case IPV6_PATHMTU:
11612 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11613 			    (struct ip6_mtuinfo *)ptr, connp->conn_netstack));
11614 		default:
11615 			break;
11616 		}
11617 		break;
11618 	default:
11619 		break;
11620 	}
11621 	return (-1);
11622 }
11623 
11624 /* Named Dispatch routine to get a current value out of our parameter table. */
11625 /* ARGSUSED */
11626 static int
11627 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11628 {
11629 	ipparam_t *ippa = (ipparam_t *)cp;
11630 
11631 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11632 	return (0);
11633 }
11634 
11635 /* ARGSUSED */
11636 static int
11637 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11638 {
11639 
11640 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11641 	return (0);
11642 }
11643 
11644 /*
11645  * Set ip{,6}_forwarding values.  This means walking through all of the
11646  * ill's and toggling their forwarding values.
11647  */
11648 /* ARGSUSED */
11649 static int
11650 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11651 {
11652 	long new_value;
11653 	int *forwarding_value = (int *)cp;
11654 	ill_t *ill;
11655 	boolean_t isv6;
11656 	ill_walk_context_t ctx;
11657 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11658 
11659 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11660 
11661 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11662 	    new_value < 0 || new_value > 1) {
11663 		return (EINVAL);
11664 	}
11665 
11666 	*forwarding_value = new_value;
11667 
11668 	/*
11669 	 * Regardless of the current value of ip_forwarding, set all per-ill
11670 	 * values of ip_forwarding to the value being set.
11671 	 *
11672 	 * Bring all the ill's up to date with the new global value.
11673 	 */
11674 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11675 
11676 	if (isv6)
11677 		ill = ILL_START_WALK_V6(&ctx, ipst);
11678 	else
11679 		ill = ILL_START_WALK_V4(&ctx, ipst);
11680 
11681 	for (; ill != NULL; ill = ill_next(&ctx, ill))
11682 		(void) ill_forward_set(ill, new_value != 0);
11683 
11684 	rw_exit(&ipst->ips_ill_g_lock);
11685 	return (0);
11686 }
11687 
11688 /*
11689  * Walk through the param array specified registering each element with the
11690  * Named Dispatch handler. This is called only during init. So it is ok
11691  * not to acquire any locks
11692  */
11693 static boolean_t
11694 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11695     ipndp_t *ipnd, size_t ipnd_cnt)
11696 {
11697 	for (; ippa_cnt-- > 0; ippa++) {
11698 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11699 			if (!nd_load(ndp, ippa->ip_param_name,
11700 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11701 				nd_free(ndp);
11702 				return (B_FALSE);
11703 			}
11704 		}
11705 	}
11706 
11707 	for (; ipnd_cnt-- > 0; ipnd++) {
11708 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11709 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11710 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11711 			    ipnd->ip_ndp_data)) {
11712 				nd_free(ndp);
11713 				return (B_FALSE);
11714 			}
11715 		}
11716 	}
11717 
11718 	return (B_TRUE);
11719 }
11720 
11721 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11722 /* ARGSUSED */
11723 static int
11724 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11725 {
11726 	long		new_value;
11727 	ipparam_t	*ippa = (ipparam_t *)cp;
11728 
11729 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11730 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11731 		return (EINVAL);
11732 	}
11733 	ippa->ip_param_value = new_value;
11734 	return (0);
11735 }
11736 
11737 /*
11738  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11739  * When an ipf is passed here for the first time, if
11740  * we already have in-order fragments on the queue, we convert from the fast-
11741  * path reassembly scheme to the hard-case scheme.  From then on, additional
11742  * fragments are reassembled here.  We keep track of the start and end offsets
11743  * of each piece, and the number of holes in the chain.  When the hole count
11744  * goes to zero, we are done!
11745  *
11746  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11747  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11748  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11749  * after the call to ip_reassemble().
11750  */
11751 int
11752 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11753     size_t msg_len)
11754 {
11755 	uint_t	end;
11756 	mblk_t	*next_mp;
11757 	mblk_t	*mp1;
11758 	uint_t	offset;
11759 	boolean_t incr_dups = B_TRUE;
11760 	boolean_t offset_zero_seen = B_FALSE;
11761 	boolean_t pkt_boundary_checked = B_FALSE;
11762 
11763 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11764 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11765 
11766 	/* Add in byte count */
11767 	ipf->ipf_count += msg_len;
11768 	if (ipf->ipf_end) {
11769 		/*
11770 		 * We were part way through in-order reassembly, but now there
11771 		 * is a hole.  We walk through messages already queued, and
11772 		 * mark them for hard case reassembly.  We know that up till
11773 		 * now they were in order starting from offset zero.
11774 		 */
11775 		offset = 0;
11776 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11777 			IP_REASS_SET_START(mp1, offset);
11778 			if (offset == 0) {
11779 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11780 				offset = -ipf->ipf_nf_hdr_len;
11781 			}
11782 			offset += mp1->b_wptr - mp1->b_rptr;
11783 			IP_REASS_SET_END(mp1, offset);
11784 		}
11785 		/* One hole at the end. */
11786 		ipf->ipf_hole_cnt = 1;
11787 		/* Brand it as a hard case, forever. */
11788 		ipf->ipf_end = 0;
11789 	}
11790 	/* Walk through all the new pieces. */
11791 	do {
11792 		end = start + (mp->b_wptr - mp->b_rptr);
11793 		/*
11794 		 * If start is 0, decrease 'end' only for the first mblk of
11795 		 * the fragment. Otherwise 'end' can get wrong value in the
11796 		 * second pass of the loop if first mblk is exactly the
11797 		 * size of ipf_nf_hdr_len.
11798 		 */
11799 		if (start == 0 && !offset_zero_seen) {
11800 			/* First segment */
11801 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11802 			end -= ipf->ipf_nf_hdr_len;
11803 			offset_zero_seen = B_TRUE;
11804 		}
11805 		next_mp = mp->b_cont;
11806 		/*
11807 		 * We are checking to see if there is any interesing data
11808 		 * to process.  If there isn't and the mblk isn't the
11809 		 * one which carries the unfragmentable header then we
11810 		 * drop it.  It's possible to have just the unfragmentable
11811 		 * header come through without any data.  That needs to be
11812 		 * saved.
11813 		 *
11814 		 * If the assert at the top of this function holds then the
11815 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11816 		 * is infrequently traveled enough that the test is left in
11817 		 * to protect against future code changes which break that
11818 		 * invariant.
11819 		 */
11820 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11821 			/* Empty.  Blast it. */
11822 			IP_REASS_SET_START(mp, 0);
11823 			IP_REASS_SET_END(mp, 0);
11824 			/*
11825 			 * If the ipf points to the mblk we are about to free,
11826 			 * update ipf to point to the next mblk (or NULL
11827 			 * if none).
11828 			 */
11829 			if (ipf->ipf_mp->b_cont == mp)
11830 				ipf->ipf_mp->b_cont = next_mp;
11831 			freeb(mp);
11832 			continue;
11833 		}
11834 		mp->b_cont = NULL;
11835 		IP_REASS_SET_START(mp, start);
11836 		IP_REASS_SET_END(mp, end);
11837 		if (!ipf->ipf_tail_mp) {
11838 			ipf->ipf_tail_mp = mp;
11839 			ipf->ipf_mp->b_cont = mp;
11840 			if (start == 0 || !more) {
11841 				ipf->ipf_hole_cnt = 1;
11842 				/*
11843 				 * if the first fragment comes in more than one
11844 				 * mblk, this loop will be executed for each
11845 				 * mblk. Need to adjust hole count so exiting
11846 				 * this routine will leave hole count at 1.
11847 				 */
11848 				if (next_mp)
11849 					ipf->ipf_hole_cnt++;
11850 			} else
11851 				ipf->ipf_hole_cnt = 2;
11852 			continue;
11853 		} else if (ipf->ipf_last_frag_seen && !more &&
11854 		    !pkt_boundary_checked) {
11855 			/*
11856 			 * We check datagram boundary only if this fragment
11857 			 * claims to be the last fragment and we have seen a
11858 			 * last fragment in the past too. We do this only
11859 			 * once for a given fragment.
11860 			 *
11861 			 * start cannot be 0 here as fragments with start=0
11862 			 * and MF=0 gets handled as a complete packet. These
11863 			 * fragments should not reach here.
11864 			 */
11865 
11866 			if (start + msgdsize(mp) !=
11867 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11868 				/*
11869 				 * We have two fragments both of which claim
11870 				 * to be the last fragment but gives conflicting
11871 				 * information about the whole datagram size.
11872 				 * Something fishy is going on. Drop the
11873 				 * fragment and free up the reassembly list.
11874 				 */
11875 				return (IP_REASS_FAILED);
11876 			}
11877 
11878 			/*
11879 			 * We shouldn't come to this code block again for this
11880 			 * particular fragment.
11881 			 */
11882 			pkt_boundary_checked = B_TRUE;
11883 		}
11884 
11885 		/* New stuff at or beyond tail? */
11886 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11887 		if (start >= offset) {
11888 			if (ipf->ipf_last_frag_seen) {
11889 				/* current fragment is beyond last fragment */
11890 				return (IP_REASS_FAILED);
11891 			}
11892 			/* Link it on end. */
11893 			ipf->ipf_tail_mp->b_cont = mp;
11894 			ipf->ipf_tail_mp = mp;
11895 			if (more) {
11896 				if (start != offset)
11897 					ipf->ipf_hole_cnt++;
11898 			} else if (start == offset && next_mp == NULL)
11899 					ipf->ipf_hole_cnt--;
11900 			continue;
11901 		}
11902 		mp1 = ipf->ipf_mp->b_cont;
11903 		offset = IP_REASS_START(mp1);
11904 		/* New stuff at the front? */
11905 		if (start < offset) {
11906 			if (start == 0) {
11907 				if (end >= offset) {
11908 					/* Nailed the hole at the begining. */
11909 					ipf->ipf_hole_cnt--;
11910 				}
11911 			} else if (end < offset) {
11912 				/*
11913 				 * A hole, stuff, and a hole where there used
11914 				 * to be just a hole.
11915 				 */
11916 				ipf->ipf_hole_cnt++;
11917 			}
11918 			mp->b_cont = mp1;
11919 			/* Check for overlap. */
11920 			while (end > offset) {
11921 				if (end < IP_REASS_END(mp1)) {
11922 					mp->b_wptr -= end - offset;
11923 					IP_REASS_SET_END(mp, offset);
11924 					BUMP_MIB(ill->ill_ip_mib,
11925 					    ipIfStatsReasmPartDups);
11926 					break;
11927 				}
11928 				/* Did we cover another hole? */
11929 				if ((mp1->b_cont &&
11930 				    IP_REASS_END(mp1) !=
11931 				    IP_REASS_START(mp1->b_cont) &&
11932 				    end >= IP_REASS_START(mp1->b_cont)) ||
11933 				    (!ipf->ipf_last_frag_seen && !more)) {
11934 					ipf->ipf_hole_cnt--;
11935 				}
11936 				/* Clip out mp1. */
11937 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11938 					/*
11939 					 * After clipping out mp1, this guy
11940 					 * is now hanging off the end.
11941 					 */
11942 					ipf->ipf_tail_mp = mp;
11943 				}
11944 				IP_REASS_SET_START(mp1, 0);
11945 				IP_REASS_SET_END(mp1, 0);
11946 				/* Subtract byte count */
11947 				ipf->ipf_count -= mp1->b_datap->db_lim -
11948 				    mp1->b_datap->db_base;
11949 				freeb(mp1);
11950 				BUMP_MIB(ill->ill_ip_mib,
11951 				    ipIfStatsReasmPartDups);
11952 				mp1 = mp->b_cont;
11953 				if (!mp1)
11954 					break;
11955 				offset = IP_REASS_START(mp1);
11956 			}
11957 			ipf->ipf_mp->b_cont = mp;
11958 			continue;
11959 		}
11960 		/*
11961 		 * The new piece starts somewhere between the start of the head
11962 		 * and before the end of the tail.
11963 		 */
11964 		for (; mp1; mp1 = mp1->b_cont) {
11965 			offset = IP_REASS_END(mp1);
11966 			if (start < offset) {
11967 				if (end <= offset) {
11968 					/* Nothing new. */
11969 					IP_REASS_SET_START(mp, 0);
11970 					IP_REASS_SET_END(mp, 0);
11971 					/* Subtract byte count */
11972 					ipf->ipf_count -= mp->b_datap->db_lim -
11973 					    mp->b_datap->db_base;
11974 					if (incr_dups) {
11975 						ipf->ipf_num_dups++;
11976 						incr_dups = B_FALSE;
11977 					}
11978 					freeb(mp);
11979 					BUMP_MIB(ill->ill_ip_mib,
11980 					    ipIfStatsReasmDuplicates);
11981 					break;
11982 				}
11983 				/*
11984 				 * Trim redundant stuff off beginning of new
11985 				 * piece.
11986 				 */
11987 				IP_REASS_SET_START(mp, offset);
11988 				mp->b_rptr += offset - start;
11989 				BUMP_MIB(ill->ill_ip_mib,
11990 				    ipIfStatsReasmPartDups);
11991 				start = offset;
11992 				if (!mp1->b_cont) {
11993 					/*
11994 					 * After trimming, this guy is now
11995 					 * hanging off the end.
11996 					 */
11997 					mp1->b_cont = mp;
11998 					ipf->ipf_tail_mp = mp;
11999 					if (!more) {
12000 						ipf->ipf_hole_cnt--;
12001 					}
12002 					break;
12003 				}
12004 			}
12005 			if (start >= IP_REASS_START(mp1->b_cont))
12006 				continue;
12007 			/* Fill a hole */
12008 			if (start > offset)
12009 				ipf->ipf_hole_cnt++;
12010 			mp->b_cont = mp1->b_cont;
12011 			mp1->b_cont = mp;
12012 			mp1 = mp->b_cont;
12013 			offset = IP_REASS_START(mp1);
12014 			if (end >= offset) {
12015 				ipf->ipf_hole_cnt--;
12016 				/* Check for overlap. */
12017 				while (end > offset) {
12018 					if (end < IP_REASS_END(mp1)) {
12019 						mp->b_wptr -= end - offset;
12020 						IP_REASS_SET_END(mp, offset);
12021 						/*
12022 						 * TODO we might bump
12023 						 * this up twice if there is
12024 						 * overlap at both ends.
12025 						 */
12026 						BUMP_MIB(ill->ill_ip_mib,
12027 						    ipIfStatsReasmPartDups);
12028 						break;
12029 					}
12030 					/* Did we cover another hole? */
12031 					if ((mp1->b_cont &&
12032 					    IP_REASS_END(mp1)
12033 					    != IP_REASS_START(mp1->b_cont) &&
12034 					    end >=
12035 					    IP_REASS_START(mp1->b_cont)) ||
12036 					    (!ipf->ipf_last_frag_seen &&
12037 					    !more)) {
12038 						ipf->ipf_hole_cnt--;
12039 					}
12040 					/* Clip out mp1. */
12041 					if ((mp->b_cont = mp1->b_cont) ==
12042 					    NULL) {
12043 						/*
12044 						 * After clipping out mp1,
12045 						 * this guy is now hanging
12046 						 * off the end.
12047 						 */
12048 						ipf->ipf_tail_mp = mp;
12049 					}
12050 					IP_REASS_SET_START(mp1, 0);
12051 					IP_REASS_SET_END(mp1, 0);
12052 					/* Subtract byte count */
12053 					ipf->ipf_count -=
12054 					    mp1->b_datap->db_lim -
12055 					    mp1->b_datap->db_base;
12056 					freeb(mp1);
12057 					BUMP_MIB(ill->ill_ip_mib,
12058 					    ipIfStatsReasmPartDups);
12059 					mp1 = mp->b_cont;
12060 					if (!mp1)
12061 						break;
12062 					offset = IP_REASS_START(mp1);
12063 				}
12064 			}
12065 			break;
12066 		}
12067 	} while (start = end, mp = next_mp);
12068 
12069 	/* Fragment just processed could be the last one. Remember this fact */
12070 	if (!more)
12071 		ipf->ipf_last_frag_seen = B_TRUE;
12072 
12073 	/* Still got holes? */
12074 	if (ipf->ipf_hole_cnt)
12075 		return (IP_REASS_PARTIAL);
12076 	/* Clean up overloaded fields to avoid upstream disasters. */
12077 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12078 		IP_REASS_SET_START(mp1, 0);
12079 		IP_REASS_SET_END(mp1, 0);
12080 	}
12081 	return (IP_REASS_COMPLETE);
12082 }
12083 
12084 /*
12085  * ipsec processing for the fast path, used for input UDP Packets
12086  * Returns true if ready for passup to UDP.
12087  * Return false if packet is not passable to UDP (e.g. it failed IPsec policy,
12088  * was an ESP-in-UDP packet, etc.).
12089  */
12090 static boolean_t
12091 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
12092     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present, ire_t *ire)
12093 {
12094 	uint32_t	ill_index;
12095 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
12096 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
12097 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12098 	udp_t		*udp = connp->conn_udp;
12099 
12100 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12101 	/* The ill_index of the incoming ILL */
12102 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
12103 
12104 	/* pass packet up to the transport */
12105 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
12106 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
12107 		    NULL, mctl_present);
12108 		if (*first_mpp == NULL) {
12109 			return (B_FALSE);
12110 		}
12111 	}
12112 
12113 	/* Initiate IPPF processing for fastpath UDP */
12114 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12115 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
12116 		if (*mpp == NULL) {
12117 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
12118 			    "deferred/dropped during IPPF processing\n"));
12119 			return (B_FALSE);
12120 		}
12121 	}
12122 	/*
12123 	 * Remove 0-spi if it's 0, or move everything behind
12124 	 * the UDP header over it and forward to ESP via
12125 	 * ip_proto_input().
12126 	 */
12127 	if (udp->udp_nat_t_endpoint) {
12128 		if (mctl_present) {
12129 			/* mctl_present *shouldn't* happen. */
12130 			ip_drop_packet(*first_mpp, B_TRUE, NULL,
12131 			    NULL, DROPPER(ipss, ipds_esp_nat_t_ipsec),
12132 			    &ipss->ipsec_dropper);
12133 			*first_mpp = NULL;
12134 			return (B_FALSE);
12135 		}
12136 
12137 		/* "ill" is "recv_ill" in actuality. */
12138 		if (!zero_spi_check(q, *mpp, ire, ill, ipss))
12139 			return (B_FALSE);
12140 
12141 		/* Else continue like a normal UDP packet. */
12142 	}
12143 
12144 	/*
12145 	 * We make the checks as below since we are in the fast path
12146 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12147 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12148 	 */
12149 	if (connp->conn_recvif || connp->conn_recvslla ||
12150 	    connp->conn_ip_recvpktinfo) {
12151 		if (connp->conn_recvif) {
12152 			in_flags = IPF_RECVIF;
12153 		}
12154 		/*
12155 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12156 		 * so the flag passed to ip_add_info is based on IP version
12157 		 * of connp.
12158 		 */
12159 		if (connp->conn_ip_recvpktinfo) {
12160 			if (connp->conn_af_isv6) {
12161 				/*
12162 				 * V6 only needs index
12163 				 */
12164 				in_flags |= IPF_RECVIF;
12165 			} else {
12166 				/*
12167 				 * V4 needs index + matching address.
12168 				 */
12169 				in_flags |= IPF_RECVADDR;
12170 			}
12171 		}
12172 		if (connp->conn_recvslla) {
12173 			in_flags |= IPF_RECVSLLA;
12174 		}
12175 		/*
12176 		 * since in_flags are being set ill will be
12177 		 * referenced in ip_add_info, so it better not
12178 		 * be NULL.
12179 		 */
12180 		/*
12181 		 * the actual data will be contained in b_cont
12182 		 * upon successful return of the following call.
12183 		 * If the call fails then the original mblk is
12184 		 * returned.
12185 		 */
12186 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12187 		    ipst);
12188 	}
12189 
12190 	return (B_TRUE);
12191 }
12192 
12193 /*
12194  * Fragmentation reassembly.  Each ILL has a hash table for
12195  * queuing packets undergoing reassembly for all IPIFs
12196  * associated with the ILL.  The hash is based on the packet
12197  * IP ident field.  The ILL frag hash table was allocated
12198  * as a timer block at the time the ILL was created.  Whenever
12199  * there is anything on the reassembly queue, the timer will
12200  * be running.  Returns B_TRUE if successful else B_FALSE;
12201  * frees mp on failure.
12202  */
12203 static boolean_t
12204 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
12205     uint32_t *cksum_val, uint16_t *cksum_flags)
12206 {
12207 	uint32_t	frag_offset_flags;
12208 	ill_t		*ill = (ill_t *)q->q_ptr;
12209 	mblk_t		*mp = *mpp;
12210 	mblk_t		*t_mp;
12211 	ipaddr_t	dst;
12212 	uint8_t		proto = ipha->ipha_protocol;
12213 	uint32_t	sum_val;
12214 	uint16_t	sum_flags;
12215 	ipf_t		*ipf;
12216 	ipf_t		**ipfp;
12217 	ipfb_t		*ipfb;
12218 	uint16_t	ident;
12219 	uint32_t	offset;
12220 	ipaddr_t	src;
12221 	uint_t		hdr_length;
12222 	uint32_t	end;
12223 	mblk_t		*mp1;
12224 	mblk_t		*tail_mp;
12225 	size_t		count;
12226 	size_t		msg_len;
12227 	uint8_t		ecn_info = 0;
12228 	uint32_t	packet_size;
12229 	boolean_t	pruned = B_FALSE;
12230 	ip_stack_t *ipst = ill->ill_ipst;
12231 
12232 	if (cksum_val != NULL)
12233 		*cksum_val = 0;
12234 	if (cksum_flags != NULL)
12235 		*cksum_flags = 0;
12236 
12237 	/*
12238 	 * Drop the fragmented as early as possible, if
12239 	 * we don't have resource(s) to re-assemble.
12240 	 */
12241 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12242 		freemsg(mp);
12243 		return (B_FALSE);
12244 	}
12245 
12246 	/* Check for fragmentation offset; return if there's none */
12247 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12248 	    (IPH_MF | IPH_OFFSET)) == 0)
12249 		return (B_TRUE);
12250 
12251 	/*
12252 	 * We utilize hardware computed checksum info only for UDP since
12253 	 * IP fragmentation is a normal occurence for the protocol.  In
12254 	 * addition, checksum offload support for IP fragments carrying
12255 	 * UDP payload is commonly implemented across network adapters.
12256 	 */
12257 	ASSERT(ill != NULL);
12258 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
12259 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12260 		mblk_t *mp1 = mp->b_cont;
12261 		int32_t len;
12262 
12263 		/* Record checksum information from the packet */
12264 		sum_val = (uint32_t)DB_CKSUM16(mp);
12265 		sum_flags = DB_CKSUMFLAGS(mp);
12266 
12267 		/* IP payload offset from beginning of mblk */
12268 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12269 
12270 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12271 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12272 		    offset >= DB_CKSUMSTART(mp) &&
12273 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12274 			uint32_t adj;
12275 			/*
12276 			 * Partial checksum has been calculated by hardware
12277 			 * and attached to the packet; in addition, any
12278 			 * prepended extraneous data is even byte aligned.
12279 			 * If any such data exists, we adjust the checksum;
12280 			 * this would also handle any postpended data.
12281 			 */
12282 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12283 			    mp, mp1, len, adj);
12284 
12285 			/* One's complement subtract extraneous checksum */
12286 			if (adj >= sum_val)
12287 				sum_val = ~(adj - sum_val) & 0xFFFF;
12288 			else
12289 				sum_val -= adj;
12290 		}
12291 	} else {
12292 		sum_val = 0;
12293 		sum_flags = 0;
12294 	}
12295 
12296 	/* Clear hardware checksumming flag */
12297 	DB_CKSUMFLAGS(mp) = 0;
12298 
12299 	ident = ipha->ipha_ident;
12300 	offset = (frag_offset_flags << 3) & 0xFFFF;
12301 	src = ipha->ipha_src;
12302 	dst = ipha->ipha_dst;
12303 	hdr_length = IPH_HDR_LENGTH(ipha);
12304 	end = ntohs(ipha->ipha_length) - hdr_length;
12305 
12306 	/* If end == 0 then we have a packet with no data, so just free it */
12307 	if (end == 0) {
12308 		freemsg(mp);
12309 		return (B_FALSE);
12310 	}
12311 
12312 	/* Record the ECN field info. */
12313 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12314 	if (offset != 0) {
12315 		/*
12316 		 * If this isn't the first piece, strip the header, and
12317 		 * add the offset to the end value.
12318 		 */
12319 		mp->b_rptr += hdr_length;
12320 		end += offset;
12321 	}
12322 
12323 	msg_len = MBLKSIZE(mp);
12324 	tail_mp = mp;
12325 	while (tail_mp->b_cont != NULL) {
12326 		tail_mp = tail_mp->b_cont;
12327 		msg_len += MBLKSIZE(tail_mp);
12328 	}
12329 
12330 	/* If the reassembly list for this ILL will get too big, prune it */
12331 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12332 	    ipst->ips_ip_reass_queue_bytes) {
12333 		ill_frag_prune(ill,
12334 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12335 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12336 		pruned = B_TRUE;
12337 	}
12338 
12339 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12340 	mutex_enter(&ipfb->ipfb_lock);
12341 
12342 	ipfp = &ipfb->ipfb_ipf;
12343 	/* Try to find an existing fragment queue for this packet. */
12344 	for (;;) {
12345 		ipf = ipfp[0];
12346 		if (ipf != NULL) {
12347 			/*
12348 			 * It has to match on ident and src/dst address.
12349 			 */
12350 			if (ipf->ipf_ident == ident &&
12351 			    ipf->ipf_src == src &&
12352 			    ipf->ipf_dst == dst &&
12353 			    ipf->ipf_protocol == proto) {
12354 				/*
12355 				 * If we have received too many
12356 				 * duplicate fragments for this packet
12357 				 * free it.
12358 				 */
12359 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12360 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12361 					freemsg(mp);
12362 					mutex_exit(&ipfb->ipfb_lock);
12363 					return (B_FALSE);
12364 				}
12365 				/* Found it. */
12366 				break;
12367 			}
12368 			ipfp = &ipf->ipf_hash_next;
12369 			continue;
12370 		}
12371 
12372 		/*
12373 		 * If we pruned the list, do we want to store this new
12374 		 * fragment?. We apply an optimization here based on the
12375 		 * fact that most fragments will be received in order.
12376 		 * So if the offset of this incoming fragment is zero,
12377 		 * it is the first fragment of a new packet. We will
12378 		 * keep it.  Otherwise drop the fragment, as we have
12379 		 * probably pruned the packet already (since the
12380 		 * packet cannot be found).
12381 		 */
12382 		if (pruned && offset != 0) {
12383 			mutex_exit(&ipfb->ipfb_lock);
12384 			freemsg(mp);
12385 			return (B_FALSE);
12386 		}
12387 
12388 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12389 			/*
12390 			 * Too many fragmented packets in this hash
12391 			 * bucket. Free the oldest.
12392 			 */
12393 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12394 		}
12395 
12396 		/* New guy.  Allocate a frag message. */
12397 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12398 		if (mp1 == NULL) {
12399 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12400 			freemsg(mp);
12401 reass_done:
12402 			mutex_exit(&ipfb->ipfb_lock);
12403 			return (B_FALSE);
12404 		}
12405 
12406 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12407 		mp1->b_cont = mp;
12408 
12409 		/* Initialize the fragment header. */
12410 		ipf = (ipf_t *)mp1->b_rptr;
12411 		ipf->ipf_mp = mp1;
12412 		ipf->ipf_ptphn = ipfp;
12413 		ipfp[0] = ipf;
12414 		ipf->ipf_hash_next = NULL;
12415 		ipf->ipf_ident = ident;
12416 		ipf->ipf_protocol = proto;
12417 		ipf->ipf_src = src;
12418 		ipf->ipf_dst = dst;
12419 		ipf->ipf_nf_hdr_len = 0;
12420 		/* Record reassembly start time. */
12421 		ipf->ipf_timestamp = gethrestime_sec();
12422 		/* Record ipf generation and account for frag header */
12423 		ipf->ipf_gen = ill->ill_ipf_gen++;
12424 		ipf->ipf_count = MBLKSIZE(mp1);
12425 		ipf->ipf_last_frag_seen = B_FALSE;
12426 		ipf->ipf_ecn = ecn_info;
12427 		ipf->ipf_num_dups = 0;
12428 		ipfb->ipfb_frag_pkts++;
12429 		ipf->ipf_checksum = 0;
12430 		ipf->ipf_checksum_flags = 0;
12431 
12432 		/* Store checksum value in fragment header */
12433 		if (sum_flags != 0) {
12434 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12435 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12436 			ipf->ipf_checksum = sum_val;
12437 			ipf->ipf_checksum_flags = sum_flags;
12438 		}
12439 
12440 		/*
12441 		 * We handle reassembly two ways.  In the easy case,
12442 		 * where all the fragments show up in order, we do
12443 		 * minimal bookkeeping, and just clip new pieces on
12444 		 * the end.  If we ever see a hole, then we go off
12445 		 * to ip_reassemble which has to mark the pieces and
12446 		 * keep track of the number of holes, etc.  Obviously,
12447 		 * the point of having both mechanisms is so we can
12448 		 * handle the easy case as efficiently as possible.
12449 		 */
12450 		if (offset == 0) {
12451 			/* Easy case, in-order reassembly so far. */
12452 			ipf->ipf_count += msg_len;
12453 			ipf->ipf_tail_mp = tail_mp;
12454 			/*
12455 			 * Keep track of next expected offset in
12456 			 * ipf_end.
12457 			 */
12458 			ipf->ipf_end = end;
12459 			ipf->ipf_nf_hdr_len = hdr_length;
12460 		} else {
12461 			/* Hard case, hole at the beginning. */
12462 			ipf->ipf_tail_mp = NULL;
12463 			/*
12464 			 * ipf_end == 0 means that we have given up
12465 			 * on easy reassembly.
12466 			 */
12467 			ipf->ipf_end = 0;
12468 
12469 			/* Forget checksum offload from now on */
12470 			ipf->ipf_checksum_flags = 0;
12471 
12472 			/*
12473 			 * ipf_hole_cnt is set by ip_reassemble.
12474 			 * ipf_count is updated by ip_reassemble.
12475 			 * No need to check for return value here
12476 			 * as we don't expect reassembly to complete
12477 			 * or fail for the first fragment itself.
12478 			 */
12479 			(void) ip_reassemble(mp, ipf,
12480 			    (frag_offset_flags & IPH_OFFSET) << 3,
12481 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12482 		}
12483 		/* Update per ipfb and ill byte counts */
12484 		ipfb->ipfb_count += ipf->ipf_count;
12485 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12486 		ill->ill_frag_count += ipf->ipf_count;
12487 		/* If the frag timer wasn't already going, start it. */
12488 		mutex_enter(&ill->ill_lock);
12489 		ill_frag_timer_start(ill);
12490 		mutex_exit(&ill->ill_lock);
12491 		goto reass_done;
12492 	}
12493 
12494 	/*
12495 	 * If the packet's flag has changed (it could be coming up
12496 	 * from an interface different than the previous, therefore
12497 	 * possibly different checksum capability), then forget about
12498 	 * any stored checksum states.  Otherwise add the value to
12499 	 * the existing one stored in the fragment header.
12500 	 */
12501 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12502 		sum_val += ipf->ipf_checksum;
12503 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12504 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12505 		ipf->ipf_checksum = sum_val;
12506 	} else if (ipf->ipf_checksum_flags != 0) {
12507 		/* Forget checksum offload from now on */
12508 		ipf->ipf_checksum_flags = 0;
12509 	}
12510 
12511 	/*
12512 	 * We have a new piece of a datagram which is already being
12513 	 * reassembled.  Update the ECN info if all IP fragments
12514 	 * are ECN capable.  If there is one which is not, clear
12515 	 * all the info.  If there is at least one which has CE
12516 	 * code point, IP needs to report that up to transport.
12517 	 */
12518 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12519 		if (ecn_info == IPH_ECN_CE)
12520 			ipf->ipf_ecn = IPH_ECN_CE;
12521 	} else {
12522 		ipf->ipf_ecn = IPH_ECN_NECT;
12523 	}
12524 	if (offset && ipf->ipf_end == offset) {
12525 		/* The new fragment fits at the end */
12526 		ipf->ipf_tail_mp->b_cont = mp;
12527 		/* Update the byte count */
12528 		ipf->ipf_count += msg_len;
12529 		/* Update per ipfb and ill byte counts */
12530 		ipfb->ipfb_count += msg_len;
12531 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12532 		ill->ill_frag_count += msg_len;
12533 		if (frag_offset_flags & IPH_MF) {
12534 			/* More to come. */
12535 			ipf->ipf_end = end;
12536 			ipf->ipf_tail_mp = tail_mp;
12537 			goto reass_done;
12538 		}
12539 	} else {
12540 		/* Go do the hard cases. */
12541 		int ret;
12542 
12543 		if (offset == 0)
12544 			ipf->ipf_nf_hdr_len = hdr_length;
12545 
12546 		/* Save current byte count */
12547 		count = ipf->ipf_count;
12548 		ret = ip_reassemble(mp, ipf,
12549 		    (frag_offset_flags & IPH_OFFSET) << 3,
12550 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12551 		/* Count of bytes added and subtracted (freeb()ed) */
12552 		count = ipf->ipf_count - count;
12553 		if (count) {
12554 			/* Update per ipfb and ill byte counts */
12555 			ipfb->ipfb_count += count;
12556 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12557 			ill->ill_frag_count += count;
12558 		}
12559 		if (ret == IP_REASS_PARTIAL) {
12560 			goto reass_done;
12561 		} else if (ret == IP_REASS_FAILED) {
12562 			/* Reassembly failed. Free up all resources */
12563 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12564 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12565 				IP_REASS_SET_START(t_mp, 0);
12566 				IP_REASS_SET_END(t_mp, 0);
12567 			}
12568 			freemsg(mp);
12569 			goto reass_done;
12570 		}
12571 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12572 	}
12573 	/*
12574 	 * We have completed reassembly.  Unhook the frag header from
12575 	 * the reassembly list.
12576 	 *
12577 	 * Before we free the frag header, record the ECN info
12578 	 * to report back to the transport.
12579 	 */
12580 	ecn_info = ipf->ipf_ecn;
12581 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12582 	ipfp = ipf->ipf_ptphn;
12583 
12584 	/* We need to supply these to caller */
12585 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12586 		sum_val = ipf->ipf_checksum;
12587 	else
12588 		sum_val = 0;
12589 
12590 	mp1 = ipf->ipf_mp;
12591 	count = ipf->ipf_count;
12592 	ipf = ipf->ipf_hash_next;
12593 	if (ipf != NULL)
12594 		ipf->ipf_ptphn = ipfp;
12595 	ipfp[0] = ipf;
12596 	ill->ill_frag_count -= count;
12597 	ASSERT(ipfb->ipfb_count >= count);
12598 	ipfb->ipfb_count -= count;
12599 	ipfb->ipfb_frag_pkts--;
12600 	mutex_exit(&ipfb->ipfb_lock);
12601 	/* Ditch the frag header. */
12602 	mp = mp1->b_cont;
12603 
12604 	freeb(mp1);
12605 
12606 	/* Restore original IP length in header. */
12607 	packet_size = (uint32_t)msgdsize(mp);
12608 	if (packet_size > IP_MAXPACKET) {
12609 		freemsg(mp);
12610 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12611 		return (B_FALSE);
12612 	}
12613 
12614 	if (DB_REF(mp) > 1) {
12615 		mblk_t *mp2 = copymsg(mp);
12616 
12617 		freemsg(mp);
12618 		if (mp2 == NULL) {
12619 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12620 			return (B_FALSE);
12621 		}
12622 		mp = mp2;
12623 	}
12624 	ipha = (ipha_t *)mp->b_rptr;
12625 
12626 	ipha->ipha_length = htons((uint16_t)packet_size);
12627 	/* We're now complete, zip the frag state */
12628 	ipha->ipha_fragment_offset_and_flags = 0;
12629 	/* Record the ECN info. */
12630 	ipha->ipha_type_of_service &= 0xFC;
12631 	ipha->ipha_type_of_service |= ecn_info;
12632 	*mpp = mp;
12633 
12634 	/* Reassembly is successful; return checksum information if needed */
12635 	if (cksum_val != NULL)
12636 		*cksum_val = sum_val;
12637 	if (cksum_flags != NULL)
12638 		*cksum_flags = sum_flags;
12639 
12640 	return (B_TRUE);
12641 }
12642 
12643 /*
12644  * Perform ip header check sum update local options.
12645  * return B_TRUE if all is well, else return B_FALSE and release
12646  * the mp. caller is responsible for decrementing ire ref cnt.
12647  */
12648 static boolean_t
12649 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12650     ip_stack_t *ipst)
12651 {
12652 	mblk_t		*first_mp;
12653 	boolean_t	mctl_present;
12654 	uint16_t	sum;
12655 
12656 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12657 	/*
12658 	 * Don't do the checksum if it has gone through AH/ESP
12659 	 * processing.
12660 	 */
12661 	if (!mctl_present) {
12662 		sum = ip_csum_hdr(ipha);
12663 		if (sum != 0) {
12664 			if (ill != NULL) {
12665 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12666 			} else {
12667 				BUMP_MIB(&ipst->ips_ip_mib,
12668 				    ipIfStatsInCksumErrs);
12669 			}
12670 			freemsg(first_mp);
12671 			return (B_FALSE);
12672 		}
12673 	}
12674 
12675 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12676 		if (mctl_present)
12677 			freeb(first_mp);
12678 		return (B_FALSE);
12679 	}
12680 
12681 	return (B_TRUE);
12682 }
12683 
12684 /*
12685  * All udp packet are delivered to the local host via this routine.
12686  */
12687 void
12688 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12689     ill_t *recv_ill)
12690 {
12691 	uint32_t	sum;
12692 	uint32_t	u1;
12693 	boolean_t	mctl_present;
12694 	conn_t		*connp;
12695 	mblk_t		*first_mp;
12696 	uint16_t	*up;
12697 	ill_t		*ill = (ill_t *)q->q_ptr;
12698 	uint16_t	reass_hck_flags = 0;
12699 	ip_stack_t	*ipst;
12700 
12701 	ASSERT(recv_ill != NULL);
12702 	ipst = recv_ill->ill_ipst;
12703 
12704 #define	rptr    ((uchar_t *)ipha)
12705 
12706 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12707 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12708 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12709 	ASSERT(ill != NULL);
12710 
12711 	/*
12712 	 * FAST PATH for udp packets
12713 	 */
12714 
12715 	/* u1 is # words of IP options */
12716 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12717 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12718 
12719 	/* IP options present */
12720 	if (u1 != 0)
12721 		goto ipoptions;
12722 
12723 	/* Check the IP header checksum.  */
12724 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12725 		/* Clear the IP header h/w cksum flag */
12726 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12727 	} else if (!mctl_present) {
12728 		/*
12729 		 * Don't verify header checksum if this packet is coming
12730 		 * back from AH/ESP as we already did it.
12731 		 */
12732 #define	uph	((uint16_t *)ipha)
12733 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12734 		    uph[6] + uph[7] + uph[8] + uph[9];
12735 #undef	uph
12736 		/* finish doing IP checksum */
12737 		sum = (sum & 0xFFFF) + (sum >> 16);
12738 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12739 		if (sum != 0 && sum != 0xFFFF) {
12740 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12741 			freemsg(first_mp);
12742 			return;
12743 		}
12744 	}
12745 
12746 	/*
12747 	 * Count for SNMP of inbound packets for ire.
12748 	 * if mctl is present this might be a secure packet and
12749 	 * has already been counted for in ip_proto_input().
12750 	 */
12751 	if (!mctl_present) {
12752 		UPDATE_IB_PKT_COUNT(ire);
12753 		ire->ire_last_used_time = lbolt;
12754 	}
12755 
12756 	/* packet part of fragmented IP packet? */
12757 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12758 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12759 		goto fragmented;
12760 	}
12761 
12762 	/* u1 = IP header length (20 bytes) */
12763 	u1 = IP_SIMPLE_HDR_LENGTH;
12764 
12765 	/* packet does not contain complete IP & UDP headers */
12766 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12767 		goto udppullup;
12768 
12769 	/* up points to UDP header */
12770 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12771 #define	iphs    ((uint16_t *)ipha)
12772 
12773 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12774 	if (up[3] != 0) {
12775 		mblk_t *mp1 = mp->b_cont;
12776 		boolean_t cksum_err;
12777 		uint16_t hck_flags = 0;
12778 
12779 		/* Pseudo-header checksum */
12780 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12781 		    iphs[9] + up[2];
12782 
12783 		/*
12784 		 * Revert to software checksum calculation if the interface
12785 		 * isn't capable of checksum offload or if IPsec is present.
12786 		 */
12787 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12788 			hck_flags = DB_CKSUMFLAGS(mp);
12789 
12790 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12791 			IP_STAT(ipst, ip_in_sw_cksum);
12792 
12793 		IP_CKSUM_RECV(hck_flags, u1,
12794 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12795 		    (int32_t)((uchar_t *)up - rptr),
12796 		    mp, mp1, cksum_err);
12797 
12798 		if (cksum_err) {
12799 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12800 			if (hck_flags & HCK_FULLCKSUM)
12801 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12802 			else if (hck_flags & HCK_PARTIALCKSUM)
12803 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12804 			else
12805 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12806 
12807 			freemsg(first_mp);
12808 			return;
12809 		}
12810 	}
12811 
12812 	/* Non-fragmented broadcast or multicast packet? */
12813 	if (ire->ire_type == IRE_BROADCAST)
12814 		goto udpslowpath;
12815 
12816 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12817 	    ire->ire_zoneid, ipst)) != NULL) {
12818 		ASSERT(connp->conn_upq != NULL);
12819 		IP_STAT(ipst, ip_udp_fast_path);
12820 
12821 		if (CONN_UDP_FLOWCTLD(connp)) {
12822 			freemsg(mp);
12823 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
12824 		} else {
12825 			if (!mctl_present) {
12826 				BUMP_MIB(ill->ill_ip_mib,
12827 				    ipIfStatsHCInDelivers);
12828 			}
12829 			/*
12830 			 * mp and first_mp can change.
12831 			 */
12832 			if (ip_udp_check(q, connp, recv_ill,
12833 			    ipha, &mp, &first_mp, mctl_present, ire)) {
12834 				/* Send it upstream */
12835 				(connp->conn_recv)(connp, mp, NULL);
12836 			}
12837 		}
12838 		/*
12839 		 * freeb() cannot deal with null mblk being passed
12840 		 * in and first_mp can be set to null in the call
12841 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12842 		 */
12843 		if (mctl_present && first_mp != NULL) {
12844 			freeb(first_mp);
12845 		}
12846 		CONN_DEC_REF(connp);
12847 		return;
12848 	}
12849 
12850 	/*
12851 	 * if we got here we know the packet is not fragmented and
12852 	 * has no options. The classifier could not find a conn_t and
12853 	 * most likely its an icmp packet so send it through slow path.
12854 	 */
12855 
12856 	goto udpslowpath;
12857 
12858 ipoptions:
12859 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
12860 		goto slow_done;
12861 	}
12862 
12863 	UPDATE_IB_PKT_COUNT(ire);
12864 	ire->ire_last_used_time = lbolt;
12865 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12866 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12867 fragmented:
12868 		/*
12869 		 * "sum" and "reass_hck_flags" are non-zero if the
12870 		 * reassembled packet has a valid hardware computed
12871 		 * checksum information associated with it.
12872 		 */
12873 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
12874 			goto slow_done;
12875 		/*
12876 		 * Make sure that first_mp points back to mp as
12877 		 * the mp we came in with could have changed in
12878 		 * ip_rput_fragment().
12879 		 */
12880 		ASSERT(!mctl_present);
12881 		ipha = (ipha_t *)mp->b_rptr;
12882 		first_mp = mp;
12883 	}
12884 
12885 	/* Now we have a complete datagram, destined for this machine. */
12886 	u1 = IPH_HDR_LENGTH(ipha);
12887 	/* Pull up the UDP header, if necessary. */
12888 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12889 udppullup:
12890 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12891 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12892 			freemsg(first_mp);
12893 			goto slow_done;
12894 		}
12895 		ipha = (ipha_t *)mp->b_rptr;
12896 	}
12897 
12898 	/*
12899 	 * Validate the checksum for the reassembled packet; for the
12900 	 * pullup case we calculate the payload checksum in software.
12901 	 */
12902 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12903 	if (up[3] != 0) {
12904 		boolean_t cksum_err;
12905 
12906 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12907 			IP_STAT(ipst, ip_in_sw_cksum);
12908 
12909 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12910 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12911 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12912 		    iphs[9] + up[2], sum, cksum_err);
12913 
12914 		if (cksum_err) {
12915 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12916 
12917 			if (reass_hck_flags & HCK_FULLCKSUM)
12918 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12919 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12920 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12921 			else
12922 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12923 
12924 			freemsg(first_mp);
12925 			goto slow_done;
12926 		}
12927 	}
12928 udpslowpath:
12929 
12930 	/* Clear hardware checksum flag to be safe */
12931 	DB_CKSUMFLAGS(mp) = 0;
12932 
12933 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12934 	    (ire->ire_type == IRE_BROADCAST),
12935 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
12936 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12937 
12938 slow_done:
12939 	IP_STAT(ipst, ip_udp_slow_path);
12940 	return;
12941 
12942 #undef  iphs
12943 #undef  rptr
12944 }
12945 
12946 /* ARGSUSED */
12947 static mblk_t *
12948 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12949     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12950     ill_rx_ring_t *ill_ring)
12951 {
12952 	conn_t		*connp;
12953 	uint32_t	sum;
12954 	uint32_t	u1;
12955 	uint16_t	*up;
12956 	int		offset;
12957 	ssize_t		len;
12958 	mblk_t		*mp1;
12959 	boolean_t	syn_present = B_FALSE;
12960 	tcph_t		*tcph;
12961 	uint_t		ip_hdr_len;
12962 	ill_t		*ill = (ill_t *)q->q_ptr;
12963 	zoneid_t	zoneid = ire->ire_zoneid;
12964 	boolean_t	cksum_err;
12965 	uint16_t	hck_flags = 0;
12966 	ip_stack_t	*ipst = recv_ill->ill_ipst;
12967 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12968 
12969 #define	rptr	((uchar_t *)ipha)
12970 
12971 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12972 	ASSERT(ill != NULL);
12973 
12974 	/*
12975 	 * FAST PATH for tcp packets
12976 	 */
12977 
12978 	/* u1 is # words of IP options */
12979 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12980 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12981 
12982 	/* IP options present */
12983 	if (u1) {
12984 		goto ipoptions;
12985 	} else if (!mctl_present) {
12986 		/* Check the IP header checksum.  */
12987 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12988 			/* Clear the IP header h/w cksum flag */
12989 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12990 		} else if (!mctl_present) {
12991 			/*
12992 			 * Don't verify header checksum if this packet
12993 			 * is coming back from AH/ESP as we already did it.
12994 			 */
12995 #define	uph	((uint16_t *)ipha)
12996 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12997 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12998 #undef	uph
12999 			/* finish doing IP checksum */
13000 			sum = (sum & 0xFFFF) + (sum >> 16);
13001 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13002 			if (sum != 0 && sum != 0xFFFF) {
13003 				BUMP_MIB(ill->ill_ip_mib,
13004 				    ipIfStatsInCksumErrs);
13005 				goto error;
13006 			}
13007 		}
13008 	}
13009 
13010 	if (!mctl_present) {
13011 		UPDATE_IB_PKT_COUNT(ire);
13012 		ire->ire_last_used_time = lbolt;
13013 	}
13014 
13015 	/* packet part of fragmented IP packet? */
13016 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13017 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13018 		goto fragmented;
13019 	}
13020 
13021 	/* u1 = IP header length (20 bytes) */
13022 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
13023 
13024 	/* does packet contain IP+TCP headers? */
13025 	len = mp->b_wptr - rptr;
13026 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
13027 		IP_STAT(ipst, ip_tcppullup);
13028 		goto tcppullup;
13029 	}
13030 
13031 	/* TCP options present? */
13032 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
13033 
13034 	/*
13035 	 * If options need to be pulled up, then goto tcpoptions.
13036 	 * otherwise we are still in the fast path
13037 	 */
13038 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
13039 		IP_STAT(ipst, ip_tcpoptions);
13040 		goto tcpoptions;
13041 	}
13042 
13043 	/* multiple mblks of tcp data? */
13044 	if ((mp1 = mp->b_cont) != NULL) {
13045 		/* more then two? */
13046 		if (mp1->b_cont != NULL) {
13047 			IP_STAT(ipst, ip_multipkttcp);
13048 			goto multipkttcp;
13049 		}
13050 		len += mp1->b_wptr - mp1->b_rptr;
13051 	}
13052 
13053 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
13054 
13055 	/* part of pseudo checksum */
13056 
13057 	/* TCP datagram length */
13058 	u1 = len - IP_SIMPLE_HDR_LENGTH;
13059 
13060 #define	iphs    ((uint16_t *)ipha)
13061 
13062 #ifdef	_BIG_ENDIAN
13063 	u1 += IPPROTO_TCP;
13064 #else
13065 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13066 #endif
13067 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13068 
13069 	/*
13070 	 * Revert to software checksum calculation if the interface
13071 	 * isn't capable of checksum offload or if IPsec is present.
13072 	 */
13073 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
13074 		hck_flags = DB_CKSUMFLAGS(mp);
13075 
13076 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13077 		IP_STAT(ipst, ip_in_sw_cksum);
13078 
13079 	IP_CKSUM_RECV(hck_flags, u1,
13080 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
13081 	    (int32_t)((uchar_t *)up - rptr),
13082 	    mp, mp1, cksum_err);
13083 
13084 	if (cksum_err) {
13085 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13086 
13087 		if (hck_flags & HCK_FULLCKSUM)
13088 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
13089 		else if (hck_flags & HCK_PARTIALCKSUM)
13090 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
13091 		else
13092 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
13093 
13094 		goto error;
13095 	}
13096 
13097 try_again:
13098 
13099 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
13100 	    zoneid, ipst)) == NULL) {
13101 		/* Send the TH_RST */
13102 		goto no_conn;
13103 	}
13104 
13105 	/*
13106 	 * TCP FAST PATH for AF_INET socket.
13107 	 *
13108 	 * TCP fast path to avoid extra work. An AF_INET socket type
13109 	 * does not have facility to receive extra information via
13110 	 * ip_process or ip_add_info. Also, when the connection was
13111 	 * established, we made a check if this connection is impacted
13112 	 * by any global IPsec policy or per connection policy (a
13113 	 * policy that comes in effect later will not apply to this
13114 	 * connection). Since all this can be determined at the
13115 	 * connection establishment time, a quick check of flags
13116 	 * can avoid extra work.
13117 	 */
13118 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13119 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13120 		ASSERT(first_mp == mp);
13121 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13122 		SET_SQUEUE(mp, tcp_rput_data, connp);
13123 		return (mp);
13124 	}
13125 
13126 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
13127 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
13128 		if (IPCL_IS_TCP(connp)) {
13129 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13130 			DB_CKSUMSTART(mp) =
13131 			    (intptr_t)ip_squeue_get(ill_ring);
13132 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13133 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13134 				BUMP_MIB(ill->ill_ip_mib,
13135 				    ipIfStatsHCInDelivers);
13136 				SET_SQUEUE(mp, connp->conn_recv, connp);
13137 				return (mp);
13138 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13139 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13140 				BUMP_MIB(ill->ill_ip_mib,
13141 				    ipIfStatsHCInDelivers);
13142 				ip_squeue_enter_unbound++;
13143 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13144 				    connp);
13145 				return (mp);
13146 			}
13147 			syn_present = B_TRUE;
13148 		}
13149 
13150 	}
13151 
13152 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13153 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13154 
13155 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13156 		/* No need to send this packet to TCP */
13157 		if ((flags & TH_RST) || (flags & TH_URG)) {
13158 			CONN_DEC_REF(connp);
13159 			freemsg(first_mp);
13160 			return (NULL);
13161 		}
13162 		if (flags & TH_ACK) {
13163 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
13164 			    ipst->ips_netstack->netstack_tcp, connp);
13165 			CONN_DEC_REF(connp);
13166 			return (NULL);
13167 		}
13168 
13169 		CONN_DEC_REF(connp);
13170 		freemsg(first_mp);
13171 		return (NULL);
13172 	}
13173 
13174 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13175 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13176 		    ipha, NULL, mctl_present);
13177 		if (first_mp == NULL) {
13178 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13179 			CONN_DEC_REF(connp);
13180 			return (NULL);
13181 		}
13182 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13183 			ASSERT(syn_present);
13184 			if (mctl_present) {
13185 				ASSERT(first_mp != mp);
13186 				first_mp->b_datap->db_struioflag |=
13187 				    STRUIO_POLICY;
13188 			} else {
13189 				ASSERT(first_mp == mp);
13190 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13191 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13192 			}
13193 		} else {
13194 			/*
13195 			 * Discard first_mp early since we're dealing with a
13196 			 * fully-connected conn_t and tcp doesn't do policy in
13197 			 * this case.
13198 			 */
13199 			if (mctl_present) {
13200 				freeb(first_mp);
13201 				mctl_present = B_FALSE;
13202 			}
13203 			first_mp = mp;
13204 		}
13205 	}
13206 
13207 	/* Initiate IPPF processing for fastpath */
13208 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13209 		uint32_t	ill_index;
13210 
13211 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13212 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13213 		if (mp == NULL) {
13214 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13215 			    "deferred/dropped during IPPF processing\n"));
13216 			CONN_DEC_REF(connp);
13217 			if (mctl_present)
13218 				freeb(first_mp);
13219 			return (NULL);
13220 		} else if (mctl_present) {
13221 			/*
13222 			 * ip_process might return a new mp.
13223 			 */
13224 			ASSERT(first_mp != mp);
13225 			first_mp->b_cont = mp;
13226 		} else {
13227 			first_mp = mp;
13228 		}
13229 
13230 	}
13231 
13232 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13233 		/*
13234 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13235 		 * make sure IPF_RECVIF is passed to ip_add_info.
13236 		 */
13237 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13238 		    IPCL_ZONEID(connp), ipst);
13239 		if (mp == NULL) {
13240 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13241 			CONN_DEC_REF(connp);
13242 			if (mctl_present)
13243 				freeb(first_mp);
13244 			return (NULL);
13245 		} else if (mctl_present) {
13246 			/*
13247 			 * ip_add_info might return a new mp.
13248 			 */
13249 			ASSERT(first_mp != mp);
13250 			first_mp->b_cont = mp;
13251 		} else {
13252 			first_mp = mp;
13253 		}
13254 	}
13255 
13256 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13257 	if (IPCL_IS_TCP(connp)) {
13258 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13259 		return (first_mp);
13260 	} else {
13261 		/* SOCK_RAW, IPPROTO_TCP case */
13262 		(connp->conn_recv)(connp, first_mp, NULL);
13263 		CONN_DEC_REF(connp);
13264 		return (NULL);
13265 	}
13266 
13267 no_conn:
13268 	/* Initiate IPPf processing, if needed. */
13269 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13270 		uint32_t ill_index;
13271 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13272 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13273 		if (first_mp == NULL) {
13274 			return (NULL);
13275 		}
13276 	}
13277 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13278 
13279 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13280 	    ipst->ips_netstack->netstack_tcp, NULL);
13281 	return (NULL);
13282 ipoptions:
13283 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13284 		goto slow_done;
13285 	}
13286 
13287 	UPDATE_IB_PKT_COUNT(ire);
13288 	ire->ire_last_used_time = lbolt;
13289 
13290 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13291 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13292 fragmented:
13293 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
13294 			if (mctl_present)
13295 				freeb(first_mp);
13296 			goto slow_done;
13297 		}
13298 		/*
13299 		 * Make sure that first_mp points back to mp as
13300 		 * the mp we came in with could have changed in
13301 		 * ip_rput_fragment().
13302 		 */
13303 		ASSERT(!mctl_present);
13304 		ipha = (ipha_t *)mp->b_rptr;
13305 		first_mp = mp;
13306 	}
13307 
13308 	/* Now we have a complete datagram, destined for this machine. */
13309 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13310 
13311 	len = mp->b_wptr - mp->b_rptr;
13312 	/* Pull up a minimal TCP header, if necessary. */
13313 	if (len < (u1 + 20)) {
13314 tcppullup:
13315 		if (!pullupmsg(mp, u1 + 20)) {
13316 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13317 			goto error;
13318 		}
13319 		ipha = (ipha_t *)mp->b_rptr;
13320 		len = mp->b_wptr - mp->b_rptr;
13321 	}
13322 
13323 	/*
13324 	 * Extract the offset field from the TCP header.  As usual, we
13325 	 * try to help the compiler more than the reader.
13326 	 */
13327 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13328 	if (offset != 5) {
13329 tcpoptions:
13330 		if (offset < 5) {
13331 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13332 			goto error;
13333 		}
13334 		/*
13335 		 * There must be TCP options.
13336 		 * Make sure we can grab them.
13337 		 */
13338 		offset <<= 2;
13339 		offset += u1;
13340 		if (len < offset) {
13341 			if (!pullupmsg(mp, offset)) {
13342 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13343 				goto error;
13344 			}
13345 			ipha = (ipha_t *)mp->b_rptr;
13346 			len = mp->b_wptr - rptr;
13347 		}
13348 	}
13349 
13350 	/* Get the total packet length in len, including headers. */
13351 	if (mp->b_cont) {
13352 multipkttcp:
13353 		len = msgdsize(mp);
13354 	}
13355 
13356 	/*
13357 	 * Check the TCP checksum by pulling together the pseudo-
13358 	 * header checksum, and passing it to ip_csum to be added in
13359 	 * with the TCP datagram.
13360 	 *
13361 	 * Since we are not using the hwcksum if available we must
13362 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13363 	 * If either of these fails along the way the mblk is freed.
13364 	 * If this logic ever changes and mblk is reused to say send
13365 	 * ICMP's back, then this flag may need to be cleared in
13366 	 * other places as well.
13367 	 */
13368 	DB_CKSUMFLAGS(mp) = 0;
13369 
13370 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13371 
13372 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13373 #ifdef	_BIG_ENDIAN
13374 	u1 += IPPROTO_TCP;
13375 #else
13376 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13377 #endif
13378 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13379 	/*
13380 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13381 	 */
13382 	IP_STAT(ipst, ip_in_sw_cksum);
13383 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13384 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13385 		goto error;
13386 	}
13387 
13388 	IP_STAT(ipst, ip_tcp_slow_path);
13389 	goto try_again;
13390 #undef  iphs
13391 #undef  rptr
13392 
13393 error:
13394 	freemsg(first_mp);
13395 slow_done:
13396 	return (NULL);
13397 }
13398 
13399 /* ARGSUSED */
13400 static void
13401 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13402     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13403 {
13404 	conn_t		*connp;
13405 	uint32_t	sum;
13406 	uint32_t	u1;
13407 	ssize_t		len;
13408 	sctp_hdr_t	*sctph;
13409 	zoneid_t	zoneid = ire->ire_zoneid;
13410 	uint32_t	pktsum;
13411 	uint32_t	calcsum;
13412 	uint32_t	ports;
13413 	in6_addr_t	map_src, map_dst;
13414 	ill_t		*ill = (ill_t *)q->q_ptr;
13415 	ip_stack_t	*ipst;
13416 	sctp_stack_t	*sctps;
13417 
13418 	ASSERT(recv_ill != NULL);
13419 	ipst = recv_ill->ill_ipst;
13420 	sctps = ipst->ips_netstack->netstack_sctp;
13421 
13422 #define	rptr	((uchar_t *)ipha)
13423 
13424 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13425 	ASSERT(ill != NULL);
13426 
13427 	/* u1 is # words of IP options */
13428 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13429 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13430 
13431 	/* IP options present */
13432 	if (u1 > 0) {
13433 		goto ipoptions;
13434 	} else {
13435 		/* Check the IP header checksum.  */
13436 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill) &&
13437 		    !mctl_present) {
13438 #define	uph	((uint16_t *)ipha)
13439 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13440 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13441 #undef	uph
13442 			/* finish doing IP checksum */
13443 			sum = (sum & 0xFFFF) + (sum >> 16);
13444 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13445 			/*
13446 			 * Don't verify header checksum if this packet
13447 			 * is coming back from AH/ESP as we already did it.
13448 			 */
13449 			if (sum != 0 && sum != 0xFFFF) {
13450 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13451 				goto error;
13452 			}
13453 		}
13454 		/*
13455 		 * Since there is no SCTP h/w cksum support yet, just
13456 		 * clear the flag.
13457 		 */
13458 		DB_CKSUMFLAGS(mp) = 0;
13459 	}
13460 
13461 	/*
13462 	 * Don't verify header checksum if this packet is coming
13463 	 * back from AH/ESP as we already did it.
13464 	 */
13465 	if (!mctl_present) {
13466 		UPDATE_IB_PKT_COUNT(ire);
13467 		ire->ire_last_used_time = lbolt;
13468 	}
13469 
13470 	/* packet part of fragmented IP packet? */
13471 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13472 	if (u1 & (IPH_MF | IPH_OFFSET))
13473 		goto fragmented;
13474 
13475 	/* u1 = IP header length (20 bytes) */
13476 	u1 = IP_SIMPLE_HDR_LENGTH;
13477 
13478 find_sctp_client:
13479 	/* Pullup if we don't have the sctp common header. */
13480 	len = MBLKL(mp);
13481 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13482 		if (mp->b_cont == NULL ||
13483 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13484 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13485 			goto error;
13486 		}
13487 		ipha = (ipha_t *)mp->b_rptr;
13488 		len = MBLKL(mp);
13489 	}
13490 
13491 	sctph = (sctp_hdr_t *)(rptr + u1);
13492 #ifdef	DEBUG
13493 	if (!skip_sctp_cksum) {
13494 #endif
13495 		pktsum = sctph->sh_chksum;
13496 		sctph->sh_chksum = 0;
13497 		calcsum = sctp_cksum(mp, u1);
13498 		if (calcsum != pktsum) {
13499 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
13500 			goto error;
13501 		}
13502 		sctph->sh_chksum = pktsum;
13503 #ifdef	DEBUG	/* skip_sctp_cksum */
13504 	}
13505 #endif
13506 	/* get the ports */
13507 	ports = *(uint32_t *)&sctph->sh_sport;
13508 
13509 	IRE_REFRELE(ire);
13510 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13511 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13512 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13513 	    sctps)) == NULL) {
13514 		/* Check for raw socket or OOTB handling */
13515 		goto no_conn;
13516 	}
13517 
13518 	/* Found a client; up it goes */
13519 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13520 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13521 	return;
13522 
13523 no_conn:
13524 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13525 	    ports, mctl_present, flags, B_TRUE, zoneid);
13526 	return;
13527 
13528 ipoptions:
13529 	DB_CKSUMFLAGS(mp) = 0;
13530 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13531 		goto slow_done;
13532 
13533 	UPDATE_IB_PKT_COUNT(ire);
13534 	ire->ire_last_used_time = lbolt;
13535 
13536 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13537 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13538 fragmented:
13539 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
13540 			goto slow_done;
13541 		/*
13542 		 * Make sure that first_mp points back to mp as
13543 		 * the mp we came in with could have changed in
13544 		 * ip_rput_fragment().
13545 		 */
13546 		ASSERT(!mctl_present);
13547 		ipha = (ipha_t *)mp->b_rptr;
13548 		first_mp = mp;
13549 	}
13550 
13551 	/* Now we have a complete datagram, destined for this machine. */
13552 	u1 = IPH_HDR_LENGTH(ipha);
13553 	goto find_sctp_client;
13554 #undef  iphs
13555 #undef  rptr
13556 
13557 error:
13558 	freemsg(first_mp);
13559 slow_done:
13560 	IRE_REFRELE(ire);
13561 }
13562 
13563 #define	VER_BITS	0xF0
13564 #define	VERSION_6	0x60
13565 
13566 static boolean_t
13567 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13568     ipaddr_t *dstp, ip_stack_t *ipst)
13569 {
13570 	uint_t	opt_len;
13571 	ipha_t *ipha;
13572 	ssize_t len;
13573 	uint_t	pkt_len;
13574 
13575 	ASSERT(ill != NULL);
13576 	IP_STAT(ipst, ip_ipoptions);
13577 	ipha = *iphapp;
13578 
13579 #define	rptr    ((uchar_t *)ipha)
13580 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13581 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13582 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13583 		freemsg(mp);
13584 		return (B_FALSE);
13585 	}
13586 
13587 	/* multiple mblk or too short */
13588 	pkt_len = ntohs(ipha->ipha_length);
13589 
13590 	/* Get the number of words of IP options in the IP header. */
13591 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13592 	if (opt_len) {
13593 		/* IP Options present!  Validate and process. */
13594 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13595 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13596 			goto done;
13597 		}
13598 		/*
13599 		 * Recompute complete header length and make sure we
13600 		 * have access to all of it.
13601 		 */
13602 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13603 		if (len > (mp->b_wptr - rptr)) {
13604 			if (len > pkt_len) {
13605 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13606 				goto done;
13607 			}
13608 			if (!pullupmsg(mp, len)) {
13609 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13610 				goto done;
13611 			}
13612 			ipha = (ipha_t *)mp->b_rptr;
13613 		}
13614 		/*
13615 		 * Go off to ip_rput_options which returns the next hop
13616 		 * destination address, which may have been affected
13617 		 * by source routing.
13618 		 */
13619 		IP_STAT(ipst, ip_opt);
13620 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13621 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13622 			return (B_FALSE);
13623 		}
13624 	}
13625 	*iphapp = ipha;
13626 	return (B_TRUE);
13627 done:
13628 	/* clear b_prev - used by ip_mroute_decap */
13629 	mp->b_prev = NULL;
13630 	freemsg(mp);
13631 	return (B_FALSE);
13632 #undef  rptr
13633 }
13634 
13635 /*
13636  * Deal with the fact that there is no ire for the destination.
13637  */
13638 static ire_t *
13639 ip_rput_noire(queue_t *q, mblk_t *mp, int ll_multicast, ipaddr_t dst)
13640 {
13641 	ipha_t	*ipha;
13642 	ill_t	*ill;
13643 	ire_t	*ire;
13644 	boolean_t	check_multirt = B_FALSE;
13645 	ip_stack_t *ipst;
13646 
13647 	ipha = (ipha_t *)mp->b_rptr;
13648 	ill = (ill_t *)q->q_ptr;
13649 
13650 	ASSERT(ill != NULL);
13651 	ipst = ill->ill_ipst;
13652 
13653 	/*
13654 	 * No IRE for this destination, so it can't be for us.
13655 	 * Unless we are forwarding, drop the packet.
13656 	 * We have to let source routed packets through
13657 	 * since we don't yet know if they are 'ping -l'
13658 	 * packets i.e. if they will go out over the
13659 	 * same interface as they came in on.
13660 	 */
13661 	if (ll_multicast) {
13662 		freemsg(mp);
13663 		return (NULL);
13664 	}
13665 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13666 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13667 		freemsg(mp);
13668 		return (NULL);
13669 	}
13670 
13671 	/*
13672 	 * Mark this packet as having originated externally.
13673 	 *
13674 	 * For non-forwarding code path, ire_send later double
13675 	 * checks this interface to see if it is still exists
13676 	 * post-ARP resolution.
13677 	 *
13678 	 * Also, IPQOS uses this to differentiate between
13679 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13680 	 * QOS packet processing in ip_wput_attach_llhdr().
13681 	 * The QoS module can mark the b_band for a fastpath message
13682 	 * or the dl_priority field in a unitdata_req header for
13683 	 * CoS marking. This info can only be found in
13684 	 * ip_wput_attach_llhdr().
13685 	 */
13686 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13687 	/*
13688 	 * Clear the indication that this may have a hardware checksum
13689 	 * as we are not using it
13690 	 */
13691 	DB_CKSUMFLAGS(mp) = 0;
13692 
13693 	ire = ire_forward(dst, &check_multirt, NULL, NULL,
13694 	    MBLK_GETLABEL(mp), ipst);
13695 
13696 	if (ire == NULL && check_multirt) {
13697 		/* Let ip_newroute handle CGTP  */
13698 		ip_newroute(q, mp, dst, NULL, GLOBAL_ZONEID, ipst);
13699 		return (NULL);
13700 	}
13701 
13702 	if (ire != NULL)
13703 		return (ire);
13704 
13705 	mp->b_prev = mp->b_next = 0;
13706 	/* send icmp unreachable */
13707 	q = WR(q);
13708 	/* Sent by forwarding path, and router is global zone */
13709 	if (ip_source_routed(ipha, ipst)) {
13710 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13711 		    GLOBAL_ZONEID, ipst);
13712 	} else {
13713 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13714 		    ipst);
13715 	}
13716 
13717 	return (NULL);
13718 
13719 }
13720 
13721 /*
13722  * check ip header length and align it.
13723  */
13724 static boolean_t
13725 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13726 {
13727 	ssize_t len;
13728 	ill_t *ill;
13729 	ipha_t	*ipha;
13730 
13731 	len = MBLKL(mp);
13732 
13733 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13734 		ill = (ill_t *)q->q_ptr;
13735 
13736 		if (!OK_32PTR(mp->b_rptr))
13737 			IP_STAT(ipst, ip_notaligned1);
13738 		else
13739 			IP_STAT(ipst, ip_notaligned2);
13740 		/* Guard against bogus device drivers */
13741 		if (len < 0) {
13742 			/* clear b_prev - used by ip_mroute_decap */
13743 			mp->b_prev = NULL;
13744 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13745 			freemsg(mp);
13746 			return (B_FALSE);
13747 		}
13748 
13749 		if (ip_rput_pullups++ == 0) {
13750 			ipha = (ipha_t *)mp->b_rptr;
13751 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13752 			    "ip_check_and_align_header: %s forced us to "
13753 			    " pullup pkt, hdr len %ld, hdr addr %p",
13754 			    ill->ill_name, len, ipha);
13755 		}
13756 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13757 			/* clear b_prev - used by ip_mroute_decap */
13758 			mp->b_prev = NULL;
13759 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13760 			freemsg(mp);
13761 			return (B_FALSE);
13762 		}
13763 	}
13764 	return (B_TRUE);
13765 }
13766 
13767 ire_t *
13768 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13769 {
13770 	ire_t		*new_ire;
13771 	ill_t		*ire_ill;
13772 	uint_t		ifindex;
13773 	ip_stack_t	*ipst = ill->ill_ipst;
13774 	boolean_t	strict_check = B_FALSE;
13775 
13776 	/*
13777 	 * This packet came in on an interface other than the one associated
13778 	 * with the first ire we found for the destination address. We do
13779 	 * another ire lookup here, using the ingress ill, to see if the
13780 	 * interface is in an interface group.
13781 	 * As long as the ills belong to the same group, we don't consider
13782 	 * them to be arriving on the wrong interface. Thus, if the switch
13783 	 * is doing inbound load spreading, we won't drop packets when the
13784 	 * ip*_strict_dst_multihoming switch is on. Note, the same holds true
13785 	 * for 'usesrc groups' where the destination address may belong to
13786 	 * another interface to allow multipathing to happen.
13787 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
13788 	 * where the local address may not be unique. In this case we were
13789 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
13790 	 * actually returned. The new lookup, which is more specific, should
13791 	 * only find the IRE_LOCAL associated with the ingress ill if one
13792 	 * exists.
13793 	 */
13794 
13795 	if (ire->ire_ipversion == IPV4_VERSION) {
13796 		if (ipst->ips_ip_strict_dst_multihoming)
13797 			strict_check = B_TRUE;
13798 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
13799 		    ill->ill_ipif, ALL_ZONES, NULL,
13800 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13801 	} else {
13802 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
13803 		if (ipst->ips_ipv6_strict_dst_multihoming)
13804 			strict_check = B_TRUE;
13805 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
13806 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
13807 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13808 	}
13809 	/*
13810 	 * If the same ire that was returned in ip_input() is found then this
13811 	 * is an indication that interface groups are in use. The packet
13812 	 * arrived on a different ill in the group than the one associated with
13813 	 * the destination address.  If a different ire was found then the same
13814 	 * IP address must be hosted on multiple ills. This is possible with
13815 	 * unnumbered point2point interfaces. We switch to use this new ire in
13816 	 * order to have accurate interface statistics.
13817 	 */
13818 	if (new_ire != NULL) {
13819 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
13820 			ire_refrele(ire);
13821 			ire = new_ire;
13822 		} else {
13823 			ire_refrele(new_ire);
13824 		}
13825 		return (ire);
13826 	} else if ((ire->ire_rfq == NULL) &&
13827 	    (ire->ire_ipversion == IPV4_VERSION)) {
13828 		/*
13829 		 * The best match could have been the original ire which
13830 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
13831 		 * the strict multihoming checks are irrelevant as we consider
13832 		 * local addresses hosted on lo0 to be interface agnostic. We
13833 		 * only expect a null ire_rfq on IREs which are associated with
13834 		 * lo0 hence we can return now.
13835 		 */
13836 		return (ire);
13837 	}
13838 
13839 	/*
13840 	 * Chase pointers once and store locally.
13841 	 */
13842 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
13843 	    (ill_t *)(ire->ire_rfq->q_ptr);
13844 	ifindex = ill->ill_usesrc_ifindex;
13845 
13846 	/*
13847 	 * Check if it's a legal address on the 'usesrc' interface.
13848 	 */
13849 	if ((ifindex != 0) && (ire_ill != NULL) &&
13850 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
13851 		return (ire);
13852 	}
13853 
13854 	/*
13855 	 * If the ip*_strict_dst_multihoming switch is on then we can
13856 	 * only accept this packet if the interface is marked as routing.
13857 	 */
13858 	if (!(strict_check))
13859 		return (ire);
13860 
13861 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
13862 	    ILLF_ROUTER) != 0) {
13863 		return (ire);
13864 	}
13865 
13866 	ire_refrele(ire);
13867 	return (NULL);
13868 }
13869 
13870 ire_t *
13871 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13872 {
13873 	ipha_t	*ipha;
13874 	ire_t	*src_ire;
13875 	ill_t	*stq_ill;
13876 	uint_t	hlen;
13877 	uint_t	pkt_len;
13878 	uint32_t sum;
13879 	queue_t	*dev_q;
13880 	ip_stack_t *ipst = ill->ill_ipst;
13881 	mblk_t *fpmp;
13882 
13883 	ipha = (ipha_t *)mp->b_rptr;
13884 
13885 	/*
13886 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13887 	 * The loopback address check for both src and dst has already
13888 	 * been checked in ip_input
13889 	 */
13890 
13891 	if (dst == INADDR_ANY || CLASSD(ipha->ipha_src)) {
13892 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13893 		goto drop;
13894 	}
13895 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13896 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
13897 
13898 	if (src_ire != NULL) {
13899 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13900 		ire_refrele(src_ire);
13901 		goto drop;
13902 	}
13903 
13904 
13905 	/* No ire cache of nexthop. So first create one  */
13906 	if (ire == NULL) {
13907 		boolean_t check_multirt;
13908 
13909 		ire = ire_forward(dst, &check_multirt, NULL, NULL, NULL, ipst);
13910 		/*
13911 		 * We only come to ip_fast_forward if ip_cgtp_filter is
13912 		 * is not set. So upon return from ire_forward
13913 		 * check_multirt should remain as false.
13914 		 */
13915 		if (ire == NULL) {
13916 			/* An attempt was made to forward the packet */
13917 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13918 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13919 			mp->b_prev = mp->b_next = 0;
13920 			/* send icmp unreachable */
13921 			/* Sent by forwarding path, and router is global zone */
13922 			if (ip_source_routed(ipha, ipst)) {
13923 				icmp_unreachable(ill->ill_wq, mp,
13924 				    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID,
13925 				    ipst);
13926 			} else {
13927 				icmp_unreachable(ill->ill_wq, mp,
13928 				    ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13929 				    ipst);
13930 			}
13931 			return (ire);
13932 		}
13933 	}
13934 
13935 	/*
13936 	 * Forwarding fastpath exception case:
13937 	 * If either of the follwoing case is true, we take
13938 	 * the slowpath
13939 	 *	o forwarding is not enabled
13940 	 *	o incoming and outgoing interface are the same, or the same
13941 	 *	  IPMP group
13942 	 *	o corresponding ire is in incomplete state
13943 	 *	o packet needs fragmentation
13944 	 *	o ARP cache is not resolved
13945 	 *
13946 	 * The codeflow from here on is thus:
13947 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
13948 	 */
13949 	pkt_len = ntohs(ipha->ipha_length);
13950 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
13951 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
13952 	    !(ill->ill_flags & ILLF_ROUTER) ||
13953 	    (ill == stq_ill) ||
13954 	    (ill->ill_group != NULL && ill->ill_group == stq_ill->ill_group) ||
13955 	    (ire->ire_nce == NULL) ||
13956 	    (pkt_len > ire->ire_max_frag) ||
13957 	    ((fpmp = ire->ire_nce->nce_fp_mp) == NULL) ||
13958 	    ((hlen = MBLKL(fpmp)) > MBLKHEAD(mp)) ||
13959 	    ipha->ipha_ttl <= 1) {
13960 		ip_rput_process_forward(ill->ill_rq, mp, ire,
13961 		    ipha, ill, B_FALSE);
13962 		return (ire);
13963 	}
13964 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13965 
13966 	DTRACE_PROBE4(ip4__forwarding__start,
13967 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
13968 
13969 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
13970 	    ipst->ips_ipv4firewall_forwarding,
13971 	    ill, stq_ill, ipha, mp, mp, ipst);
13972 
13973 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
13974 
13975 	if (mp == NULL)
13976 		goto drop;
13977 
13978 	mp->b_datap->db_struioun.cksum.flags = 0;
13979 	/* Adjust the checksum to reflect the ttl decrement. */
13980 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
13981 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
13982 	ipha->ipha_ttl--;
13983 
13984 	/*
13985 	 * Write the link layer header.  We can do this safely here,
13986 	 * because we have already tested to make sure that the IP
13987 	 * policy is not set, and that we have a fast path destination
13988 	 * header.
13989 	 */
13990 	mp->b_rptr -= hlen;
13991 	bcopy(fpmp->b_rptr, mp->b_rptr, hlen);
13992 
13993 	UPDATE_IB_PKT_COUNT(ire);
13994 	ire->ire_last_used_time = lbolt;
13995 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
13996 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
13997 	UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets, pkt_len);
13998 
13999 	dev_q = ire->ire_stq->q_next;
14000 	if ((dev_q->q_next != NULL || dev_q->q_first != NULL) &&
14001 	    !canputnext(ire->ire_stq)) {
14002 		goto indiscard;
14003 	}
14004 	if (ILL_DLS_CAPABLE(stq_ill)) {
14005 		/*
14006 		 * Send the packet directly to DLD, where it
14007 		 * may be queued depending on the availability
14008 		 * of transmit resources at the media layer.
14009 		 */
14010 		IP_DLS_ILL_TX(stq_ill, ipha, mp, ipst);
14011 	} else {
14012 		DTRACE_PROBE4(ip4__physical__out__start,
14013 		    ill_t *, NULL, ill_t *, stq_ill,
14014 		    ipha_t *, ipha, mblk_t *, mp);
14015 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
14016 		    ipst->ips_ipv4firewall_physical_out,
14017 		    NULL, stq_ill, ipha, mp, mp, ipst);
14018 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
14019 		if (mp == NULL)
14020 			goto drop;
14021 		putnext(ire->ire_stq, mp);
14022 	}
14023 	return (ire);
14024 
14025 indiscard:
14026 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14027 drop:
14028 	if (mp != NULL)
14029 		freemsg(mp);
14030 	return (ire);
14031 
14032 }
14033 
14034 /*
14035  * This function is called in the forwarding slowpath, when
14036  * either the ire lacks the link-layer address, or the packet needs
14037  * further processing(eg. fragmentation), before transmission.
14038  */
14039 
14040 static void
14041 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14042     ill_t *ill, boolean_t ll_multicast)
14043 {
14044 	ill_group_t	*ill_group;
14045 	ill_group_t	*ire_group;
14046 	queue_t		*dev_q;
14047 	ire_t		*src_ire;
14048 	ip_stack_t	*ipst = ill->ill_ipst;
14049 
14050 	ASSERT(ire->ire_stq != NULL);
14051 
14052 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14053 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14054 
14055 	if (ll_multicast != 0) {
14056 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14057 		goto drop_pkt;
14058 	}
14059 
14060 	/*
14061 	 * check if ipha_src is a broadcast address. Note that this
14062 	 * check is redundant when we get here from ip_fast_forward()
14063 	 * which has already done this check. However, since we can
14064 	 * also get here from ip_rput_process_broadcast() or, for
14065 	 * for the slow path through ip_fast_forward(), we perform
14066 	 * the check again for code-reusability
14067 	 */
14068 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14069 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14070 	if (src_ire != NULL || ipha->ipha_dst == INADDR_ANY) {
14071 		if (src_ire != NULL)
14072 			ire_refrele(src_ire);
14073 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14074 		ip2dbg(("ip_rput_process_forward: Received packet with"
14075 		    " bad src/dst address on %s\n", ill->ill_name));
14076 		goto drop_pkt;
14077 	}
14078 
14079 	ill_group = ill->ill_group;
14080 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
14081 	/*
14082 	 * Check if we want to forward this one at this time.
14083 	 * We allow source routed packets on a host provided that
14084 	 * they go out the same interface or same interface group
14085 	 * as they came in on.
14086 	 *
14087 	 * XXX To be quicker, we may wish to not chase pointers to
14088 	 * get the ILLF_ROUTER flag and instead store the
14089 	 * forwarding policy in the ire.  An unfortunate
14090 	 * side-effect of that would be requiring an ire flush
14091 	 * whenever the ILLF_ROUTER flag changes.
14092 	 */
14093 	if (((ill->ill_flags &
14094 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
14095 	    ILLF_ROUTER) == 0) &&
14096 	    !(ip_source_routed(ipha, ipst) && (ire->ire_rfq == q ||
14097 	    (ill_group != NULL && ill_group == ire_group)))) {
14098 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14099 		if (ip_source_routed(ipha, ipst)) {
14100 			q = WR(q);
14101 			/*
14102 			 * Clear the indication that this may have
14103 			 * hardware checksum as we are not using it.
14104 			 */
14105 			DB_CKSUMFLAGS(mp) = 0;
14106 			/* Sent by forwarding path, and router is global zone */
14107 			icmp_unreachable(q, mp,
14108 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
14109 			return;
14110 		}
14111 		goto drop_pkt;
14112 	}
14113 
14114 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14115 
14116 	/* Packet is being forwarded. Turning off hwcksum flag. */
14117 	DB_CKSUMFLAGS(mp) = 0;
14118 	if (ipst->ips_ip_g_send_redirects) {
14119 		/*
14120 		 * Check whether the incoming interface and outgoing
14121 		 * interface is part of the same group. If so,
14122 		 * send redirects.
14123 		 *
14124 		 * Check the source address to see if it originated
14125 		 * on the same logical subnet it is going back out on.
14126 		 * If so, we should be able to send it a redirect.
14127 		 * Avoid sending a redirect if the destination
14128 		 * is directly connected (i.e., ipha_dst is the same
14129 		 * as ire_gateway_addr or the ire_addr of the
14130 		 * nexthop IRE_CACHE ), or if the packet was source
14131 		 * routed out this interface.
14132 		 */
14133 		ipaddr_t src, nhop;
14134 		mblk_t	*mp1;
14135 		ire_t	*nhop_ire = NULL;
14136 
14137 		/*
14138 		 * Check whether ire_rfq and q are from the same ill
14139 		 * or if they are not same, they at least belong
14140 		 * to the same group. If so, send redirects.
14141 		 */
14142 		if ((ire->ire_rfq == q ||
14143 		    (ill_group != NULL && ill_group == ire_group)) &&
14144 		    !ip_source_routed(ipha, ipst)) {
14145 
14146 			nhop = (ire->ire_gateway_addr != 0 ?
14147 			    ire->ire_gateway_addr : ire->ire_addr);
14148 
14149 			if (ipha->ipha_dst == nhop) {
14150 				/*
14151 				 * We avoid sending a redirect if the
14152 				 * destination is directly connected
14153 				 * because it is possible that multiple
14154 				 * IP subnets may have been configured on
14155 				 * the link, and the source may not
14156 				 * be on the same subnet as ip destination,
14157 				 * even though they are on the same
14158 				 * physical link.
14159 				 */
14160 				goto sendit;
14161 			}
14162 
14163 			src = ipha->ipha_src;
14164 
14165 			/*
14166 			 * We look up the interface ire for the nexthop,
14167 			 * to see if ipha_src is in the same subnet
14168 			 * as the nexthop.
14169 			 *
14170 			 * Note that, if, in the future, IRE_CACHE entries
14171 			 * are obsoleted,  this lookup will not be needed,
14172 			 * as the ire passed to this function will be the
14173 			 * same as the nhop_ire computed below.
14174 			 */
14175 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14176 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14177 			    0, NULL, MATCH_IRE_TYPE, ipst);
14178 
14179 			if (nhop_ire != NULL) {
14180 				if ((src & nhop_ire->ire_mask) ==
14181 				    (nhop & nhop_ire->ire_mask)) {
14182 					/*
14183 					 * The source is directly connected.
14184 					 * Just copy the ip header (which is
14185 					 * in the first mblk)
14186 					 */
14187 					mp1 = copyb(mp);
14188 					if (mp1 != NULL) {
14189 						icmp_send_redirect(WR(q), mp1,
14190 						    nhop, ipst);
14191 					}
14192 				}
14193 				ire_refrele(nhop_ire);
14194 			}
14195 		}
14196 	}
14197 sendit:
14198 	dev_q = ire->ire_stq->q_next;
14199 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
14200 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14201 		freemsg(mp);
14202 		return;
14203 	}
14204 
14205 	ip_rput_forward(ire, ipha, mp, ill);
14206 	return;
14207 
14208 drop_pkt:
14209 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14210 	freemsg(mp);
14211 }
14212 
14213 ire_t *
14214 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14215     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14216 {
14217 	queue_t		*q;
14218 	uint16_t	hcksumflags;
14219 	ip_stack_t	*ipst = ill->ill_ipst;
14220 
14221 	q = *qp;
14222 
14223 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14224 
14225 	/*
14226 	 * Clear the indication that this may have hardware
14227 	 * checksum as we are not using it for forwarding.
14228 	 */
14229 	hcksumflags = DB_CKSUMFLAGS(mp);
14230 	DB_CKSUMFLAGS(mp) = 0;
14231 
14232 	/*
14233 	 * Directed broadcast forwarding: if the packet came in over a
14234 	 * different interface then it is routed out over we can forward it.
14235 	 */
14236 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14237 		ire_refrele(ire);
14238 		freemsg(mp);
14239 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14240 		return (NULL);
14241 	}
14242 	/*
14243 	 * For multicast we have set dst to be INADDR_BROADCAST
14244 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
14245 	 * only for broadcast packets.
14246 	 */
14247 	if (!CLASSD(ipha->ipha_dst)) {
14248 		ire_t *new_ire;
14249 		ipif_t *ipif;
14250 		/*
14251 		 * For ill groups, as the switch duplicates broadcasts
14252 		 * across all the ports, we need to filter out and
14253 		 * send up only one copy. There is one copy for every
14254 		 * broadcast address on each ill. Thus, we look for a
14255 		 * specific IRE on this ill and look at IRE_MARK_NORECV
14256 		 * later to see whether this ill is eligible to receive
14257 		 * them or not. ill_nominate_bcast_rcv() nominates only
14258 		 * one set of IREs for receiving.
14259 		 */
14260 
14261 		ipif = ipif_get_next_ipif(NULL, ill);
14262 		if (ipif == NULL) {
14263 			ire_refrele(ire);
14264 			freemsg(mp);
14265 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14266 			return (NULL);
14267 		}
14268 		new_ire = ire_ctable_lookup(dst, 0, 0,
14269 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14270 		ipif_refrele(ipif);
14271 
14272 		if (new_ire != NULL) {
14273 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
14274 				ire_refrele(ire);
14275 				ire_refrele(new_ire);
14276 				freemsg(mp);
14277 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14278 				return (NULL);
14279 			}
14280 			/*
14281 			 * In the special case of multirouted broadcast
14282 			 * packets, we unconditionally need to "gateway"
14283 			 * them to the appropriate interface here.
14284 			 * In the normal case, this cannot happen, because
14285 			 * there is no broadcast IRE tagged with the
14286 			 * RTF_MULTIRT flag.
14287 			 */
14288 			if (new_ire->ire_flags & RTF_MULTIRT) {
14289 				ire_refrele(new_ire);
14290 				if (ire->ire_rfq != NULL) {
14291 					q = ire->ire_rfq;
14292 					*qp = q;
14293 				}
14294 			} else {
14295 				ire_refrele(ire);
14296 				ire = new_ire;
14297 			}
14298 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14299 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14300 				/*
14301 				 * Free the message if
14302 				 * ip_g_forward_directed_bcast is turned
14303 				 * off for non-local broadcast.
14304 				 */
14305 				ire_refrele(ire);
14306 				freemsg(mp);
14307 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14308 				return (NULL);
14309 			}
14310 		} else {
14311 			/*
14312 			 * This CGTP packet successfully passed the
14313 			 * CGTP filter, but the related CGTP
14314 			 * broadcast IRE has not been found,
14315 			 * meaning that the redundant ipif is
14316 			 * probably down. However, if we discarded
14317 			 * this packet, its duplicate would be
14318 			 * filtered out by the CGTP filter so none
14319 			 * of them would get through. So we keep
14320 			 * going with this one.
14321 			 */
14322 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14323 			if (ire->ire_rfq != NULL) {
14324 				q = ire->ire_rfq;
14325 				*qp = q;
14326 			}
14327 		}
14328 	}
14329 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14330 		/*
14331 		 * Verify that there are not more then one
14332 		 * IRE_BROADCAST with this broadcast address which
14333 		 * has ire_stq set.
14334 		 * TODO: simplify, loop over all IRE's
14335 		 */
14336 		ire_t	*ire1;
14337 		int	num_stq = 0;
14338 		mblk_t	*mp1;
14339 
14340 		/* Find the first one with ire_stq set */
14341 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14342 		for (ire1 = ire; ire1 &&
14343 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14344 		    ire1 = ire1->ire_next)
14345 			;
14346 		if (ire1) {
14347 			ire_refrele(ire);
14348 			ire = ire1;
14349 			IRE_REFHOLD(ire);
14350 		}
14351 
14352 		/* Check if there are additional ones with stq set */
14353 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14354 			if (ire->ire_addr != ire1->ire_addr)
14355 				break;
14356 			if (ire1->ire_stq) {
14357 				num_stq++;
14358 				break;
14359 			}
14360 		}
14361 		rw_exit(&ire->ire_bucket->irb_lock);
14362 		if (num_stq == 1 && ire->ire_stq != NULL) {
14363 			ip1dbg(("ip_rput_process_broadcast: directed "
14364 			    "broadcast to 0x%x\n",
14365 			    ntohl(ire->ire_addr)));
14366 			mp1 = copymsg(mp);
14367 			if (mp1) {
14368 				switch (ipha->ipha_protocol) {
14369 				case IPPROTO_UDP:
14370 					ip_udp_input(q, mp1, ipha, ire, ill);
14371 					break;
14372 				default:
14373 					ip_proto_input(q, mp1, ipha, ire, ill,
14374 					    B_FALSE);
14375 					break;
14376 				}
14377 			}
14378 			/*
14379 			 * Adjust ttl to 2 (1+1 - the forward engine
14380 			 * will decrement it by one.
14381 			 */
14382 			if (ip_csum_hdr(ipha)) {
14383 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14384 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14385 				freemsg(mp);
14386 				ire_refrele(ire);
14387 				return (NULL);
14388 			}
14389 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14390 			ipha->ipha_hdr_checksum = 0;
14391 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14392 			ip_rput_process_forward(q, mp, ire, ipha,
14393 			    ill, ll_multicast);
14394 			ire_refrele(ire);
14395 			return (NULL);
14396 		}
14397 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14398 		    ntohl(ire->ire_addr)));
14399 	}
14400 
14401 
14402 	/* Restore any hardware checksum flags */
14403 	DB_CKSUMFLAGS(mp) = hcksumflags;
14404 	return (ire);
14405 }
14406 
14407 /* ARGSUSED */
14408 static boolean_t
14409 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14410     int *ll_multicast, ipaddr_t *dstp)
14411 {
14412 	ip_stack_t	*ipst = ill->ill_ipst;
14413 
14414 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14415 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14416 	    ntohs(ipha->ipha_length));
14417 
14418 	/*
14419 	 * Forward packets only if we have joined the allmulti
14420 	 * group on this interface.
14421 	 */
14422 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14423 		int retval;
14424 
14425 		/*
14426 		 * Clear the indication that this may have hardware
14427 		 * checksum as we are not using it.
14428 		 */
14429 		DB_CKSUMFLAGS(mp) = 0;
14430 		retval = ip_mforward(ill, ipha, mp);
14431 		/* ip_mforward updates mib variables if needed */
14432 		/* clear b_prev - used by ip_mroute_decap */
14433 		mp->b_prev = NULL;
14434 
14435 		switch (retval) {
14436 		case 0:
14437 			/*
14438 			 * pkt is okay and arrived on phyint.
14439 			 *
14440 			 * If we are running as a multicast router
14441 			 * we need to see all IGMP and/or PIM packets.
14442 			 */
14443 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14444 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14445 				goto done;
14446 			}
14447 			break;
14448 		case -1:
14449 			/* pkt is mal-formed, toss it */
14450 			goto drop_pkt;
14451 		case 1:
14452 			/* pkt is okay and arrived on a tunnel */
14453 			/*
14454 			 * If we are running a multicast router
14455 			 *  we need to see all igmp packets.
14456 			 */
14457 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14458 				*dstp = INADDR_BROADCAST;
14459 				*ll_multicast = 1;
14460 				return (B_FALSE);
14461 			}
14462 
14463 			goto drop_pkt;
14464 		}
14465 	}
14466 
14467 	ILM_WALKER_HOLD(ill);
14468 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14469 		/*
14470 		 * This might just be caused by the fact that
14471 		 * multiple IP Multicast addresses map to the same
14472 		 * link layer multicast - no need to increment counter!
14473 		 */
14474 		ILM_WALKER_RELE(ill);
14475 		freemsg(mp);
14476 		return (B_TRUE);
14477 	}
14478 	ILM_WALKER_RELE(ill);
14479 done:
14480 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14481 	/*
14482 	 * This assumes the we deliver to all streams for multicast
14483 	 * and broadcast packets.
14484 	 */
14485 	*dstp = INADDR_BROADCAST;
14486 	*ll_multicast = 1;
14487 	return (B_FALSE);
14488 drop_pkt:
14489 	ip2dbg(("ip_rput: drop pkt\n"));
14490 	freemsg(mp);
14491 	return (B_TRUE);
14492 }
14493 
14494 static boolean_t
14495 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14496     int *ll_multicast, mblk_t **mpp)
14497 {
14498 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14499 	boolean_t must_copy = B_FALSE;
14500 	struct iocblk   *iocp;
14501 	ipha_t		*ipha;
14502 	ip_stack_t	*ipst = ill->ill_ipst;
14503 
14504 #define	rptr    ((uchar_t *)ipha)
14505 
14506 	first_mp = *first_mpp;
14507 	mp = *mpp;
14508 
14509 	ASSERT(first_mp == mp);
14510 
14511 	/*
14512 	 * if db_ref > 1 then copymsg and free original. Packet may be
14513 	 * changed and do not want other entity who has a reference to this
14514 	 * message to trip over the changes. This is a blind change because
14515 	 * trying to catch all places that might change packet is too
14516 	 * difficult (since it may be a module above this one)
14517 	 *
14518 	 * This corresponds to the non-fast path case. We walk down the full
14519 	 * chain in this case, and check the db_ref count of all the dblks,
14520 	 * and do a copymsg if required. It is possible that the db_ref counts
14521 	 * of the data blocks in the mblk chain can be different.
14522 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14523 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14524 	 * 'snoop' is running.
14525 	 */
14526 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14527 		if (mp1->b_datap->db_ref > 1) {
14528 			must_copy = B_TRUE;
14529 			break;
14530 		}
14531 	}
14532 
14533 	if (must_copy) {
14534 		mp1 = copymsg(mp);
14535 		if (mp1 == NULL) {
14536 			for (mp1 = mp; mp1 != NULL;
14537 			    mp1 = mp1->b_cont) {
14538 				mp1->b_next = NULL;
14539 				mp1->b_prev = NULL;
14540 			}
14541 			freemsg(mp);
14542 			if (ill != NULL) {
14543 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14544 			} else {
14545 				BUMP_MIB(&ipst->ips_ip_mib,
14546 				    ipIfStatsInDiscards);
14547 			}
14548 			return (B_TRUE);
14549 		}
14550 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14551 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14552 			/* Copy b_prev - used by ip_mroute_decap */
14553 			to_mp->b_prev = from_mp->b_prev;
14554 			from_mp->b_prev = NULL;
14555 		}
14556 		*first_mpp = first_mp = mp1;
14557 		freemsg(mp);
14558 		mp = mp1;
14559 		*mpp = mp1;
14560 	}
14561 
14562 	ipha = (ipha_t *)mp->b_rptr;
14563 
14564 	/*
14565 	 * previous code has a case for M_DATA.
14566 	 * We want to check how that happens.
14567 	 */
14568 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14569 	switch (first_mp->b_datap->db_type) {
14570 	case M_PROTO:
14571 	case M_PCPROTO:
14572 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14573 		    DL_UNITDATA_IND) {
14574 			/* Go handle anything other than data elsewhere. */
14575 			ip_rput_dlpi(q, mp);
14576 			return (B_TRUE);
14577 		}
14578 		*ll_multicast = ((dl_unitdata_ind_t *)rptr)->dl_group_address;
14579 		/* Ditch the DLPI header. */
14580 		mp1 = mp->b_cont;
14581 		ASSERT(first_mp == mp);
14582 		*first_mpp = mp1;
14583 		freeb(mp);
14584 		*mpp = mp1;
14585 		return (B_FALSE);
14586 	case M_IOCACK:
14587 		ip1dbg(("got iocack "));
14588 		iocp = (struct iocblk *)mp->b_rptr;
14589 		switch (iocp->ioc_cmd) {
14590 		case DL_IOC_HDR_INFO:
14591 			ill = (ill_t *)q->q_ptr;
14592 			ill_fastpath_ack(ill, mp);
14593 			return (B_TRUE);
14594 		case SIOCSTUNPARAM:
14595 		case OSIOCSTUNPARAM:
14596 			/* Go through qwriter_ip */
14597 			break;
14598 		case SIOCGTUNPARAM:
14599 		case OSIOCGTUNPARAM:
14600 			ip_rput_other(NULL, q, mp, NULL);
14601 			return (B_TRUE);
14602 		default:
14603 			putnext(q, mp);
14604 			return (B_TRUE);
14605 		}
14606 		/* FALLTHRU */
14607 	case M_ERROR:
14608 	case M_HANGUP:
14609 		/*
14610 		 * Since this is on the ill stream we unconditionally
14611 		 * bump up the refcount
14612 		 */
14613 		ill_refhold(ill);
14614 		qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14615 		return (B_TRUE);
14616 	case M_CTL:
14617 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14618 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14619 		    IPHADA_M_CTL)) {
14620 			/*
14621 			 * It's an IPsec accelerated packet.
14622 			 * Make sure that the ill from which we received the
14623 			 * packet has enabled IPsec hardware acceleration.
14624 			 */
14625 			if (!(ill->ill_capabilities &
14626 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14627 				/* IPsec kstats: bean counter */
14628 				freemsg(mp);
14629 				return (B_TRUE);
14630 			}
14631 
14632 			/*
14633 			 * Make mp point to the mblk following the M_CTL,
14634 			 * then process according to type of mp.
14635 			 * After this processing, first_mp will point to
14636 			 * the data-attributes and mp to the pkt following
14637 			 * the M_CTL.
14638 			 */
14639 			mp = first_mp->b_cont;
14640 			if (mp == NULL) {
14641 				freemsg(first_mp);
14642 				return (B_TRUE);
14643 			}
14644 			/*
14645 			 * A Hardware Accelerated packet can only be M_DATA
14646 			 * ESP or AH packet.
14647 			 */
14648 			if (mp->b_datap->db_type != M_DATA) {
14649 				/* non-M_DATA IPsec accelerated packet */
14650 				IPSECHW_DEBUG(IPSECHW_PKT,
14651 				    ("non-M_DATA IPsec accelerated pkt\n"));
14652 				freemsg(first_mp);
14653 				return (B_TRUE);
14654 			}
14655 			ipha = (ipha_t *)mp->b_rptr;
14656 			if (ipha->ipha_protocol != IPPROTO_AH &&
14657 			    ipha->ipha_protocol != IPPROTO_ESP) {
14658 				IPSECHW_DEBUG(IPSECHW_PKT,
14659 				    ("non-M_DATA IPsec accelerated pkt\n"));
14660 				freemsg(first_mp);
14661 				return (B_TRUE);
14662 			}
14663 			*mpp = mp;
14664 			return (B_FALSE);
14665 		}
14666 		putnext(q, mp);
14667 		return (B_TRUE);
14668 	case M_IOCNAK:
14669 		ip1dbg(("got iocnak "));
14670 		iocp = (struct iocblk *)mp->b_rptr;
14671 		switch (iocp->ioc_cmd) {
14672 		case SIOCSTUNPARAM:
14673 		case OSIOCSTUNPARAM:
14674 			/*
14675 			 * Since this is on the ill stream we unconditionally
14676 			 * bump up the refcount
14677 			 */
14678 			ill_refhold(ill);
14679 			qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14680 			return (B_TRUE);
14681 		case DL_IOC_HDR_INFO:
14682 		case SIOCGTUNPARAM:
14683 		case OSIOCGTUNPARAM:
14684 			ip_rput_other(NULL, q, mp, NULL);
14685 			return (B_TRUE);
14686 		default:
14687 			break;
14688 		}
14689 		/* FALLTHRU */
14690 	default:
14691 		putnext(q, mp);
14692 		return (B_TRUE);
14693 	}
14694 }
14695 
14696 /* Read side put procedure.  Packets coming from the wire arrive here. */
14697 void
14698 ip_rput(queue_t *q, mblk_t *mp)
14699 {
14700 	ill_t	*ill;
14701 	union DL_primitives *dl;
14702 
14703 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14704 
14705 	ill = (ill_t *)q->q_ptr;
14706 
14707 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14708 		/*
14709 		 * If things are opening or closing, only accept high-priority
14710 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
14711 		 * created; on close, things hanging off the ill may have been
14712 		 * freed already.)
14713 		 */
14714 		dl = (union DL_primitives *)mp->b_rptr;
14715 		if (DB_TYPE(mp) != M_PCPROTO ||
14716 		    dl->dl_primitive == DL_UNITDATA_IND) {
14717 			/*
14718 			 * SIOC[GS]TUNPARAM ioctls can come here.
14719 			 */
14720 			inet_freemsg(mp);
14721 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14722 			    "ip_rput_end: q %p (%S)", q, "uninit");
14723 			return;
14724 		}
14725 	}
14726 
14727 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14728 	    "ip_rput_end: q %p (%S)", q, "end");
14729 
14730 	ip_input(ill, NULL, mp, NULL);
14731 }
14732 
14733 static mblk_t *
14734 ip_fix_dbref(ill_t *ill, mblk_t *mp)
14735 {
14736 	mblk_t *mp1;
14737 	boolean_t adjusted = B_FALSE;
14738 	ip_stack_t *ipst = ill->ill_ipst;
14739 
14740 	IP_STAT(ipst, ip_db_ref);
14741 	/*
14742 	 * The IP_RECVSLLA option depends on having the
14743 	 * link layer header. First check that:
14744 	 * a> the underlying device is of type ether,
14745 	 * since this option is currently supported only
14746 	 * over ethernet.
14747 	 * b> there is enough room to copy over the link
14748 	 * layer header.
14749 	 *
14750 	 * Once the checks are done, adjust rptr so that
14751 	 * the link layer header will be copied via
14752 	 * copymsg. Note that, IFT_ETHER may be returned
14753 	 * by some non-ethernet drivers but in this case
14754 	 * the second check will fail.
14755 	 */
14756 	if (ill->ill_type == IFT_ETHER &&
14757 	    (mp->b_rptr - mp->b_datap->db_base) >=
14758 	    sizeof (struct ether_header)) {
14759 		mp->b_rptr -= sizeof (struct ether_header);
14760 		adjusted = B_TRUE;
14761 	}
14762 	mp1 = copymsg(mp);
14763 
14764 	if (mp1 == NULL) {
14765 		mp->b_next = NULL;
14766 		/* clear b_prev - used by ip_mroute_decap */
14767 		mp->b_prev = NULL;
14768 		freemsg(mp);
14769 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14770 		return (NULL);
14771 	}
14772 
14773 	if (adjusted) {
14774 		/*
14775 		 * Copy is done. Restore the pointer in
14776 		 * the _new_ mblk
14777 		 */
14778 		mp1->b_rptr += sizeof (struct ether_header);
14779 	}
14780 
14781 	/* Copy b_prev - used by ip_mroute_decap */
14782 	mp1->b_prev = mp->b_prev;
14783 	mp->b_prev = NULL;
14784 
14785 	/* preserve the hardware checksum flags and data, if present */
14786 	if (DB_CKSUMFLAGS(mp) != 0) {
14787 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
14788 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
14789 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
14790 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
14791 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
14792 	}
14793 
14794 	freemsg(mp);
14795 	return (mp1);
14796 }
14797 
14798 /*
14799  * Direct read side procedure capable of dealing with chains. GLDv3 based
14800  * drivers call this function directly with mblk chains while STREAMS
14801  * read side procedure ip_rput() calls this for single packet with ip_ring
14802  * set to NULL to process one packet at a time.
14803  *
14804  * The ill will always be valid if this function is called directly from
14805  * the driver.
14806  *
14807  * If ip_input() is called from GLDv3:
14808  *
14809  *   - This must be a non-VLAN IP stream.
14810  *   - 'mp' is either an untagged or a special priority-tagged packet.
14811  *   - Any VLAN tag that was in the MAC header has been stripped.
14812  *
14813  * If the IP header in packet is not 32-bit aligned, every message in the
14814  * chain will be aligned before further operations. This is required on SPARC
14815  * platform.
14816  */
14817 /* ARGSUSED */
14818 void
14819 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14820     struct mac_header_info_s *mhip)
14821 {
14822 	ipaddr_t		dst = NULL;
14823 	ipaddr_t		prev_dst;
14824 	ire_t			*ire = NULL;
14825 	ipha_t			*ipha;
14826 	uint_t			pkt_len;
14827 	ssize_t			len;
14828 	uint_t			opt_len;
14829 	int			ll_multicast;
14830 	int			cgtp_flt_pkt;
14831 	queue_t			*q = ill->ill_rq;
14832 	squeue_t		*curr_sqp = NULL;
14833 	mblk_t 			*head = NULL;
14834 	mblk_t			*tail = NULL;
14835 	mblk_t			*first_mp;
14836 	mblk_t 			*mp;
14837 	mblk_t			*dmp;
14838 	int			cnt = 0;
14839 	ip_stack_t		*ipst = ill->ill_ipst;
14840 
14841 	ASSERT(mp_chain != NULL);
14842 	ASSERT(ill != NULL);
14843 
14844 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14845 
14846 #define	rptr	((uchar_t *)ipha)
14847 
14848 	while (mp_chain != NULL) {
14849 		first_mp = mp = mp_chain;
14850 		mp_chain = mp_chain->b_next;
14851 		mp->b_next = NULL;
14852 		ll_multicast = 0;
14853 
14854 		/*
14855 		 * We do ire caching from one iteration to
14856 		 * another. In the event the packet chain contains
14857 		 * all packets from the same dst, this caching saves
14858 		 * an ire_cache_lookup for each of the succeeding
14859 		 * packets in a packet chain.
14860 		 */
14861 		prev_dst = dst;
14862 
14863 		/*
14864 		 * if db_ref > 1 then copymsg and free original. Packet
14865 		 * may be changed and we do not want the other entity
14866 		 * who has a reference to this message to trip over the
14867 		 * changes. This is a blind change because trying to
14868 		 * catch all places that might change the packet is too
14869 		 * difficult.
14870 		 *
14871 		 * This corresponds to the fast path case, where we have
14872 		 * a chain of M_DATA mblks.  We check the db_ref count
14873 		 * of only the 1st data block in the mblk chain. There
14874 		 * doesn't seem to be a reason why a device driver would
14875 		 * send up data with varying db_ref counts in the mblk
14876 		 * chain. In any case the Fast path is a private
14877 		 * interface, and our drivers don't do such a thing.
14878 		 * Given the above assumption, there is no need to walk
14879 		 * down the entire mblk chain (which could have a
14880 		 * potential performance problem)
14881 		 */
14882 
14883 		if (DB_REF(mp) > 1) {
14884 			if ((mp = ip_fix_dbref(ill, mp)) == NULL)
14885 				continue;
14886 		}
14887 
14888 		/*
14889 		 * Check and align the IP header.
14890 		 */
14891 		first_mp = mp;
14892 		if (DB_TYPE(mp) == M_DATA) {
14893 			dmp = mp;
14894 		} else if (DB_TYPE(mp) == M_PROTO &&
14895 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14896 			dmp = mp->b_cont;
14897 		} else {
14898 			dmp = NULL;
14899 		}
14900 		if (dmp != NULL) {
14901 			/*
14902 			 * IP header ptr not aligned?
14903 			 * OR IP header not complete in first mblk
14904 			 */
14905 			if (!OK_32PTR(dmp->b_rptr) ||
14906 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
14907 				if (!ip_check_and_align_header(q, dmp, ipst))
14908 					continue;
14909 			}
14910 		}
14911 
14912 		/*
14913 		 * ip_input fast path
14914 		 */
14915 
14916 		/* mblk type is not M_DATA */
14917 		if (DB_TYPE(mp) != M_DATA) {
14918 			if (ip_rput_process_notdata(q, &first_mp, ill,
14919 			    &ll_multicast, &mp))
14920 				continue;
14921 
14922 			/*
14923 			 * The only way we can get here is if we had a
14924 			 * packet that was either a DL_UNITDATA_IND or
14925 			 * an M_CTL for an IPsec accelerated packet.
14926 			 *
14927 			 * In either case, the first_mp will point to
14928 			 * the leading M_PROTO or M_CTL.
14929 			 */
14930 			ASSERT(first_mp != NULL);
14931 		}
14932 
14933 		/* Make sure its an M_DATA and that its aligned */
14934 		ASSERT(DB_TYPE(mp) == M_DATA);
14935 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
14936 
14937 		ipha = (ipha_t *)mp->b_rptr;
14938 		len = mp->b_wptr - rptr;
14939 		pkt_len = ntohs(ipha->ipha_length);
14940 
14941 		/*
14942 		 * We must count all incoming packets, even if they end
14943 		 * up being dropped later on.
14944 		 */
14945 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
14946 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
14947 
14948 		/* multiple mblk or too short */
14949 		len -= pkt_len;
14950 		if (len != 0) {
14951 			/*
14952 			 * Make sure we have data length consistent
14953 			 * with the IP header.
14954 			 */
14955 			if (mp->b_cont == NULL) {
14956 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14957 					BUMP_MIB(ill->ill_ip_mib,
14958 					    ipIfStatsInHdrErrors);
14959 					ip2dbg(("ip_input: drop pkt\n"));
14960 					freemsg(mp);
14961 					continue;
14962 				}
14963 				mp->b_wptr = rptr + pkt_len;
14964 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
14965 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14966 					BUMP_MIB(ill->ill_ip_mib,
14967 					    ipIfStatsInHdrErrors);
14968 					ip2dbg(("ip_input: drop pkt\n"));
14969 					freemsg(mp);
14970 					continue;
14971 				}
14972 				(void) adjmsg(mp, -len);
14973 				IP_STAT(ipst, ip_multimblk3);
14974 			}
14975 		}
14976 
14977 		/* Obtain the dst of the current packet */
14978 		dst = ipha->ipha_dst;
14979 
14980 		/*
14981 		 * The following test for loopback is faster than
14982 		 * IP_LOOPBACK_ADDR(), because it avoids any bitwise
14983 		 * operations.
14984 		 * Note that these addresses are always in network byte order
14985 		 */
14986 		if (((*(uchar_t *)&ipha->ipha_dst) == 127) ||
14987 		    ((*(uchar_t *)&ipha->ipha_src) == 127)) {
14988 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
14989 			freemsg(mp);
14990 			continue;
14991 		}
14992 
14993 		/*
14994 		 * The event for packets being received from a 'physical'
14995 		 * interface is placed after validation of the source and/or
14996 		 * destination address as being local so that packets can be
14997 		 * redirected to loopback addresses using ipnat.
14998 		 */
14999 		DTRACE_PROBE4(ip4__physical__in__start,
15000 		    ill_t *, ill, ill_t *, NULL,
15001 		    ipha_t *, ipha, mblk_t *, first_mp);
15002 
15003 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15004 		    ipst->ips_ipv4firewall_physical_in,
15005 		    ill, NULL, ipha, first_mp, mp, ipst);
15006 
15007 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
15008 
15009 		if (first_mp == NULL) {
15010 			continue;
15011 		}
15012 		dst = ipha->ipha_dst;
15013 
15014 		/*
15015 		 * Attach any necessary label information to
15016 		 * this packet
15017 		 */
15018 		if (is_system_labeled() &&
15019 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
15020 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
15021 			freemsg(mp);
15022 			continue;
15023 		}
15024 
15025 		/*
15026 		 * Reuse the cached ire only if the ipha_dst of the previous
15027 		 * packet is the same as the current packet AND it is not
15028 		 * INADDR_ANY.
15029 		 */
15030 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15031 		    (ire != NULL)) {
15032 			ire_refrele(ire);
15033 			ire = NULL;
15034 		}
15035 		opt_len = ipha->ipha_version_and_hdr_length -
15036 		    IP_SIMPLE_HDR_VERSION;
15037 
15038 		/*
15039 		 * Check to see if we can take the fastpath.
15040 		 * That is possible if the following conditions are met
15041 		 *	o Tsol disabled
15042 		 *	o CGTP disabled
15043 		 *	o ipp_action_count is 0
15044 		 *	o no options in the packet
15045 		 *	o not a RSVP packet
15046 		 * 	o not a multicast packet
15047 		 *	o ill not in IP_DHCPINIT_IF mode
15048 		 */
15049 		if (!is_system_labeled() &&
15050 		    !ipst->ips_ip_cgtp_filter && ipp_action_count == 0 &&
15051 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
15052 		    !ll_multicast && !CLASSD(dst) && ill->ill_dhcpinit == 0) {
15053 			if (ire == NULL)
15054 				ire = ire_cache_lookup(dst, ALL_ZONES, NULL,
15055 				    ipst);
15056 
15057 			/* incoming packet is for forwarding */
15058 			if (ire == NULL || (ire->ire_type & IRE_CACHE)) {
15059 				ire = ip_fast_forward(ire, dst, ill, mp);
15060 				continue;
15061 			}
15062 			/* incoming packet is for local consumption */
15063 			if (ire->ire_type & IRE_LOCAL)
15064 				goto local;
15065 		}
15066 
15067 		/*
15068 		 * Disable ire caching for anything more complex
15069 		 * than the simple fast path case we checked for above.
15070 		 */
15071 		if (ire != NULL) {
15072 			ire_refrele(ire);
15073 			ire = NULL;
15074 		}
15075 
15076 		/*
15077 		 * Brutal hack for DHCPv4 unicast: RFC2131 allows a DHCP
15078 		 * server to unicast DHCP packets to a DHCP client using the
15079 		 * IP address it is offering to the client.  This can be
15080 		 * disabled through the "broadcast bit", but not all DHCP
15081 		 * servers honor that bit.  Therefore, to interoperate with as
15082 		 * many DHCP servers as possible, the DHCP client allows the
15083 		 * server to unicast, but we treat those packets as broadcast
15084 		 * here.  Note that we don't rewrite the packet itself since
15085 		 * (a) that would mess up the checksums and (b) the DHCP
15086 		 * client conn is bound to INADDR_ANY so ip_fanout_udp() will
15087 		 * hand it the packet regardless.
15088 		 */
15089 		if (ill->ill_dhcpinit != 0 &&
15090 		    IS_SIMPLE_IPH(ipha) && ipha->ipha_protocol == IPPROTO_UDP &&
15091 		    pullupmsg(mp, sizeof (ipha_t) + sizeof (udpha_t)) == 1) {
15092 			udpha_t *udpha;
15093 
15094 			/*
15095 			 * Reload ipha since pullupmsg() can change b_rptr.
15096 			 */
15097 			ipha = (ipha_t *)mp->b_rptr;
15098 			udpha = (udpha_t *)&ipha[1];
15099 
15100 			if (ntohs(udpha->uha_dst_port) == IPPORT_BOOTPC) {
15101 				DTRACE_PROBE2(ip4__dhcpinit__pkt, ill_t *, ill,
15102 				    mblk_t *, mp);
15103 				dst = INADDR_BROADCAST;
15104 			}
15105 		}
15106 
15107 		/* Full-blown slow path */
15108 		if (opt_len != 0) {
15109 			if (len != 0)
15110 				IP_STAT(ipst, ip_multimblk4);
15111 			else
15112 				IP_STAT(ipst, ip_ipoptions);
15113 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15114 			    &dst, ipst))
15115 				continue;
15116 		}
15117 
15118 		/*
15119 		 * Invoke the CGTP (multirouting) filtering module to process
15120 		 * the incoming packet. Packets identified as duplicates
15121 		 * must be discarded. Filtering is active only if the
15122 		 * the ip_cgtp_filter ndd variable is non-zero.
15123 		 */
15124 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15125 		if (ipst->ips_ip_cgtp_filter &&
15126 		    ipst->ips_ip_cgtp_filter_ops != NULL) {
15127 			netstackid_t stackid;
15128 
15129 			stackid = ipst->ips_netstack->netstack_stackid;
15130 			cgtp_flt_pkt =
15131 			    ipst->ips_ip_cgtp_filter_ops->cfo_filter(stackid,
15132 			    ill->ill_phyint->phyint_ifindex, mp);
15133 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15134 				freemsg(first_mp);
15135 				continue;
15136 			}
15137 		}
15138 
15139 		/*
15140 		 * If rsvpd is running, let RSVP daemon handle its processing
15141 		 * and forwarding of RSVP multicast/unicast packets.
15142 		 * If rsvpd is not running but mrouted is running, RSVP
15143 		 * multicast packets are forwarded as multicast traffic
15144 		 * and RSVP unicast packets are forwarded by unicast router.
15145 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15146 		 * packets are not forwarded, but the unicast packets are
15147 		 * forwarded like unicast traffic.
15148 		 */
15149 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15150 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15151 		    NULL) {
15152 			/* RSVP packet and rsvpd running. Treat as ours */
15153 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15154 			/*
15155 			 * This assumes that we deliver to all streams for
15156 			 * multicast and broadcast packets.
15157 			 * We have to force ll_multicast to 1 to handle the
15158 			 * M_DATA messages passed in from ip_mroute_decap.
15159 			 */
15160 			dst = INADDR_BROADCAST;
15161 			ll_multicast = 1;
15162 		} else if (CLASSD(dst)) {
15163 			/* packet is multicast */
15164 			mp->b_next = NULL;
15165 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15166 			    &ll_multicast, &dst))
15167 				continue;
15168 		}
15169 
15170 		if (ire == NULL) {
15171 			ire = ire_cache_lookup(dst, ALL_ZONES,
15172 			    MBLK_GETLABEL(mp), ipst);
15173 		}
15174 
15175 		if (ire == NULL) {
15176 			/*
15177 			 * No IRE for this destination, so it can't be for us.
15178 			 * Unless we are forwarding, drop the packet.
15179 			 * We have to let source routed packets through
15180 			 * since we don't yet know if they are 'ping -l'
15181 			 * packets i.e. if they will go out over the
15182 			 * same interface as they came in on.
15183 			 */
15184 			ire = ip_rput_noire(q, mp, ll_multicast, dst);
15185 			if (ire == NULL)
15186 				continue;
15187 		}
15188 
15189 		/*
15190 		 * Broadcast IRE may indicate either broadcast or
15191 		 * multicast packet
15192 		 */
15193 		if (ire->ire_type == IRE_BROADCAST) {
15194 			/*
15195 			 * Skip broadcast checks if packet is UDP multicast;
15196 			 * we'd rather not enter ip_rput_process_broadcast()
15197 			 * unless the packet is broadcast for real, since
15198 			 * that routine is a no-op for multicast.
15199 			 */
15200 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15201 			    !CLASSD(ipha->ipha_dst)) {
15202 				ire = ip_rput_process_broadcast(&q, mp,
15203 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15204 				    ll_multicast);
15205 				if (ire == NULL)
15206 					continue;
15207 			}
15208 		} else if (ire->ire_stq != NULL) {
15209 			/* fowarding? */
15210 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15211 			    ll_multicast);
15212 			/* ip_rput_process_forward consumed the packet */
15213 			continue;
15214 		}
15215 
15216 local:
15217 		/*
15218 		 * If the queue in the ire is different to the ingress queue
15219 		 * then we need to check to see if we can accept the packet.
15220 		 * Note that for multicast packets and broadcast packets sent
15221 		 * to a broadcast address which is shared between multiple
15222 		 * interfaces we should not do this since we just got a random
15223 		 * broadcast ire.
15224 		 */
15225 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15226 			if ((ire = ip_check_multihome(&ipha->ipha_dst, ire,
15227 			    ill)) == NULL) {
15228 				/* Drop packet */
15229 				BUMP_MIB(ill->ill_ip_mib,
15230 				    ipIfStatsForwProhibits);
15231 				freemsg(mp);
15232 				continue;
15233 			}
15234 			if (ire->ire_rfq != NULL)
15235 				q = ire->ire_rfq;
15236 		}
15237 
15238 		switch (ipha->ipha_protocol) {
15239 		case IPPROTO_TCP:
15240 			ASSERT(first_mp == mp);
15241 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15242 			    mp, 0, q, ip_ring)) != NULL) {
15243 				if (curr_sqp == NULL) {
15244 					curr_sqp = GET_SQUEUE(mp);
15245 					ASSERT(cnt == 0);
15246 					cnt++;
15247 					head = tail = mp;
15248 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15249 					ASSERT(tail != NULL);
15250 					cnt++;
15251 					tail->b_next = mp;
15252 					tail = mp;
15253 				} else {
15254 					/*
15255 					 * A different squeue. Send the
15256 					 * chain for the previous squeue on
15257 					 * its way. This shouldn't happen
15258 					 * often unless interrupt binding
15259 					 * changes.
15260 					 */
15261 					IP_STAT(ipst, ip_input_multi_squeue);
15262 					squeue_enter_chain(curr_sqp, head,
15263 					    tail, cnt, SQTAG_IP_INPUT);
15264 					curr_sqp = GET_SQUEUE(mp);
15265 					head = mp;
15266 					tail = mp;
15267 					cnt = 1;
15268 				}
15269 			}
15270 			continue;
15271 		case IPPROTO_UDP:
15272 			ASSERT(first_mp == mp);
15273 			ip_udp_input(q, mp, ipha, ire, ill);
15274 			continue;
15275 		case IPPROTO_SCTP:
15276 			ASSERT(first_mp == mp);
15277 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15278 			    q, dst);
15279 			/* ire has been released by ip_sctp_input */
15280 			ire = NULL;
15281 			continue;
15282 		default:
15283 			ip_proto_input(q, first_mp, ipha, ire, ill, B_FALSE);
15284 			continue;
15285 		}
15286 	}
15287 
15288 	if (ire != NULL)
15289 		ire_refrele(ire);
15290 
15291 	if (head != NULL)
15292 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
15293 
15294 	/*
15295 	 * This code is there just to make netperf/ttcp look good.
15296 	 *
15297 	 * Its possible that after being in polling mode (and having cleared
15298 	 * the backlog), squeues have turned the interrupt frequency higher
15299 	 * to improve latency at the expense of more CPU utilization (less
15300 	 * packets per interrupts or more number of interrupts). Workloads
15301 	 * like ttcp/netperf do manage to tickle polling once in a while
15302 	 * but for the remaining time, stay in higher interrupt mode since
15303 	 * their packet arrival rate is pretty uniform and this shows up
15304 	 * as higher CPU utilization. Since people care about CPU utilization
15305 	 * while running netperf/ttcp, turn the interrupt frequency back to
15306 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
15307 	 */
15308 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
15309 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
15310 			ip_ring->rr_poll_state &= ~ILL_POLLING;
15311 			ip_ring->rr_blank(ip_ring->rr_handle,
15312 			    ip_ring->rr_normal_blank_time,
15313 			    ip_ring->rr_normal_pkt_cnt);
15314 		}
15315 		}
15316 
15317 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15318 	    "ip_input_end: q %p (%S)", q, "end");
15319 #undef  rptr
15320 }
15321 
15322 static void
15323 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15324     t_uscalar_t err)
15325 {
15326 	if (dl_err == DL_SYSERR) {
15327 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15328 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15329 		    ill->ill_name, dlpi_prim_str(prim), err);
15330 		return;
15331 	}
15332 
15333 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15334 	    "%s: %s failed: %s\n", ill->ill_name, dlpi_prim_str(prim),
15335 	    dlpi_err_str(dl_err));
15336 }
15337 
15338 /*
15339  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15340  * than DL_UNITDATA_IND messages. If we need to process this message
15341  * exclusively, we call qwriter_ip, in which case we also need to call
15342  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15343  */
15344 void
15345 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15346 {
15347 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15348 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15349 	ill_t		*ill = (ill_t *)q->q_ptr;
15350 	boolean_t	pending;
15351 
15352 	ip1dbg(("ip_rput_dlpi"));
15353 	if (dloa->dl_primitive == DL_ERROR_ACK) {
15354 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
15355 		    "%s (0x%x), unix %u\n", ill->ill_name,
15356 		    dlpi_prim_str(dlea->dl_error_primitive),
15357 		    dlea->dl_error_primitive,
15358 		    dlpi_err_str(dlea->dl_errno),
15359 		    dlea->dl_errno,
15360 		    dlea->dl_unix_errno));
15361 	}
15362 
15363 	/*
15364 	 * If we received an ACK but didn't send a request for it, then it
15365 	 * can't be part of any pending operation; discard up-front.
15366 	 */
15367 	switch (dloa->dl_primitive) {
15368 	case DL_NOTIFY_IND:
15369 		pending = B_TRUE;
15370 		break;
15371 	case DL_ERROR_ACK:
15372 		pending = ill_dlpi_pending(ill, dlea->dl_error_primitive);
15373 		break;
15374 	case DL_OK_ACK:
15375 		pending = ill_dlpi_pending(ill, dloa->dl_correct_primitive);
15376 		break;
15377 	case DL_INFO_ACK:
15378 		pending = ill_dlpi_pending(ill, DL_INFO_REQ);
15379 		break;
15380 	case DL_BIND_ACK:
15381 		pending = ill_dlpi_pending(ill, DL_BIND_REQ);
15382 		break;
15383 	case DL_PHYS_ADDR_ACK:
15384 		pending = ill_dlpi_pending(ill, DL_PHYS_ADDR_REQ);
15385 		break;
15386 	case DL_NOTIFY_ACK:
15387 		pending = ill_dlpi_pending(ill, DL_NOTIFY_REQ);
15388 		break;
15389 	case DL_CONTROL_ACK:
15390 		pending = ill_dlpi_pending(ill, DL_CONTROL_REQ);
15391 		break;
15392 	case DL_CAPABILITY_ACK:
15393 		pending = ill_dlpi_pending(ill, DL_CAPABILITY_REQ);
15394 		break;
15395 	default:
15396 		/* Not a DLPI message we support or were expecting */
15397 		freemsg(mp);
15398 		return;
15399 	}
15400 
15401 	if (!pending) {
15402 		freemsg(mp);
15403 		return;
15404 	}
15405 
15406 	switch (dloa->dl_primitive) {
15407 	case DL_ERROR_ACK:
15408 		if (dlea->dl_error_primitive == DL_UNBIND_REQ) {
15409 			mutex_enter(&ill->ill_lock);
15410 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15411 			cv_signal(&ill->ill_cv);
15412 			mutex_exit(&ill->ill_lock);
15413 		}
15414 		break;
15415 
15416 	case DL_OK_ACK:
15417 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
15418 		    dlpi_prim_str((int)dloa->dl_correct_primitive)));
15419 		switch (dloa->dl_correct_primitive) {
15420 		case DL_UNBIND_REQ:
15421 			mutex_enter(&ill->ill_lock);
15422 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15423 			cv_signal(&ill->ill_cv);
15424 			mutex_exit(&ill->ill_lock);
15425 			break;
15426 
15427 		case DL_ENABMULTI_REQ:
15428 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15429 				ill->ill_dlpi_multicast_state = IDS_OK;
15430 			break;
15431 		}
15432 		break;
15433 	default:
15434 		break;
15435 	}
15436 
15437 	/*
15438 	 * We know the message is one we're waiting for (or DL_NOTIFY_IND),
15439 	 * and we need to become writer to continue to process it. If it's not
15440 	 * a DL_NOTIFY_IND, we assume we're in the middle of an exclusive
15441 	 * operation and pass CUR_OP.  If this isn't true, we'll end up doing
15442 	 * some work as part of the current exclusive operation that actually
15443 	 * is not part of it -- which is wrong, but better than the
15444 	 * alternative of deadlock (if NEW_OP is always used).  Someday, we
15445 	 * should track which DLPI requests have ACKs that we wait on
15446 	 * synchronously so we can know whether to use CUR_OP or NEW_OP.
15447 	 *
15448 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
15449 	 * Since this is on the ill stream we unconditionally bump up the
15450 	 * refcount without doing ILL_CAN_LOOKUP().
15451 	 */
15452 	ill_refhold(ill);
15453 	if (dloa->dl_primitive == DL_NOTIFY_IND)
15454 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
15455 	else
15456 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
15457 }
15458 
15459 /*
15460  * Handling of DLPI messages that require exclusive access to the ipsq.
15461  *
15462  * Need to do ill_pending_mp_release on ioctl completion, which could
15463  * happen here. (along with mi_copy_done)
15464  */
15465 /* ARGSUSED */
15466 static void
15467 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15468 {
15469 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15470 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15471 	int		err = 0;
15472 	ill_t		*ill;
15473 	ipif_t		*ipif = NULL;
15474 	mblk_t		*mp1 = NULL;
15475 	conn_t		*connp = NULL;
15476 	t_uscalar_t	paddrreq;
15477 	mblk_t		*mp_hw;
15478 	boolean_t	success;
15479 	boolean_t	ioctl_aborted = B_FALSE;
15480 	boolean_t	log = B_TRUE;
15481 	hook_nic_event_t	*info;
15482 	ip_stack_t		*ipst;
15483 
15484 	ip1dbg(("ip_rput_dlpi_writer .."));
15485 	ill = (ill_t *)q->q_ptr;
15486 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15487 
15488 	ASSERT(IAM_WRITER_ILL(ill));
15489 
15490 	ipst = ill->ill_ipst;
15491 
15492 	/*
15493 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
15494 	 * both are null or non-null. However we can assert that only
15495 	 * after grabbing the ipsq_lock. So we don't make any assertion
15496 	 * here and in other places in the code.
15497 	 */
15498 	ipif = ipsq->ipsq_pending_ipif;
15499 	/*
15500 	 * The current ioctl could have been aborted by the user and a new
15501 	 * ioctl to bring up another ill could have started. We could still
15502 	 * get a response from the driver later.
15503 	 */
15504 	if (ipif != NULL && ipif->ipif_ill != ill)
15505 		ioctl_aborted = B_TRUE;
15506 
15507 	switch (dloa->dl_primitive) {
15508 	case DL_ERROR_ACK:
15509 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
15510 		    dlpi_prim_str(dlea->dl_error_primitive)));
15511 
15512 		switch (dlea->dl_error_primitive) {
15513 		case DL_PROMISCON_REQ:
15514 		case DL_PROMISCOFF_REQ:
15515 		case DL_DISABMULTI_REQ:
15516 		case DL_UNBIND_REQ:
15517 		case DL_ATTACH_REQ:
15518 		case DL_INFO_REQ:
15519 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15520 			break;
15521 		case DL_NOTIFY_REQ:
15522 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15523 			log = B_FALSE;
15524 			break;
15525 		case DL_PHYS_ADDR_REQ:
15526 			/*
15527 			 * For IPv6 only, there are two additional
15528 			 * phys_addr_req's sent to the driver to get the
15529 			 * IPv6 token and lla. This allows IP to acquire
15530 			 * the hardware address format for a given interface
15531 			 * without having built in knowledge of the hardware
15532 			 * address. ill_phys_addr_pend keeps track of the last
15533 			 * DL_PAR sent so we know which response we are
15534 			 * dealing with. ill_dlpi_done will update
15535 			 * ill_phys_addr_pend when it sends the next req.
15536 			 * We don't complete the IOCTL until all three DL_PARs
15537 			 * have been attempted, so set *_len to 0 and break.
15538 			 */
15539 			paddrreq = ill->ill_phys_addr_pend;
15540 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15541 			if (paddrreq == DL_IPV6_TOKEN) {
15542 				ill->ill_token_length = 0;
15543 				log = B_FALSE;
15544 				break;
15545 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15546 				ill->ill_nd_lla_len = 0;
15547 				log = B_FALSE;
15548 				break;
15549 			}
15550 			/*
15551 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15552 			 * We presumably have an IOCTL hanging out waiting
15553 			 * for completion. Find it and complete the IOCTL
15554 			 * with the error noted.
15555 			 * However, ill_dl_phys was called on an ill queue
15556 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15557 			 * set. But the ioctl is known to be pending on ill_wq.
15558 			 */
15559 			if (!ill->ill_ifname_pending)
15560 				break;
15561 			ill->ill_ifname_pending = 0;
15562 			if (!ioctl_aborted)
15563 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15564 			if (mp1 != NULL) {
15565 				/*
15566 				 * This operation (SIOCSLIFNAME) must have
15567 				 * happened on the ill. Assert there is no conn
15568 				 */
15569 				ASSERT(connp == NULL);
15570 				q = ill->ill_wq;
15571 			}
15572 			break;
15573 		case DL_BIND_REQ:
15574 			ill_dlpi_done(ill, DL_BIND_REQ);
15575 			if (ill->ill_ifname_pending)
15576 				break;
15577 			/*
15578 			 * Something went wrong with the bind.  We presumably
15579 			 * have an IOCTL hanging out waiting for completion.
15580 			 * Find it, take down the interface that was coming
15581 			 * up, and complete the IOCTL with the error noted.
15582 			 */
15583 			if (!ioctl_aborted)
15584 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15585 			if (mp1 != NULL) {
15586 				/*
15587 				 * This operation (SIOCSLIFFLAGS) must have
15588 				 * happened from a conn.
15589 				 */
15590 				ASSERT(connp != NULL);
15591 				q = CONNP_TO_WQ(connp);
15592 				if (ill->ill_move_in_progress) {
15593 					ILL_CLEAR_MOVE(ill);
15594 				}
15595 				(void) ipif_down(ipif, NULL, NULL);
15596 				/* error is set below the switch */
15597 			}
15598 			break;
15599 		case DL_ENABMULTI_REQ:
15600 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
15601 
15602 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15603 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15604 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15605 				ipif_t *ipif;
15606 
15607 				printf("ip: joining multicasts failed (%d)"
15608 				    " on %s - will use link layer "
15609 				    "broadcasts for multicast\n",
15610 				    dlea->dl_errno, ill->ill_name);
15611 
15612 				/*
15613 				 * Set up the multicast mapping alone.
15614 				 * writer, so ok to access ill->ill_ipif
15615 				 * without any lock.
15616 				 */
15617 				ipif = ill->ill_ipif;
15618 				mutex_enter(&ill->ill_phyint->phyint_lock);
15619 				ill->ill_phyint->phyint_flags |=
15620 				    PHYI_MULTI_BCAST;
15621 				mutex_exit(&ill->ill_phyint->phyint_lock);
15622 
15623 				if (!ill->ill_isv6) {
15624 					(void) ipif_arp_setup_multicast(ipif,
15625 					    NULL);
15626 				} else {
15627 					(void) ipif_ndp_setup_multicast(ipif,
15628 					    NULL);
15629 				}
15630 			}
15631 			freemsg(mp);	/* Don't want to pass this up */
15632 			return;
15633 
15634 		case DL_CAPABILITY_REQ:
15635 		case DL_CONTROL_REQ:
15636 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15637 			ill->ill_dlpi_capab_state = IDS_FAILED;
15638 			freemsg(mp);
15639 			return;
15640 		}
15641 		/*
15642 		 * Note the error for IOCTL completion (mp1 is set when
15643 		 * ready to complete ioctl). If ill_ifname_pending_err is
15644 		 * set, an error occured during plumbing (ill_ifname_pending),
15645 		 * so we want to report that error.
15646 		 *
15647 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15648 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15649 		 * expected to get errack'd if the driver doesn't support
15650 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15651 		 * if these error conditions are encountered.
15652 		 */
15653 		if (mp1 != NULL) {
15654 			if (ill->ill_ifname_pending_err != 0)  {
15655 				err = ill->ill_ifname_pending_err;
15656 				ill->ill_ifname_pending_err = 0;
15657 			} else {
15658 				err = dlea->dl_unix_errno ?
15659 				    dlea->dl_unix_errno : ENXIO;
15660 			}
15661 		/*
15662 		 * If we're plumbing an interface and an error hasn't already
15663 		 * been saved, set ill_ifname_pending_err to the error passed
15664 		 * up. Ignore the error if log is B_FALSE (see comment above).
15665 		 */
15666 		} else if (log && ill->ill_ifname_pending &&
15667 		    ill->ill_ifname_pending_err == 0) {
15668 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15669 			    dlea->dl_unix_errno : ENXIO;
15670 		}
15671 
15672 		if (log)
15673 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15674 			    dlea->dl_errno, dlea->dl_unix_errno);
15675 		break;
15676 	case DL_CAPABILITY_ACK:
15677 		/* Call a routine to handle this one. */
15678 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
15679 		ill_capability_ack(ill, mp);
15680 
15681 		/*
15682 		 * If the ack is due to renegotiation, we will need to send
15683 		 * a new CAPABILITY_REQ to start the renegotiation.
15684 		 */
15685 		if (ill->ill_capab_reneg) {
15686 			ill->ill_capab_reneg = B_FALSE;
15687 			ill_capability_probe(ill);
15688 		}
15689 		break;
15690 	case DL_CONTROL_ACK:
15691 		/* We treat all of these as "fire and forget" */
15692 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15693 		break;
15694 	case DL_INFO_ACK:
15695 		/* Call a routine to handle this one. */
15696 		ill_dlpi_done(ill, DL_INFO_REQ);
15697 		ip_ll_subnet_defaults(ill, mp);
15698 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15699 		return;
15700 	case DL_BIND_ACK:
15701 		/*
15702 		 * We should have an IOCTL waiting on this unless
15703 		 * sent by ill_dl_phys, in which case just return
15704 		 */
15705 		ill_dlpi_done(ill, DL_BIND_REQ);
15706 		if (ill->ill_ifname_pending)
15707 			break;
15708 
15709 		if (!ioctl_aborted)
15710 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15711 		if (mp1 == NULL)
15712 			break;
15713 		/*
15714 		 * Because mp1 was added by ill_dl_up(), and it always
15715 		 * passes a valid connp, connp must be valid here.
15716 		 */
15717 		ASSERT(connp != NULL);
15718 		q = CONNP_TO_WQ(connp);
15719 
15720 		/*
15721 		 * We are exclusive. So nothing can change even after
15722 		 * we get the pending mp. If need be we can put it back
15723 		 * and restart, as in calling ipif_arp_up()  below.
15724 		 */
15725 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15726 
15727 		mutex_enter(&ill->ill_lock);
15728 
15729 		ill->ill_dl_up = 1;
15730 
15731 		if ((info = ill->ill_nic_event_info) != NULL) {
15732 			ip2dbg(("ip_rput_dlpi_writer: unexpected nic event %d "
15733 			    "attached for %s\n", info->hne_event,
15734 			    ill->ill_name));
15735 			if (info->hne_data != NULL)
15736 				kmem_free(info->hne_data, info->hne_datalen);
15737 			kmem_free(info, sizeof (hook_nic_event_t));
15738 		}
15739 
15740 		info = kmem_alloc(sizeof (hook_nic_event_t), KM_NOSLEEP);
15741 		if (info != NULL) {
15742 			info->hne_nic = ill->ill_phyint->phyint_hook_ifindex;
15743 			info->hne_lif = 0;
15744 			info->hne_event = NE_UP;
15745 			info->hne_data = NULL;
15746 			info->hne_datalen = 0;
15747 			info->hne_family = ill->ill_isv6 ?
15748 			    ipst->ips_ipv6_net_data : ipst->ips_ipv4_net_data;
15749 		} else
15750 			ip2dbg(("ip_rput_dlpi_writer: could not attach UP nic "
15751 			    "event information for %s (ENOMEM)\n",
15752 			    ill->ill_name));
15753 
15754 		ill->ill_nic_event_info = info;
15755 
15756 		mutex_exit(&ill->ill_lock);
15757 
15758 		/*
15759 		 * Now bring up the resolver; when that is complete, we'll
15760 		 * create IREs.  Note that we intentionally mirror what
15761 		 * ipif_up() would have done, because we got here by way of
15762 		 * ill_dl_up(), which stopped ipif_up()'s processing.
15763 		 */
15764 		if (ill->ill_isv6) {
15765 			/*
15766 			 * v6 interfaces.
15767 			 * Unlike ARP which has to do another bind
15768 			 * and attach, once we get here we are
15769 			 * done with NDP. Except in the case of
15770 			 * ILLF_XRESOLV, in which case we send an
15771 			 * AR_INTERFACE_UP to the external resolver.
15772 			 * If all goes well, the ioctl will complete
15773 			 * in ip_rput(). If there's an error, we
15774 			 * complete it here.
15775 			 */
15776 			if ((err = ipif_ndp_up(ipif)) == 0) {
15777 				if (ill->ill_flags & ILLF_XRESOLV) {
15778 					mutex_enter(&connp->conn_lock);
15779 					mutex_enter(&ill->ill_lock);
15780 					success = ipsq_pending_mp_add(
15781 					    connp, ipif, q, mp1, 0);
15782 					mutex_exit(&ill->ill_lock);
15783 					mutex_exit(&connp->conn_lock);
15784 					if (success) {
15785 						err = ipif_resolver_up(ipif,
15786 						    Res_act_initial);
15787 						if (err == EINPROGRESS) {
15788 							freemsg(mp);
15789 							return;
15790 						}
15791 						ASSERT(err != 0);
15792 						mp1 = ipsq_pending_mp_get(ipsq,
15793 						    &connp);
15794 						ASSERT(mp1 != NULL);
15795 					} else {
15796 						/* conn has started closing */
15797 						err = EINTR;
15798 					}
15799 				} else { /* Non XRESOLV interface */
15800 					(void) ipif_resolver_up(ipif,
15801 					    Res_act_initial);
15802 					err = ipif_up_done_v6(ipif);
15803 				}
15804 			}
15805 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
15806 			/*
15807 			 * ARP and other v4 external resolvers.
15808 			 * Leave the pending mblk intact so that
15809 			 * the ioctl completes in ip_rput().
15810 			 */
15811 			mutex_enter(&connp->conn_lock);
15812 			mutex_enter(&ill->ill_lock);
15813 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
15814 			mutex_exit(&ill->ill_lock);
15815 			mutex_exit(&connp->conn_lock);
15816 			if (success) {
15817 				err = ipif_resolver_up(ipif, Res_act_initial);
15818 				if (err == EINPROGRESS) {
15819 					freemsg(mp);
15820 					return;
15821 				}
15822 				ASSERT(err != 0);
15823 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15824 			} else {
15825 				/* The conn has started closing */
15826 				err = EINTR;
15827 			}
15828 		} else {
15829 			/*
15830 			 * This one is complete. Reply to pending ioctl.
15831 			 */
15832 			(void) ipif_resolver_up(ipif, Res_act_initial);
15833 			err = ipif_up_done(ipif);
15834 		}
15835 
15836 		if ((err == 0) && (ill->ill_up_ipifs)) {
15837 			err = ill_up_ipifs(ill, q, mp1);
15838 			if (err == EINPROGRESS) {
15839 				freemsg(mp);
15840 				return;
15841 			}
15842 		}
15843 
15844 		if (ill->ill_up_ipifs) {
15845 			ill_group_cleanup(ill);
15846 		}
15847 
15848 		break;
15849 	case DL_NOTIFY_IND: {
15850 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
15851 		ire_t *ire;
15852 		boolean_t need_ire_walk_v4 = B_FALSE;
15853 		boolean_t need_ire_walk_v6 = B_FALSE;
15854 
15855 		switch (notify->dl_notification) {
15856 		case DL_NOTE_PHYS_ADDR:
15857 			err = ill_set_phys_addr(ill, mp);
15858 			break;
15859 
15860 		case DL_NOTE_FASTPATH_FLUSH:
15861 			ill_fastpath_flush(ill);
15862 			break;
15863 
15864 		case DL_NOTE_SDU_SIZE:
15865 			/*
15866 			 * Change the MTU size of the interface, of all
15867 			 * attached ipif's, and of all relevant ire's.  The
15868 			 * new value's a uint32_t at notify->dl_data.
15869 			 * Mtu change Vs. new ire creation - protocol below.
15870 			 *
15871 			 * a Mark the ipif as IPIF_CHANGING.
15872 			 * b Set the new mtu in the ipif.
15873 			 * c Change the ire_max_frag on all affected ires
15874 			 * d Unmark the IPIF_CHANGING
15875 			 *
15876 			 * To see how the protocol works, assume an interface
15877 			 * route is also being added simultaneously by
15878 			 * ip_rt_add and let 'ipif' be the ipif referenced by
15879 			 * the ire. If the ire is created before step a,
15880 			 * it will be cleaned up by step c. If the ire is
15881 			 * created after step d, it will see the new value of
15882 			 * ipif_mtu. Any attempt to create the ire between
15883 			 * steps a to d will fail because of the IPIF_CHANGING
15884 			 * flag. Note that ire_create() is passed a pointer to
15885 			 * the ipif_mtu, and not the value. During ire_add
15886 			 * under the bucket lock, the ire_max_frag of the
15887 			 * new ire being created is set from the ipif/ire from
15888 			 * which it is being derived.
15889 			 */
15890 			mutex_enter(&ill->ill_lock);
15891 			ill->ill_max_frag = (uint_t)notify->dl_data;
15892 
15893 			/*
15894 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
15895 			 * leave it alone
15896 			 */
15897 			if (ill->ill_mtu_userspecified) {
15898 				mutex_exit(&ill->ill_lock);
15899 				break;
15900 			}
15901 			ill->ill_max_mtu = ill->ill_max_frag;
15902 			if (ill->ill_isv6) {
15903 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
15904 					ill->ill_max_mtu = IPV6_MIN_MTU;
15905 			} else {
15906 				if (ill->ill_max_mtu < IP_MIN_MTU)
15907 					ill->ill_max_mtu = IP_MIN_MTU;
15908 			}
15909 			for (ipif = ill->ill_ipif; ipif != NULL;
15910 			    ipif = ipif->ipif_next) {
15911 				/*
15912 				 * Don't override the mtu if the user
15913 				 * has explicitly set it.
15914 				 */
15915 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
15916 					continue;
15917 				ipif->ipif_mtu = (uint_t)notify->dl_data;
15918 				if (ipif->ipif_isv6)
15919 					ire = ipif_to_ire_v6(ipif);
15920 				else
15921 					ire = ipif_to_ire(ipif);
15922 				if (ire != NULL) {
15923 					ire->ire_max_frag = ipif->ipif_mtu;
15924 					ire_refrele(ire);
15925 				}
15926 				if (ipif->ipif_flags & IPIF_UP) {
15927 					if (ill->ill_isv6)
15928 						need_ire_walk_v6 = B_TRUE;
15929 					else
15930 						need_ire_walk_v4 = B_TRUE;
15931 				}
15932 			}
15933 			mutex_exit(&ill->ill_lock);
15934 			if (need_ire_walk_v4)
15935 				ire_walk_v4(ill_mtu_change, (char *)ill,
15936 				    ALL_ZONES, ipst);
15937 			if (need_ire_walk_v6)
15938 				ire_walk_v6(ill_mtu_change, (char *)ill,
15939 				    ALL_ZONES, ipst);
15940 			break;
15941 		case DL_NOTE_LINK_UP:
15942 		case DL_NOTE_LINK_DOWN: {
15943 			/*
15944 			 * We are writer. ill / phyint / ipsq assocs stable.
15945 			 * The RUNNING flag reflects the state of the link.
15946 			 */
15947 			phyint_t *phyint = ill->ill_phyint;
15948 			uint64_t new_phyint_flags;
15949 			boolean_t changed = B_FALSE;
15950 			boolean_t went_up;
15951 
15952 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
15953 			mutex_enter(&phyint->phyint_lock);
15954 			new_phyint_flags = went_up ?
15955 			    phyint->phyint_flags | PHYI_RUNNING :
15956 			    phyint->phyint_flags & ~PHYI_RUNNING;
15957 			if (new_phyint_flags != phyint->phyint_flags) {
15958 				phyint->phyint_flags = new_phyint_flags;
15959 				changed = B_TRUE;
15960 			}
15961 			mutex_exit(&phyint->phyint_lock);
15962 			/*
15963 			 * ill_restart_dad handles the DAD restart and routing
15964 			 * socket notification logic.
15965 			 */
15966 			if (changed) {
15967 				ill_restart_dad(phyint->phyint_illv4, went_up);
15968 				ill_restart_dad(phyint->phyint_illv6, went_up);
15969 			}
15970 			break;
15971 		}
15972 		case DL_NOTE_PROMISC_ON_PHYS:
15973 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15974 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
15975 			mutex_enter(&ill->ill_lock);
15976 			ill->ill_promisc_on_phys = B_TRUE;
15977 			mutex_exit(&ill->ill_lock);
15978 			break;
15979 		case DL_NOTE_PROMISC_OFF_PHYS:
15980 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15981 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
15982 			mutex_enter(&ill->ill_lock);
15983 			ill->ill_promisc_on_phys = B_FALSE;
15984 			mutex_exit(&ill->ill_lock);
15985 			break;
15986 		case DL_NOTE_CAPAB_RENEG:
15987 			/*
15988 			 * Something changed on the driver side.
15989 			 * It wants us to renegotiate the capabilities
15990 			 * on this ill. One possible cause is the aggregation
15991 			 * interface under us where a port got added or
15992 			 * went away.
15993 			 *
15994 			 * If the capability negotiation is already done
15995 			 * or is in progress, reset the capabilities and
15996 			 * mark the ill's ill_capab_reneg to be B_TRUE,
15997 			 * so that when the ack comes back, we can start
15998 			 * the renegotiation process.
15999 			 *
16000 			 * Note that if ill_capab_reneg is already B_TRUE
16001 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
16002 			 * the capability resetting request has been sent
16003 			 * and the renegotiation has not been started yet;
16004 			 * nothing needs to be done in this case.
16005 			 */
16006 			if (ill->ill_dlpi_capab_state != IDS_UNKNOWN) {
16007 				ill_capability_reset(ill);
16008 				ill->ill_capab_reneg = B_TRUE;
16009 			}
16010 			break;
16011 		default:
16012 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
16013 			    "type 0x%x for DL_NOTIFY_IND\n",
16014 			    notify->dl_notification));
16015 			break;
16016 		}
16017 
16018 		/*
16019 		 * As this is an asynchronous operation, we
16020 		 * should not call ill_dlpi_done
16021 		 */
16022 		break;
16023 	}
16024 	case DL_NOTIFY_ACK: {
16025 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
16026 
16027 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
16028 			ill->ill_note_link = 1;
16029 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
16030 		break;
16031 	}
16032 	case DL_PHYS_ADDR_ACK: {
16033 		/*
16034 		 * As part of plumbing the interface via SIOCSLIFNAME,
16035 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
16036 		 * whose answers we receive here.  As each answer is received,
16037 		 * we call ill_dlpi_done() to dispatch the next request as
16038 		 * we're processing the current one.  Once all answers have
16039 		 * been received, we use ipsq_pending_mp_get() to dequeue the
16040 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
16041 		 * is invoked from an ill queue, conn_oper_pending_ill is not
16042 		 * available, but we know the ioctl is pending on ill_wq.)
16043 		 */
16044 		uint_t paddrlen, paddroff;
16045 
16046 		paddrreq = ill->ill_phys_addr_pend;
16047 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
16048 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
16049 
16050 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
16051 		if (paddrreq == DL_IPV6_TOKEN) {
16052 			/*
16053 			 * bcopy to low-order bits of ill_token
16054 			 *
16055 			 * XXX Temporary hack - currently, all known tokens
16056 			 * are 64 bits, so I'll cheat for the moment.
16057 			 */
16058 			bcopy(mp->b_rptr + paddroff,
16059 			    &ill->ill_token.s6_addr32[2], paddrlen);
16060 			ill->ill_token_length = paddrlen;
16061 			break;
16062 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16063 			ASSERT(ill->ill_nd_lla_mp == NULL);
16064 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
16065 			mp = NULL;
16066 			break;
16067 		}
16068 
16069 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
16070 		ASSERT(ill->ill_phys_addr_mp == NULL);
16071 		if (!ill->ill_ifname_pending)
16072 			break;
16073 		ill->ill_ifname_pending = 0;
16074 		if (!ioctl_aborted)
16075 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16076 		if (mp1 != NULL) {
16077 			ASSERT(connp == NULL);
16078 			q = ill->ill_wq;
16079 		}
16080 		/*
16081 		 * If any error acks received during the plumbing sequence,
16082 		 * ill_ifname_pending_err will be set. Break out and send up
16083 		 * the error to the pending ioctl.
16084 		 */
16085 		if (ill->ill_ifname_pending_err != 0) {
16086 			err = ill->ill_ifname_pending_err;
16087 			ill->ill_ifname_pending_err = 0;
16088 			break;
16089 		}
16090 
16091 		ill->ill_phys_addr_mp = mp;
16092 		ill->ill_phys_addr = mp->b_rptr + paddroff;
16093 		mp = NULL;
16094 
16095 		/*
16096 		 * If paddrlen is zero, the DLPI provider doesn't support
16097 		 * physical addresses.  The other two tests were historical
16098 		 * workarounds for bugs in our former PPP implementation, but
16099 		 * now other things have grown dependencies on them -- e.g.,
16100 		 * the tun module specifies a dl_addr_length of zero in its
16101 		 * DL_BIND_ACK, but then specifies an incorrect value in its
16102 		 * DL_PHYS_ADDR_ACK.  These bogus checks need to be removed,
16103 		 * but only after careful testing ensures that all dependent
16104 		 * broken DLPI providers have been fixed.
16105 		 */
16106 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0 ||
16107 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
16108 			ill->ill_phys_addr = NULL;
16109 		} else if (paddrlen != ill->ill_phys_addr_length) {
16110 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16111 			    paddrlen, ill->ill_phys_addr_length));
16112 			err = EINVAL;
16113 			break;
16114 		}
16115 
16116 		if (ill->ill_nd_lla_mp == NULL) {
16117 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16118 				err = ENOMEM;
16119 				break;
16120 			}
16121 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16122 		}
16123 
16124 		/*
16125 		 * Set the interface token.  If the zeroth interface address
16126 		 * is unspecified, then set it to the link local address.
16127 		 */
16128 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
16129 			(void) ill_setdefaulttoken(ill);
16130 
16131 		ASSERT(ill->ill_ipif->ipif_id == 0);
16132 		if (ipif != NULL &&
16133 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr)) {
16134 			(void) ipif_setlinklocal(ipif);
16135 		}
16136 		break;
16137 	}
16138 	case DL_OK_ACK:
16139 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16140 		    dlpi_prim_str((int)dloa->dl_correct_primitive),
16141 		    dloa->dl_correct_primitive));
16142 		switch (dloa->dl_correct_primitive) {
16143 		case DL_PROMISCON_REQ:
16144 		case DL_PROMISCOFF_REQ:
16145 		case DL_ENABMULTI_REQ:
16146 		case DL_DISABMULTI_REQ:
16147 		case DL_UNBIND_REQ:
16148 		case DL_ATTACH_REQ:
16149 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16150 			break;
16151 		}
16152 		break;
16153 	default:
16154 		break;
16155 	}
16156 
16157 	freemsg(mp);
16158 	if (mp1 != NULL) {
16159 		/*
16160 		 * The operation must complete without EINPROGRESS
16161 		 * since ipsq_pending_mp_get() has removed the mblk
16162 		 * from ipsq_pending_mp.  Otherwise, the operation
16163 		 * will be stuck forever in the ipsq.
16164 		 */
16165 		ASSERT(err != EINPROGRESS);
16166 
16167 		switch (ipsq->ipsq_current_ioctl) {
16168 		case 0:
16169 			ipsq_current_finish(ipsq);
16170 			break;
16171 
16172 		case SIOCLIFADDIF:
16173 		case SIOCSLIFNAME:
16174 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16175 			break;
16176 
16177 		default:
16178 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16179 			break;
16180 		}
16181 	}
16182 }
16183 
16184 /*
16185  * ip_rput_other is called by ip_rput to handle messages modifying the global
16186  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16187  */
16188 /* ARGSUSED */
16189 void
16190 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16191 {
16192 	ill_t		*ill;
16193 	struct iocblk	*iocp;
16194 	mblk_t		*mp1;
16195 	conn_t		*connp = NULL;
16196 
16197 	ip1dbg(("ip_rput_other "));
16198 	ill = (ill_t *)q->q_ptr;
16199 	/*
16200 	 * This routine is not a writer in the case of SIOCGTUNPARAM
16201 	 * in which case ipsq is NULL.
16202 	 */
16203 	if (ipsq != NULL) {
16204 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16205 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
16206 	}
16207 
16208 	switch (mp->b_datap->db_type) {
16209 	case M_ERROR:
16210 	case M_HANGUP:
16211 		/*
16212 		 * The device has a problem.  We force the ILL down.  It can
16213 		 * be brought up again manually using SIOCSIFFLAGS (via
16214 		 * ifconfig or equivalent).
16215 		 */
16216 		ASSERT(ipsq != NULL);
16217 		if (mp->b_rptr < mp->b_wptr)
16218 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16219 		if (ill->ill_error == 0)
16220 			ill->ill_error = ENXIO;
16221 		if (!ill_down_start(q, mp))
16222 			return;
16223 		ipif_all_down_tail(ipsq, q, mp, NULL);
16224 		break;
16225 	case M_IOCACK:
16226 		iocp = (struct iocblk *)mp->b_rptr;
16227 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16228 		switch (iocp->ioc_cmd) {
16229 		case SIOCSTUNPARAM:
16230 		case OSIOCSTUNPARAM:
16231 			ASSERT(ipsq != NULL);
16232 			/*
16233 			 * Finish socket ioctl passed through to tun.
16234 			 * We should have an IOCTL waiting on this.
16235 			 */
16236 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16237 			if (ill->ill_isv6) {
16238 				struct iftun_req *ta;
16239 
16240 				/*
16241 				 * if a source or destination is
16242 				 * being set, try and set the link
16243 				 * local address for the tunnel
16244 				 */
16245 				ta = (struct iftun_req *)mp->b_cont->
16246 				    b_cont->b_rptr;
16247 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16248 					ipif_set_tun_llink(ill, ta);
16249 				}
16250 
16251 			}
16252 			if (mp1 != NULL) {
16253 				/*
16254 				 * Now copy back the b_next/b_prev used by
16255 				 * mi code for the mi_copy* functions.
16256 				 * See ip_sioctl_tunparam() for the reason.
16257 				 * Also protect against missing b_cont.
16258 				 */
16259 				if (mp->b_cont != NULL) {
16260 					mp->b_cont->b_next =
16261 					    mp1->b_cont->b_next;
16262 					mp->b_cont->b_prev =
16263 					    mp1->b_cont->b_prev;
16264 				}
16265 				inet_freemsg(mp1);
16266 				ASSERT(connp != NULL);
16267 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16268 				    iocp->ioc_error, NO_COPYOUT, ipsq);
16269 			} else {
16270 				ASSERT(connp == NULL);
16271 				putnext(q, mp);
16272 			}
16273 			break;
16274 		case SIOCGTUNPARAM:
16275 		case OSIOCGTUNPARAM:
16276 			/*
16277 			 * This is really M_IOCDATA from the tunnel driver.
16278 			 * convert back and complete the ioctl.
16279 			 * We should have an IOCTL waiting on this.
16280 			 */
16281 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16282 			if (mp1) {
16283 				/*
16284 				 * Now copy back the b_next/b_prev used by
16285 				 * mi code for the mi_copy* functions.
16286 				 * See ip_sioctl_tunparam() for the reason.
16287 				 * Also protect against missing b_cont.
16288 				 */
16289 				if (mp->b_cont != NULL) {
16290 					mp->b_cont->b_next =
16291 					    mp1->b_cont->b_next;
16292 					mp->b_cont->b_prev =
16293 					    mp1->b_cont->b_prev;
16294 				}
16295 				inet_freemsg(mp1);
16296 				if (iocp->ioc_error == 0)
16297 					mp->b_datap->db_type = M_IOCDATA;
16298 				ASSERT(connp != NULL);
16299 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16300 				    iocp->ioc_error, COPYOUT, NULL);
16301 			} else {
16302 				ASSERT(connp == NULL);
16303 				putnext(q, mp);
16304 			}
16305 			break;
16306 		default:
16307 			break;
16308 		}
16309 		break;
16310 	case M_IOCNAK:
16311 		iocp = (struct iocblk *)mp->b_rptr;
16312 
16313 		switch (iocp->ioc_cmd) {
16314 		int mode;
16315 
16316 		case DL_IOC_HDR_INFO:
16317 			/*
16318 			 * If this was the first attempt turn of the
16319 			 * fastpath probing.
16320 			 */
16321 			mutex_enter(&ill->ill_lock);
16322 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16323 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16324 				mutex_exit(&ill->ill_lock);
16325 				ill_fastpath_nack(ill);
16326 				ip1dbg(("ip_rput: DLPI fastpath off on "
16327 				    "interface %s\n",
16328 				    ill->ill_name));
16329 			} else {
16330 				mutex_exit(&ill->ill_lock);
16331 			}
16332 			freemsg(mp);
16333 			break;
16334 		case SIOCSTUNPARAM:
16335 		case OSIOCSTUNPARAM:
16336 			ASSERT(ipsq != NULL);
16337 			/*
16338 			 * Finish socket ioctl passed through to tun
16339 			 * We should have an IOCTL waiting on this.
16340 			 */
16341 			/* FALLTHRU */
16342 		case SIOCGTUNPARAM:
16343 		case OSIOCGTUNPARAM:
16344 			/*
16345 			 * This is really M_IOCDATA from the tunnel driver.
16346 			 * convert back and complete the ioctl.
16347 			 * We should have an IOCTL waiting on this.
16348 			 */
16349 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16350 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16351 				mp1 = ill_pending_mp_get(ill, &connp,
16352 				    iocp->ioc_id);
16353 				mode = COPYOUT;
16354 				ipsq = NULL;
16355 			} else {
16356 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16357 				mode = NO_COPYOUT;
16358 			}
16359 			if (mp1 != NULL) {
16360 				/*
16361 				 * Now copy back the b_next/b_prev used by
16362 				 * mi code for the mi_copy* functions.
16363 				 * See ip_sioctl_tunparam() for the reason.
16364 				 * Also protect against missing b_cont.
16365 				 */
16366 				if (mp->b_cont != NULL) {
16367 					mp->b_cont->b_next =
16368 					    mp1->b_cont->b_next;
16369 					mp->b_cont->b_prev =
16370 					    mp1->b_cont->b_prev;
16371 				}
16372 				inet_freemsg(mp1);
16373 				if (iocp->ioc_error == 0)
16374 					iocp->ioc_error = EINVAL;
16375 				ASSERT(connp != NULL);
16376 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16377 				    iocp->ioc_error, mode, ipsq);
16378 			} else {
16379 				ASSERT(connp == NULL);
16380 				putnext(q, mp);
16381 			}
16382 			break;
16383 		default:
16384 			break;
16385 		}
16386 	default:
16387 		break;
16388 	}
16389 }
16390 
16391 /*
16392  * NOTE : This function does not ire_refrele the ire argument passed in.
16393  *
16394  * IPQoS notes
16395  * IP policy is invoked twice for a forwarded packet, once on the read side
16396  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16397  * enabled. An additional parameter, in_ill, has been added for this purpose.
16398  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16399  * because ip_mroute drops this information.
16400  *
16401  */
16402 void
16403 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16404 {
16405 	uint32_t	old_pkt_len;
16406 	uint32_t	pkt_len;
16407 	queue_t	*q;
16408 	uint32_t	sum;
16409 #define	rptr	((uchar_t *)ipha)
16410 	uint32_t	max_frag;
16411 	uint32_t	ill_index;
16412 	ill_t		*out_ill;
16413 	mib2_ipIfStatsEntry_t *mibptr;
16414 	ip_stack_t	*ipst = ((ill_t *)(ire->ire_stq->q_ptr))->ill_ipst;
16415 
16416 	/* Get the ill_index of the incoming ILL */
16417 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16418 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16419 
16420 	/* Initiate Read side IPPF processing */
16421 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16422 		ip_process(IPP_FWD_IN, &mp, ill_index);
16423 		if (mp == NULL) {
16424 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16425 			    "during IPPF processing\n"));
16426 			return;
16427 		}
16428 	}
16429 
16430 	/* Adjust the checksum to reflect the ttl decrement. */
16431 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16432 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16433 
16434 	if (ipha->ipha_ttl-- <= 1) {
16435 		if (ip_csum_hdr(ipha)) {
16436 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16437 			goto drop_pkt;
16438 		}
16439 		/*
16440 		 * Note: ire_stq this will be NULL for multicast
16441 		 * datagrams using the long path through arp (the IRE
16442 		 * is not an IRE_CACHE). This should not cause
16443 		 * problems since we don't generate ICMP errors for
16444 		 * multicast packets.
16445 		 */
16446 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16447 		q = ire->ire_stq;
16448 		if (q != NULL) {
16449 			/* Sent by forwarding path, and router is global zone */
16450 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16451 			    GLOBAL_ZONEID, ipst);
16452 		} else
16453 			freemsg(mp);
16454 		return;
16455 	}
16456 
16457 	/*
16458 	 * Don't forward if the interface is down
16459 	 */
16460 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16461 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16462 		ip2dbg(("ip_rput_forward:interface is down\n"));
16463 		goto drop_pkt;
16464 	}
16465 
16466 	/* Get the ill_index of the outgoing ILL */
16467 	out_ill = ire_to_ill(ire);
16468 	ill_index = out_ill->ill_phyint->phyint_ifindex;
16469 
16470 	DTRACE_PROBE4(ip4__forwarding__start,
16471 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16472 
16473 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16474 	    ipst->ips_ipv4firewall_forwarding,
16475 	    in_ill, out_ill, ipha, mp, mp, ipst);
16476 
16477 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16478 
16479 	if (mp == NULL)
16480 		return;
16481 	old_pkt_len = pkt_len = ntohs(ipha->ipha_length);
16482 
16483 	if (is_system_labeled()) {
16484 		mblk_t *mp1;
16485 
16486 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16487 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16488 			goto drop_pkt;
16489 		}
16490 		/* Size may have changed */
16491 		mp = mp1;
16492 		ipha = (ipha_t *)mp->b_rptr;
16493 		pkt_len = ntohs(ipha->ipha_length);
16494 	}
16495 
16496 	/* Check if there are options to update */
16497 	if (!IS_SIMPLE_IPH(ipha)) {
16498 		if (ip_csum_hdr(ipha)) {
16499 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16500 			goto drop_pkt;
16501 		}
16502 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16503 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16504 			return;
16505 		}
16506 
16507 		ipha->ipha_hdr_checksum = 0;
16508 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16509 	}
16510 	max_frag = ire->ire_max_frag;
16511 	if (pkt_len > max_frag) {
16512 		/*
16513 		 * It needs fragging on its way out.  We haven't
16514 		 * verified the header checksum yet.  Since we
16515 		 * are going to put a surely good checksum in the
16516 		 * outgoing header, we have to make sure that it
16517 		 * was good coming in.
16518 		 */
16519 		if (ip_csum_hdr(ipha)) {
16520 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16521 			goto drop_pkt;
16522 		}
16523 		/* Initiate Write side IPPF processing */
16524 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16525 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16526 			if (mp == NULL) {
16527 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16528 				    " during IPPF processing\n"));
16529 				return;
16530 			}
16531 		}
16532 		/*
16533 		 * Handle labeled packet resizing.
16534 		 *
16535 		 * If we have added a label, inform ip_wput_frag() of its
16536 		 * effect on the MTU for ICMP messages.
16537 		 */
16538 		if (pkt_len > old_pkt_len) {
16539 			uint32_t secopt_size;
16540 
16541 			secopt_size = pkt_len - old_pkt_len;
16542 			if (secopt_size < max_frag)
16543 				max_frag -= secopt_size;
16544 		}
16545 
16546 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID, ipst);
16547 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16548 		return;
16549 	}
16550 
16551 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16552 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16553 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16554 	    ipst->ips_ipv4firewall_physical_out,
16555 	    NULL, out_ill, ipha, mp, mp, ipst);
16556 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16557 	if (mp == NULL)
16558 		return;
16559 
16560 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16561 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16562 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE);
16563 	/* ip_xmit_v4 always consumes the packet */
16564 	return;
16565 
16566 drop_pkt:;
16567 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16568 	freemsg(mp);
16569 #undef	rptr
16570 }
16571 
16572 void
16573 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16574 {
16575 	ire_t	*ire;
16576 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
16577 
16578 	ASSERT(!ipif->ipif_isv6);
16579 	/*
16580 	 * Find an IRE which matches the destination and the outgoing
16581 	 * queue in the cache table. All we need is an IRE_CACHE which
16582 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
16583 	 * then it is enough to have some IRE_CACHE in the group.
16584 	 */
16585 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16586 		dst = ipif->ipif_pp_dst_addr;
16587 
16588 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
16589 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR, ipst);
16590 	if (ire == NULL) {
16591 		/*
16592 		 * Mark this packet to make it be delivered to
16593 		 * ip_rput_forward after the new ire has been
16594 		 * created.
16595 		 */
16596 		mp->b_prev = NULL;
16597 		mp->b_next = mp;
16598 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16599 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
16600 	} else {
16601 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16602 		IRE_REFRELE(ire);
16603 	}
16604 }
16605 
16606 /* Update any source route, record route or timestamp options */
16607 static int
16608 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
16609 {
16610 	ipoptp_t	opts;
16611 	uchar_t		*opt;
16612 	uint8_t		optval;
16613 	uint8_t		optlen;
16614 	ipaddr_t	dst;
16615 	uint32_t	ts;
16616 	ire_t		*dst_ire = NULL;
16617 	ire_t		*tmp_ire = NULL;
16618 	timestruc_t	now;
16619 
16620 	ip2dbg(("ip_rput_forward_options\n"));
16621 	dst = ipha->ipha_dst;
16622 	for (optval = ipoptp_first(&opts, ipha);
16623 	    optval != IPOPT_EOL;
16624 	    optval = ipoptp_next(&opts)) {
16625 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16626 		opt = opts.ipoptp_cur;
16627 		optlen = opts.ipoptp_len;
16628 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16629 		    optval, opts.ipoptp_len));
16630 		switch (optval) {
16631 			uint32_t off;
16632 		case IPOPT_SSRR:
16633 		case IPOPT_LSRR:
16634 			/* Check if adminstratively disabled */
16635 			if (!ipst->ips_ip_forward_src_routed) {
16636 				if (ire->ire_stq != NULL) {
16637 					/*
16638 					 * Sent by forwarding path, and router
16639 					 * is global zone
16640 					 */
16641 					icmp_unreachable(ire->ire_stq, mp,
16642 					    ICMP_SOURCE_ROUTE_FAILED,
16643 					    GLOBAL_ZONEID, ipst);
16644 				} else {
16645 					ip0dbg(("ip_rput_forward_options: "
16646 					    "unable to send unreach\n"));
16647 					freemsg(mp);
16648 				}
16649 				return (-1);
16650 			}
16651 
16652 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16653 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16654 			if (dst_ire == NULL) {
16655 				/*
16656 				 * Must be partial since ip_rput_options
16657 				 * checked for strict.
16658 				 */
16659 				break;
16660 			}
16661 			off = opt[IPOPT_OFFSET];
16662 			off--;
16663 		redo_srr:
16664 			if (optlen < IP_ADDR_LEN ||
16665 			    off > optlen - IP_ADDR_LEN) {
16666 				/* End of source route */
16667 				ip1dbg((
16668 				    "ip_rput_forward_options: end of SR\n"));
16669 				ire_refrele(dst_ire);
16670 				break;
16671 			}
16672 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16673 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16674 			    IP_ADDR_LEN);
16675 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16676 			    ntohl(dst)));
16677 
16678 			/*
16679 			 * Check if our address is present more than
16680 			 * once as consecutive hops in source route.
16681 			 */
16682 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16683 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16684 			if (tmp_ire != NULL) {
16685 				ire_refrele(tmp_ire);
16686 				off += IP_ADDR_LEN;
16687 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16688 				goto redo_srr;
16689 			}
16690 			ipha->ipha_dst = dst;
16691 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16692 			ire_refrele(dst_ire);
16693 			break;
16694 		case IPOPT_RR:
16695 			off = opt[IPOPT_OFFSET];
16696 			off--;
16697 			if (optlen < IP_ADDR_LEN ||
16698 			    off > optlen - IP_ADDR_LEN) {
16699 				/* No more room - ignore */
16700 				ip1dbg((
16701 				    "ip_rput_forward_options: end of RR\n"));
16702 				break;
16703 			}
16704 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16705 			    IP_ADDR_LEN);
16706 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16707 			break;
16708 		case IPOPT_TS:
16709 			/* Insert timestamp if there is room */
16710 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16711 			case IPOPT_TS_TSONLY:
16712 				off = IPOPT_TS_TIMELEN;
16713 				break;
16714 			case IPOPT_TS_PRESPEC:
16715 			case IPOPT_TS_PRESPEC_RFC791:
16716 				/* Verify that the address matched */
16717 				off = opt[IPOPT_OFFSET] - 1;
16718 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16719 				dst_ire = ire_ctable_lookup(dst, 0,
16720 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16721 				    MATCH_IRE_TYPE, ipst);
16722 				if (dst_ire == NULL) {
16723 					/* Not for us */
16724 					break;
16725 				}
16726 				ire_refrele(dst_ire);
16727 				/* FALLTHRU */
16728 			case IPOPT_TS_TSANDADDR:
16729 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16730 				break;
16731 			default:
16732 				/*
16733 				 * ip_*put_options should have already
16734 				 * dropped this packet.
16735 				 */
16736 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16737 				    "unknown IT - bug in ip_rput_options?\n");
16738 				return (0);	/* Keep "lint" happy */
16739 			}
16740 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16741 				/* Increase overflow counter */
16742 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16743 				opt[IPOPT_POS_OV_FLG] =
16744 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16745 				    (off << 4));
16746 				break;
16747 			}
16748 			off = opt[IPOPT_OFFSET] - 1;
16749 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16750 			case IPOPT_TS_PRESPEC:
16751 			case IPOPT_TS_PRESPEC_RFC791:
16752 			case IPOPT_TS_TSANDADDR:
16753 				bcopy(&ire->ire_src_addr,
16754 				    (char *)opt + off, IP_ADDR_LEN);
16755 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16756 				/* FALLTHRU */
16757 			case IPOPT_TS_TSONLY:
16758 				off = opt[IPOPT_OFFSET] - 1;
16759 				/* Compute # of milliseconds since midnight */
16760 				gethrestime(&now);
16761 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16762 				    now.tv_nsec / (NANOSEC / MILLISEC);
16763 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16764 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16765 				break;
16766 			}
16767 			break;
16768 		}
16769 	}
16770 	return (0);
16771 }
16772 
16773 /*
16774  * This is called after processing at least one of AH/ESP headers.
16775  *
16776  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16777  * the actual, physical interface on which the packet was received,
16778  * but, when ip_strict_dst_multihoming is set to 1, could be the
16779  * interface which had the ipha_dst configured when the packet went
16780  * through ip_rput. The ill_index corresponding to the recv_ill
16781  * is saved in ipsec_in_rill_index
16782  *
16783  * NOTE2: The "ire" argument is only used in IPv4 cases.  This function
16784  * cannot assume "ire" points to valid data for any IPv6 cases.
16785  */
16786 void
16787 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
16788 {
16789 	mblk_t *mp;
16790 	ipaddr_t dst;
16791 	in6_addr_t *v6dstp;
16792 	ipha_t *ipha;
16793 	ip6_t *ip6h;
16794 	ipsec_in_t *ii;
16795 	boolean_t ill_need_rele = B_FALSE;
16796 	boolean_t rill_need_rele = B_FALSE;
16797 	boolean_t ire_need_rele = B_FALSE;
16798 	netstack_t	*ns;
16799 	ip_stack_t	*ipst;
16800 
16801 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
16802 	ASSERT(ii->ipsec_in_ill_index != 0);
16803 	ns = ii->ipsec_in_ns;
16804 	ASSERT(ii->ipsec_in_ns != NULL);
16805 	ipst = ns->netstack_ip;
16806 
16807 	mp = ipsec_mp->b_cont;
16808 	ASSERT(mp != NULL);
16809 
16810 
16811 	if (ill == NULL) {
16812 		ASSERT(recv_ill == NULL);
16813 		/*
16814 		 * We need to get the original queue on which ip_rput_local
16815 		 * or ip_rput_data_v6 was called.
16816 		 */
16817 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
16818 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
16819 		ill_need_rele = B_TRUE;
16820 
16821 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
16822 			recv_ill = ill_lookup_on_ifindex(
16823 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
16824 			    NULL, NULL, NULL, NULL, ipst);
16825 			rill_need_rele = B_TRUE;
16826 		} else {
16827 			recv_ill = ill;
16828 		}
16829 
16830 		if ((ill == NULL) || (recv_ill == NULL)) {
16831 			ip0dbg(("ip_fanout_proto_again: interface "
16832 			    "disappeared\n"));
16833 			if (ill != NULL)
16834 				ill_refrele(ill);
16835 			if (recv_ill != NULL)
16836 				ill_refrele(recv_ill);
16837 			freemsg(ipsec_mp);
16838 			return;
16839 		}
16840 	}
16841 
16842 	ASSERT(ill != NULL && recv_ill != NULL);
16843 
16844 	if (mp->b_datap->db_type == M_CTL) {
16845 		/*
16846 		 * AH/ESP is returning the ICMP message after
16847 		 * removing their headers. Fanout again till
16848 		 * it gets to the right protocol.
16849 		 */
16850 		if (ii->ipsec_in_v4) {
16851 			icmph_t *icmph;
16852 			int iph_hdr_length;
16853 			int hdr_length;
16854 
16855 			ipha = (ipha_t *)mp->b_rptr;
16856 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
16857 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
16858 			ipha = (ipha_t *)&icmph[1];
16859 			hdr_length = IPH_HDR_LENGTH(ipha);
16860 			/*
16861 			 * icmp_inbound_error_fanout may need to do pullupmsg.
16862 			 * Reset the type to M_DATA.
16863 			 */
16864 			mp->b_datap->db_type = M_DATA;
16865 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
16866 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
16867 			    B_FALSE, ill, ii->ipsec_in_zoneid);
16868 		} else {
16869 			icmp6_t *icmp6;
16870 			int hdr_length;
16871 
16872 			ip6h = (ip6_t *)mp->b_rptr;
16873 			/* Don't call hdr_length_v6() unless you have to. */
16874 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
16875 				hdr_length = ip_hdr_length_v6(mp, ip6h);
16876 			else
16877 				hdr_length = IPV6_HDR_LEN;
16878 
16879 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
16880 			/*
16881 			 * icmp_inbound_error_fanout_v6 may need to do
16882 			 * pullupmsg.  Reset the type to M_DATA.
16883 			 */
16884 			mp->b_datap->db_type = M_DATA;
16885 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
16886 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
16887 		}
16888 		if (ill_need_rele)
16889 			ill_refrele(ill);
16890 		if (rill_need_rele)
16891 			ill_refrele(recv_ill);
16892 		return;
16893 	}
16894 
16895 	if (ii->ipsec_in_v4) {
16896 		ipha = (ipha_t *)mp->b_rptr;
16897 		dst = ipha->ipha_dst;
16898 		if (CLASSD(dst)) {
16899 			/*
16900 			 * Multicast has to be delivered to all streams.
16901 			 */
16902 			dst = INADDR_BROADCAST;
16903 		}
16904 
16905 		if (ire == NULL) {
16906 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
16907 			    MBLK_GETLABEL(mp), ipst);
16908 			if (ire == NULL) {
16909 				if (ill_need_rele)
16910 					ill_refrele(ill);
16911 				if (rill_need_rele)
16912 					ill_refrele(recv_ill);
16913 				ip1dbg(("ip_fanout_proto_again: "
16914 				    "IRE not found"));
16915 				freemsg(ipsec_mp);
16916 				return;
16917 			}
16918 			ire_need_rele = B_TRUE;
16919 		}
16920 
16921 		switch (ipha->ipha_protocol) {
16922 			case IPPROTO_UDP:
16923 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
16924 				    recv_ill);
16925 				if (ire_need_rele)
16926 					ire_refrele(ire);
16927 				break;
16928 			case IPPROTO_TCP:
16929 				if (!ire_need_rele)
16930 					IRE_REFHOLD(ire);
16931 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
16932 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
16933 				IRE_REFRELE(ire);
16934 				if (mp != NULL)
16935 					squeue_enter_chain(GET_SQUEUE(mp), mp,
16936 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
16937 				break;
16938 			case IPPROTO_SCTP:
16939 				if (!ire_need_rele)
16940 					IRE_REFHOLD(ire);
16941 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
16942 				    ipsec_mp, 0, ill->ill_rq, dst);
16943 				break;
16944 			default:
16945 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
16946 				    recv_ill, B_FALSE);
16947 				if (ire_need_rele)
16948 					ire_refrele(ire);
16949 				break;
16950 		}
16951 	} else {
16952 		uint32_t rput_flags = 0;
16953 
16954 		ip6h = (ip6_t *)mp->b_rptr;
16955 		v6dstp = &ip6h->ip6_dst;
16956 		/*
16957 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
16958 		 * address.
16959 		 *
16960 		 * Currently, we don't store that state in the IPSEC_IN
16961 		 * message, and we may need to.
16962 		 */
16963 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
16964 		    IP6_IN_LLMCAST : 0);
16965 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
16966 		    NULL, NULL);
16967 	}
16968 	if (ill_need_rele)
16969 		ill_refrele(ill);
16970 	if (rill_need_rele)
16971 		ill_refrele(recv_ill);
16972 }
16973 
16974 /*
16975  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
16976  * returns 'true' if there are still fragments left on the queue, in
16977  * which case we restart the timer.
16978  */
16979 void
16980 ill_frag_timer(void *arg)
16981 {
16982 	ill_t	*ill = (ill_t *)arg;
16983 	boolean_t frag_pending;
16984 	ip_stack_t	*ipst = ill->ill_ipst;
16985 
16986 	mutex_enter(&ill->ill_lock);
16987 	ASSERT(!ill->ill_fragtimer_executing);
16988 	if (ill->ill_state_flags & ILL_CONDEMNED) {
16989 		ill->ill_frag_timer_id = 0;
16990 		mutex_exit(&ill->ill_lock);
16991 		return;
16992 	}
16993 	ill->ill_fragtimer_executing = 1;
16994 	mutex_exit(&ill->ill_lock);
16995 
16996 	frag_pending = ill_frag_timeout(ill, ipst->ips_ip_g_frag_timeout);
16997 
16998 	/*
16999 	 * Restart the timer, if we have fragments pending or if someone
17000 	 * wanted us to be scheduled again.
17001 	 */
17002 	mutex_enter(&ill->ill_lock);
17003 	ill->ill_fragtimer_executing = 0;
17004 	ill->ill_frag_timer_id = 0;
17005 	if (frag_pending || ill->ill_fragtimer_needrestart)
17006 		ill_frag_timer_start(ill);
17007 	mutex_exit(&ill->ill_lock);
17008 }
17009 
17010 void
17011 ill_frag_timer_start(ill_t *ill)
17012 {
17013 	ip_stack_t	*ipst = ill->ill_ipst;
17014 
17015 	ASSERT(MUTEX_HELD(&ill->ill_lock));
17016 
17017 	/* If the ill is closing or opening don't proceed */
17018 	if (ill->ill_state_flags & ILL_CONDEMNED)
17019 		return;
17020 
17021 	if (ill->ill_fragtimer_executing) {
17022 		/*
17023 		 * ill_frag_timer is currently executing. Just record the
17024 		 * the fact that we want the timer to be restarted.
17025 		 * ill_frag_timer will post a timeout before it returns,
17026 		 * ensuring it will be called again.
17027 		 */
17028 		ill->ill_fragtimer_needrestart = 1;
17029 		return;
17030 	}
17031 
17032 	if (ill->ill_frag_timer_id == 0) {
17033 		/*
17034 		 * The timer is neither running nor is the timeout handler
17035 		 * executing. Post a timeout so that ill_frag_timer will be
17036 		 * called
17037 		 */
17038 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
17039 		    MSEC_TO_TICK(ipst->ips_ip_g_frag_timo_ms >> 1));
17040 		ill->ill_fragtimer_needrestart = 0;
17041 	}
17042 }
17043 
17044 /*
17045  * This routine is needed for loopback when forwarding multicasts.
17046  *
17047  * IPQoS Notes:
17048  * IPPF processing is done in fanout routines.
17049  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
17050  * processing for IPsec packets is done when it comes back in clear.
17051  * NOTE : The callers of this function need to do the ire_refrele for the
17052  *	  ire that is being passed in.
17053  */
17054 void
17055 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17056     ill_t *recv_ill, boolean_t esp_in_udp_packet)
17057 {
17058 	ill_t	*ill = (ill_t *)q->q_ptr;
17059 	uint32_t	sum;
17060 	uint32_t	u1;
17061 	uint32_t	u2;
17062 	int		hdr_length;
17063 	boolean_t	mctl_present;
17064 	mblk_t		*first_mp = mp;
17065 	mblk_t		*hada_mp = NULL;
17066 	ipha_t		*inner_ipha;
17067 	ip_stack_t	*ipst;
17068 
17069 	ASSERT(recv_ill != NULL);
17070 	ipst = recv_ill->ill_ipst;
17071 
17072 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17073 	    "ip_rput_locl_start: q %p", q);
17074 
17075 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17076 	ASSERT(ill != NULL);
17077 
17078 
17079 #define	rptr	((uchar_t *)ipha)
17080 #define	iphs	((uint16_t *)ipha)
17081 
17082 	/*
17083 	 * no UDP or TCP packet should come here anymore.
17084 	 */
17085 	ASSERT(ipha->ipha_protocol != IPPROTO_TCP &&
17086 	    ipha->ipha_protocol != IPPROTO_UDP);
17087 
17088 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17089 	if (mctl_present &&
17090 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17091 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17092 
17093 		/*
17094 		 * It's an IPsec accelerated packet.
17095 		 * Keep a pointer to the data attributes around until
17096 		 * we allocate the ipsec_info_t.
17097 		 */
17098 		IPSECHW_DEBUG(IPSECHW_PKT,
17099 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17100 		hada_mp = first_mp;
17101 		hada_mp->b_cont = NULL;
17102 		/*
17103 		 * Since it is accelerated, it comes directly from
17104 		 * the ill and the data attributes is followed by
17105 		 * the packet data.
17106 		 */
17107 		ASSERT(mp->b_datap->db_type != M_CTL);
17108 		first_mp = mp;
17109 		mctl_present = B_FALSE;
17110 	}
17111 
17112 	/*
17113 	 * IF M_CTL is not present, then ipsec_in_is_secure
17114 	 * should return B_TRUE. There is a case where loopback
17115 	 * packets has an M_CTL in the front with all the
17116 	 * IPsec options set to IPSEC_PREF_NEVER - which means
17117 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17118 	 * packets never comes here, it is safe to ASSERT the
17119 	 * following.
17120 	 */
17121 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17122 
17123 	/*
17124 	 * Also, we should never have an mctl_present if this is an
17125 	 * ESP-in-UDP packet.
17126 	 */
17127 	ASSERT(!mctl_present || !esp_in_udp_packet);
17128 
17129 
17130 	/* u1 is # words of IP options */
17131 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
17132 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17133 
17134 	if (u1 || (!esp_in_udp_packet && !mctl_present)) {
17135 		if (u1) {
17136 			if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17137 				if (hada_mp != NULL)
17138 					freemsg(hada_mp);
17139 				return;
17140 			}
17141 		} else {
17142 			/* Check the IP header checksum.  */
17143 #define	uph	((uint16_t *)ipha)
17144 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
17145 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
17146 #undef  uph
17147 			/* finish doing IP checksum */
17148 			sum = (sum & 0xFFFF) + (sum >> 16);
17149 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
17150 			if (sum && sum != 0xFFFF) {
17151 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17152 				goto drop_pkt;
17153 			}
17154 		}
17155 	}
17156 
17157 	/*
17158 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17159 	 * might be called more than once for secure packets, count only
17160 	 * the first time.
17161 	 */
17162 	if (!mctl_present) {
17163 		UPDATE_IB_PKT_COUNT(ire);
17164 		ire->ire_last_used_time = lbolt;
17165 	}
17166 
17167 	/* Check for fragmentation offset. */
17168 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17169 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17170 	if (u1) {
17171 		/*
17172 		 * We re-assemble fragments before we do the AH/ESP
17173 		 * processing. Thus, M_CTL should not be present
17174 		 * while we are re-assembling.
17175 		 */
17176 		ASSERT(!mctl_present);
17177 		ASSERT(first_mp == mp);
17178 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
17179 			return;
17180 		}
17181 		/*
17182 		 * Make sure that first_mp points back to mp as
17183 		 * the mp we came in with could have changed in
17184 		 * ip_rput_fragment().
17185 		 */
17186 		ipha = (ipha_t *)mp->b_rptr;
17187 		first_mp = mp;
17188 	}
17189 
17190 	/*
17191 	 * Clear hardware checksumming flag as it is currently only
17192 	 * used by TCP and UDP.
17193 	 */
17194 	DB_CKSUMFLAGS(mp) = 0;
17195 
17196 	/* Now we have a complete datagram, destined for this machine. */
17197 	u1 = IPH_HDR_LENGTH(ipha);
17198 	switch (ipha->ipha_protocol) {
17199 	case IPPROTO_ICMP: {
17200 		ire_t		*ire_zone;
17201 		ilm_t		*ilm;
17202 		mblk_t		*mp1;
17203 		zoneid_t	last_zoneid;
17204 
17205 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(recv_ill)) {
17206 			ASSERT(ire->ire_type == IRE_BROADCAST);
17207 			/*
17208 			 * In the multicast case, applications may have joined
17209 			 * the group from different zones, so we need to deliver
17210 			 * the packet to each of them. Loop through the
17211 			 * multicast memberships structures (ilm) on the receive
17212 			 * ill and send a copy of the packet up each matching
17213 			 * one. However, we don't do this for multicasts sent on
17214 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17215 			 * they must stay in the sender's zone.
17216 			 *
17217 			 * ilm_add_v6() ensures that ilms in the same zone are
17218 			 * contiguous in the ill_ilm list. We use this property
17219 			 * to avoid sending duplicates needed when two
17220 			 * applications in the same zone join the same group on
17221 			 * different logical interfaces: we ignore the ilm if
17222 			 * its zoneid is the same as the last matching one.
17223 			 * In addition, the sending of the packet for
17224 			 * ire_zoneid is delayed until all of the other ilms
17225 			 * have been exhausted.
17226 			 */
17227 			last_zoneid = -1;
17228 			ILM_WALKER_HOLD(recv_ill);
17229 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
17230 			    ilm = ilm->ilm_next) {
17231 				if ((ilm->ilm_flags & ILM_DELETED) ||
17232 				    ipha->ipha_dst != ilm->ilm_addr ||
17233 				    ilm->ilm_zoneid == last_zoneid ||
17234 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17235 				    ilm->ilm_zoneid == ALL_ZONES ||
17236 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17237 					continue;
17238 				mp1 = ip_copymsg(first_mp);
17239 				if (mp1 == NULL)
17240 					continue;
17241 				icmp_inbound(q, mp1, B_TRUE, ill,
17242 				    0, sum, mctl_present, B_TRUE,
17243 				    recv_ill, ilm->ilm_zoneid);
17244 				last_zoneid = ilm->ilm_zoneid;
17245 			}
17246 			ILM_WALKER_RELE(recv_ill);
17247 		} else if (ire->ire_type == IRE_BROADCAST) {
17248 			/*
17249 			 * In the broadcast case, there may be many zones
17250 			 * which need a copy of the packet delivered to them.
17251 			 * There is one IRE_BROADCAST per broadcast address
17252 			 * and per zone; we walk those using a helper function.
17253 			 * In addition, the sending of the packet for ire is
17254 			 * delayed until all of the other ires have been
17255 			 * processed.
17256 			 */
17257 			IRB_REFHOLD(ire->ire_bucket);
17258 			ire_zone = NULL;
17259 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17260 			    ire)) != NULL) {
17261 				mp1 = ip_copymsg(first_mp);
17262 				if (mp1 == NULL)
17263 					continue;
17264 
17265 				UPDATE_IB_PKT_COUNT(ire_zone);
17266 				ire_zone->ire_last_used_time = lbolt;
17267 				icmp_inbound(q, mp1, B_TRUE, ill,
17268 				    0, sum, mctl_present, B_TRUE,
17269 				    recv_ill, ire_zone->ire_zoneid);
17270 			}
17271 			IRB_REFRELE(ire->ire_bucket);
17272 		}
17273 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17274 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17275 		    ire->ire_zoneid);
17276 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17277 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17278 		return;
17279 	}
17280 	case IPPROTO_IGMP:
17281 		/*
17282 		 * If we are not willing to accept IGMP packets in clear,
17283 		 * then check with global policy.
17284 		 */
17285 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17286 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17287 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17288 			if (first_mp == NULL)
17289 				return;
17290 		}
17291 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17292 			freemsg(first_mp);
17293 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17294 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17295 			return;
17296 		}
17297 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17298 			/* Bad packet - discarded by igmp_input */
17299 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17300 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17301 			if (mctl_present)
17302 				freeb(first_mp);
17303 			return;
17304 		}
17305 		/*
17306 		 * igmp_input() may have returned the pulled up message.
17307 		 * So first_mp and ipha need to be reinitialized.
17308 		 */
17309 		ipha = (ipha_t *)mp->b_rptr;
17310 		if (mctl_present)
17311 			first_mp->b_cont = mp;
17312 		else
17313 			first_mp = mp;
17314 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17315 		    connf_head != NULL) {
17316 			/* No user-level listener for IGMP packets */
17317 			goto drop_pkt;
17318 		}
17319 		/* deliver to local raw users */
17320 		break;
17321 	case IPPROTO_PIM:
17322 		/*
17323 		 * If we are not willing to accept PIM packets in clear,
17324 		 * then check with global policy.
17325 		 */
17326 		if (ipst->ips_pim_accept_clear_messages == 0) {
17327 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17328 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17329 			if (first_mp == NULL)
17330 				return;
17331 		}
17332 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17333 			freemsg(first_mp);
17334 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17335 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17336 			return;
17337 		}
17338 		if (pim_input(q, mp, ill) != 0) {
17339 			/* Bad packet - discarded by pim_input */
17340 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17341 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17342 			if (mctl_present)
17343 				freeb(first_mp);
17344 			return;
17345 		}
17346 
17347 		/*
17348 		 * pim_input() may have pulled up the message so ipha needs to
17349 		 * be reinitialized.
17350 		 */
17351 		ipha = (ipha_t *)mp->b_rptr;
17352 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17353 		    connf_head != NULL) {
17354 			/* No user-level listener for PIM packets */
17355 			goto drop_pkt;
17356 		}
17357 		/* deliver to local raw users */
17358 		break;
17359 	case IPPROTO_ENCAP:
17360 		/*
17361 		 * Handle self-encapsulated packets (IP-in-IP where
17362 		 * the inner addresses == the outer addresses).
17363 		 */
17364 		hdr_length = IPH_HDR_LENGTH(ipha);
17365 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17366 		    mp->b_wptr) {
17367 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17368 			    sizeof (ipha_t) - mp->b_rptr)) {
17369 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17370 				freemsg(first_mp);
17371 				return;
17372 			}
17373 			ipha = (ipha_t *)mp->b_rptr;
17374 		}
17375 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17376 		/*
17377 		 * Check the sanity of the inner IP header.
17378 		 */
17379 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17380 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17381 			freemsg(first_mp);
17382 			return;
17383 		}
17384 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17385 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17386 			freemsg(first_mp);
17387 			return;
17388 		}
17389 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17390 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17391 			ipsec_in_t *ii;
17392 
17393 			/*
17394 			 * Self-encapsulated tunnel packet. Remove
17395 			 * the outer IP header and fanout again.
17396 			 * We also need to make sure that the inner
17397 			 * header is pulled up until options.
17398 			 */
17399 			mp->b_rptr = (uchar_t *)inner_ipha;
17400 			ipha = inner_ipha;
17401 			hdr_length = IPH_HDR_LENGTH(ipha);
17402 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17403 				if (!pullupmsg(mp, (uchar_t *)ipha +
17404 				    + hdr_length - mp->b_rptr)) {
17405 					freemsg(first_mp);
17406 					return;
17407 				}
17408 				ipha = (ipha_t *)mp->b_rptr;
17409 			}
17410 			if (!mctl_present) {
17411 				ASSERT(first_mp == mp);
17412 				/*
17413 				 * This means that somebody is sending
17414 				 * Self-encapsualted packets without AH/ESP.
17415 				 * If AH/ESP was present, we would have already
17416 				 * allocated the first_mp.
17417 				 */
17418 				first_mp = ipsec_in_alloc(B_TRUE,
17419 				    ipst->ips_netstack);
17420 				if (first_mp == NULL) {
17421 					ip1dbg(("ip_proto_input: IPSEC_IN "
17422 					    "allocation failure.\n"));
17423 					BUMP_MIB(ill->ill_ip_mib,
17424 					    ipIfStatsInDiscards);
17425 					freemsg(mp);
17426 					return;
17427 				}
17428 				first_mp->b_cont = mp;
17429 			}
17430 			/*
17431 			 * We generally store the ill_index if we need to
17432 			 * do IPsec processing as we lose the ill queue when
17433 			 * we come back. But in this case, we never should
17434 			 * have to store the ill_index here as it should have
17435 			 * been stored previously when we processed the
17436 			 * AH/ESP header in this routine or for non-ipsec
17437 			 * cases, we still have the queue. But for some bad
17438 			 * packets from the wire, we can get to IPsec after
17439 			 * this and we better store the index for that case.
17440 			 */
17441 			ill = (ill_t *)q->q_ptr;
17442 			ii = (ipsec_in_t *)first_mp->b_rptr;
17443 			ii->ipsec_in_ill_index =
17444 			    ill->ill_phyint->phyint_ifindex;
17445 			ii->ipsec_in_rill_index =
17446 			    recv_ill->ill_phyint->phyint_ifindex;
17447 			if (ii->ipsec_in_decaps) {
17448 				/*
17449 				 * This packet is self-encapsulated multiple
17450 				 * times. We don't want to recurse infinitely.
17451 				 * To keep it simple, drop the packet.
17452 				 */
17453 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17454 				freemsg(first_mp);
17455 				return;
17456 			}
17457 			ii->ipsec_in_decaps = B_TRUE;
17458 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17459 			    ire);
17460 			return;
17461 		}
17462 		break;
17463 	case IPPROTO_AH:
17464 	case IPPROTO_ESP: {
17465 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17466 
17467 		/*
17468 		 * Fast path for AH/ESP. If this is the first time
17469 		 * we are sending a datagram to AH/ESP, allocate
17470 		 * a IPSEC_IN message and prepend it. Otherwise,
17471 		 * just fanout.
17472 		 */
17473 
17474 		int ipsec_rc;
17475 		ipsec_in_t *ii;
17476 		netstack_t *ns = ipst->ips_netstack;
17477 
17478 		IP_STAT(ipst, ipsec_proto_ahesp);
17479 		if (!mctl_present) {
17480 			ASSERT(first_mp == mp);
17481 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17482 			if (first_mp == NULL) {
17483 				ip1dbg(("ip_proto_input: IPSEC_IN "
17484 				    "allocation failure.\n"));
17485 				freemsg(hada_mp); /* okay ifnull */
17486 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17487 				freemsg(mp);
17488 				return;
17489 			}
17490 			/*
17491 			 * Store the ill_index so that when we come back
17492 			 * from IPsec we ride on the same queue.
17493 			 */
17494 			ill = (ill_t *)q->q_ptr;
17495 			ii = (ipsec_in_t *)first_mp->b_rptr;
17496 			ii->ipsec_in_ill_index =
17497 			    ill->ill_phyint->phyint_ifindex;
17498 			ii->ipsec_in_rill_index =
17499 			    recv_ill->ill_phyint->phyint_ifindex;
17500 			first_mp->b_cont = mp;
17501 			/*
17502 			 * Cache hardware acceleration info.
17503 			 */
17504 			if (hada_mp != NULL) {
17505 				IPSECHW_DEBUG(IPSECHW_PKT,
17506 				    ("ip_rput_local: caching data attr.\n"));
17507 				ii->ipsec_in_accelerated = B_TRUE;
17508 				ii->ipsec_in_da = hada_mp;
17509 				hada_mp = NULL;
17510 			}
17511 		} else {
17512 			ii = (ipsec_in_t *)first_mp->b_rptr;
17513 		}
17514 
17515 		if (!ipsec_loaded(ipss)) {
17516 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17517 			    ire->ire_zoneid, ipst);
17518 			return;
17519 		}
17520 
17521 		ns = ipst->ips_netstack;
17522 		/* select inbound SA and have IPsec process the pkt */
17523 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17524 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17525 			boolean_t esp_in_udp_sa;
17526 			if (esph == NULL)
17527 				return;
17528 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17529 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17530 			esp_in_udp_sa = ((ii->ipsec_in_esp_sa->ipsa_flags &
17531 			    IPSA_F_NATT) != 0);
17532 			/*
17533 			 * The following is a fancy, but quick, way of saying:
17534 			 * ESP-in-UDP SA and Raw ESP packet --> drop
17535 			 *    OR
17536 			 * ESP SA and ESP-in-UDP packet --> drop
17537 			 */
17538 			if (esp_in_udp_sa != esp_in_udp_packet) {
17539 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17540 				ip_drop_packet(first_mp, B_TRUE, ill, NULL,
17541 				    DROPPER(ns->netstack_ipsec, ipds_esp_no_sa),
17542 				    &ns->netstack_ipsec->ipsec_dropper);
17543 				return;
17544 			}
17545 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17546 			    first_mp, esph);
17547 		} else {
17548 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
17549 			if (ah == NULL)
17550 				return;
17551 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17552 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17553 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17554 			    first_mp, ah);
17555 		}
17556 
17557 		switch (ipsec_rc) {
17558 		case IPSEC_STATUS_SUCCESS:
17559 			break;
17560 		case IPSEC_STATUS_FAILED:
17561 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17562 			/* FALLTHRU */
17563 		case IPSEC_STATUS_PENDING:
17564 			return;
17565 		}
17566 		/* we're done with IPsec processing, send it up */
17567 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17568 		return;
17569 	}
17570 	default:
17571 		break;
17572 	}
17573 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17574 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17575 		    ire->ire_zoneid));
17576 		goto drop_pkt;
17577 	}
17578 	/*
17579 	 * Handle protocols with which IP is less intimate.  There
17580 	 * can be more than one stream bound to a particular
17581 	 * protocol.  When this is the case, each one gets a copy
17582 	 * of any incoming packets.
17583 	 */
17584 	ip_fanout_proto(q, first_mp, ill, ipha,
17585 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17586 	    B_TRUE, recv_ill, ire->ire_zoneid);
17587 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17588 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17589 	return;
17590 
17591 drop_pkt:
17592 	freemsg(first_mp);
17593 	if (hada_mp != NULL)
17594 		freeb(hada_mp);
17595 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17596 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17597 #undef	rptr
17598 #undef  iphs
17599 
17600 }
17601 
17602 /*
17603  * Update any source route, record route or timestamp options.
17604  * Check that we are at end of strict source route.
17605  * The options have already been checked for sanity in ip_rput_options().
17606  */
17607 static boolean_t
17608 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17609     ip_stack_t *ipst)
17610 {
17611 	ipoptp_t	opts;
17612 	uchar_t		*opt;
17613 	uint8_t		optval;
17614 	uint8_t		optlen;
17615 	ipaddr_t	dst;
17616 	uint32_t	ts;
17617 	ire_t		*dst_ire;
17618 	timestruc_t	now;
17619 	zoneid_t	zoneid;
17620 	ill_t		*ill;
17621 
17622 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17623 
17624 	ip2dbg(("ip_rput_local_options\n"));
17625 
17626 	for (optval = ipoptp_first(&opts, ipha);
17627 	    optval != IPOPT_EOL;
17628 	    optval = ipoptp_next(&opts)) {
17629 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17630 		opt = opts.ipoptp_cur;
17631 		optlen = opts.ipoptp_len;
17632 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17633 		    optval, optlen));
17634 		switch (optval) {
17635 			uint32_t off;
17636 		case IPOPT_SSRR:
17637 		case IPOPT_LSRR:
17638 			off = opt[IPOPT_OFFSET];
17639 			off--;
17640 			if (optlen < IP_ADDR_LEN ||
17641 			    off > optlen - IP_ADDR_LEN) {
17642 				/* End of source route */
17643 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17644 				break;
17645 			}
17646 			/*
17647 			 * This will only happen if two consecutive entries
17648 			 * in the source route contains our address or if
17649 			 * it is a packet with a loose source route which
17650 			 * reaches us before consuming the whole source route
17651 			 */
17652 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17653 			if (optval == IPOPT_SSRR) {
17654 				goto bad_src_route;
17655 			}
17656 			/*
17657 			 * Hack: instead of dropping the packet truncate the
17658 			 * source route to what has been used by filling the
17659 			 * rest with IPOPT_NOP.
17660 			 */
17661 			opt[IPOPT_OLEN] = (uint8_t)off;
17662 			while (off < optlen) {
17663 				opt[off++] = IPOPT_NOP;
17664 			}
17665 			break;
17666 		case IPOPT_RR:
17667 			off = opt[IPOPT_OFFSET];
17668 			off--;
17669 			if (optlen < IP_ADDR_LEN ||
17670 			    off > optlen - IP_ADDR_LEN) {
17671 				/* No more room - ignore */
17672 				ip1dbg((
17673 				    "ip_rput_local_options: end of RR\n"));
17674 				break;
17675 			}
17676 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17677 			    IP_ADDR_LEN);
17678 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17679 			break;
17680 		case IPOPT_TS:
17681 			/* Insert timestamp if there is romm */
17682 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17683 			case IPOPT_TS_TSONLY:
17684 				off = IPOPT_TS_TIMELEN;
17685 				break;
17686 			case IPOPT_TS_PRESPEC:
17687 			case IPOPT_TS_PRESPEC_RFC791:
17688 				/* Verify that the address matched */
17689 				off = opt[IPOPT_OFFSET] - 1;
17690 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17691 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17692 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
17693 				    ipst);
17694 				if (dst_ire == NULL) {
17695 					/* Not for us */
17696 					break;
17697 				}
17698 				ire_refrele(dst_ire);
17699 				/* FALLTHRU */
17700 			case IPOPT_TS_TSANDADDR:
17701 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17702 				break;
17703 			default:
17704 				/*
17705 				 * ip_*put_options should have already
17706 				 * dropped this packet.
17707 				 */
17708 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17709 				    "unknown IT - bug in ip_rput_options?\n");
17710 				return (B_TRUE);	/* Keep "lint" happy */
17711 			}
17712 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17713 				/* Increase overflow counter */
17714 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17715 				opt[IPOPT_POS_OV_FLG] =
17716 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17717 				    (off << 4));
17718 				break;
17719 			}
17720 			off = opt[IPOPT_OFFSET] - 1;
17721 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17722 			case IPOPT_TS_PRESPEC:
17723 			case IPOPT_TS_PRESPEC_RFC791:
17724 			case IPOPT_TS_TSANDADDR:
17725 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17726 				    IP_ADDR_LEN);
17727 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17728 				/* FALLTHRU */
17729 			case IPOPT_TS_TSONLY:
17730 				off = opt[IPOPT_OFFSET] - 1;
17731 				/* Compute # of milliseconds since midnight */
17732 				gethrestime(&now);
17733 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17734 				    now.tv_nsec / (NANOSEC / MILLISEC);
17735 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17736 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17737 				break;
17738 			}
17739 			break;
17740 		}
17741 	}
17742 	return (B_TRUE);
17743 
17744 bad_src_route:
17745 	q = WR(q);
17746 	if (q->q_next != NULL)
17747 		ill = q->q_ptr;
17748 	else
17749 		ill = NULL;
17750 
17751 	/* make sure we clear any indication of a hardware checksum */
17752 	DB_CKSUMFLAGS(mp) = 0;
17753 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
17754 	if (zoneid == ALL_ZONES)
17755 		freemsg(mp);
17756 	else
17757 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17758 	return (B_FALSE);
17759 
17760 }
17761 
17762 /*
17763  * Process IP options in an inbound packet.  If an option affects the
17764  * effective destination address, return the next hop address via dstp.
17765  * Returns -1 if something fails in which case an ICMP error has been sent
17766  * and mp freed.
17767  */
17768 static int
17769 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
17770     ip_stack_t *ipst)
17771 {
17772 	ipoptp_t	opts;
17773 	uchar_t		*opt;
17774 	uint8_t		optval;
17775 	uint8_t		optlen;
17776 	ipaddr_t	dst;
17777 	intptr_t	code = 0;
17778 	ire_t		*ire = NULL;
17779 	zoneid_t	zoneid;
17780 	ill_t		*ill;
17781 
17782 	ip2dbg(("ip_rput_options\n"));
17783 	dst = ipha->ipha_dst;
17784 	for (optval = ipoptp_first(&opts, ipha);
17785 	    optval != IPOPT_EOL;
17786 	    optval = ipoptp_next(&opts)) {
17787 		opt = opts.ipoptp_cur;
17788 		optlen = opts.ipoptp_len;
17789 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17790 		    optval, optlen));
17791 		/*
17792 		 * Note: we need to verify the checksum before we
17793 		 * modify anything thus this routine only extracts the next
17794 		 * hop dst from any source route.
17795 		 */
17796 		switch (optval) {
17797 			uint32_t off;
17798 		case IPOPT_SSRR:
17799 		case IPOPT_LSRR:
17800 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17801 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17802 			if (ire == NULL) {
17803 				if (optval == IPOPT_SSRR) {
17804 					ip1dbg(("ip_rput_options: not next"
17805 					    " strict source route 0x%x\n",
17806 					    ntohl(dst)));
17807 					code = (char *)&ipha->ipha_dst -
17808 					    (char *)ipha;
17809 					goto param_prob; /* RouterReq's */
17810 				}
17811 				ip2dbg(("ip_rput_options: "
17812 				    "not next source route 0x%x\n",
17813 				    ntohl(dst)));
17814 				break;
17815 			}
17816 			ire_refrele(ire);
17817 
17818 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17819 				ip1dbg((
17820 				    "ip_rput_options: bad option offset\n"));
17821 				code = (char *)&opt[IPOPT_OLEN] -
17822 				    (char *)ipha;
17823 				goto param_prob;
17824 			}
17825 			off = opt[IPOPT_OFFSET];
17826 			off--;
17827 		redo_srr:
17828 			if (optlen < IP_ADDR_LEN ||
17829 			    off > optlen - IP_ADDR_LEN) {
17830 				/* End of source route */
17831 				ip1dbg(("ip_rput_options: end of SR\n"));
17832 				break;
17833 			}
17834 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17835 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
17836 			    ntohl(dst)));
17837 
17838 			/*
17839 			 * Check if our address is present more than
17840 			 * once as consecutive hops in source route.
17841 			 * XXX verify per-interface ip_forwarding
17842 			 * for source route?
17843 			 */
17844 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17845 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17846 
17847 			if (ire != NULL) {
17848 				ire_refrele(ire);
17849 				off += IP_ADDR_LEN;
17850 				goto redo_srr;
17851 			}
17852 
17853 			if (dst == htonl(INADDR_LOOPBACK)) {
17854 				ip1dbg(("ip_rput_options: loopback addr in "
17855 				    "source route!\n"));
17856 				goto bad_src_route;
17857 			}
17858 			/*
17859 			 * For strict: verify that dst is directly
17860 			 * reachable.
17861 			 */
17862 			if (optval == IPOPT_SSRR) {
17863 				ire = ire_ftable_lookup(dst, 0, 0,
17864 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
17865 				    MBLK_GETLABEL(mp),
17866 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
17867 				if (ire == NULL) {
17868 					ip1dbg(("ip_rput_options: SSRR not "
17869 					    "directly reachable: 0x%x\n",
17870 					    ntohl(dst)));
17871 					goto bad_src_route;
17872 				}
17873 				ire_refrele(ire);
17874 			}
17875 			/*
17876 			 * Defer update of the offset and the record route
17877 			 * until the packet is forwarded.
17878 			 */
17879 			break;
17880 		case IPOPT_RR:
17881 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17882 				ip1dbg((
17883 				    "ip_rput_options: bad option offset\n"));
17884 				code = (char *)&opt[IPOPT_OLEN] -
17885 				    (char *)ipha;
17886 				goto param_prob;
17887 			}
17888 			break;
17889 		case IPOPT_TS:
17890 			/*
17891 			 * Verify that length >= 5 and that there is either
17892 			 * room for another timestamp or that the overflow
17893 			 * counter is not maxed out.
17894 			 */
17895 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
17896 			if (optlen < IPOPT_MINLEN_IT) {
17897 				goto param_prob;
17898 			}
17899 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17900 				ip1dbg((
17901 				    "ip_rput_options: bad option offset\n"));
17902 				code = (char *)&opt[IPOPT_OFFSET] -
17903 				    (char *)ipha;
17904 				goto param_prob;
17905 			}
17906 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17907 			case IPOPT_TS_TSONLY:
17908 				off = IPOPT_TS_TIMELEN;
17909 				break;
17910 			case IPOPT_TS_TSANDADDR:
17911 			case IPOPT_TS_PRESPEC:
17912 			case IPOPT_TS_PRESPEC_RFC791:
17913 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17914 				break;
17915 			default:
17916 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
17917 				    (char *)ipha;
17918 				goto param_prob;
17919 			}
17920 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
17921 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
17922 				/*
17923 				 * No room and the overflow counter is 15
17924 				 * already.
17925 				 */
17926 				goto param_prob;
17927 			}
17928 			break;
17929 		}
17930 	}
17931 
17932 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
17933 		*dstp = dst;
17934 		return (0);
17935 	}
17936 
17937 	ip1dbg(("ip_rput_options: error processing IP options."));
17938 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
17939 
17940 param_prob:
17941 	q = WR(q);
17942 	if (q->q_next != NULL)
17943 		ill = q->q_ptr;
17944 	else
17945 		ill = NULL;
17946 
17947 	/* make sure we clear any indication of a hardware checksum */
17948 	DB_CKSUMFLAGS(mp) = 0;
17949 	/* Don't know whether this is for non-global or global/forwarding */
17950 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
17951 	if (zoneid == ALL_ZONES)
17952 		freemsg(mp);
17953 	else
17954 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
17955 	return (-1);
17956 
17957 bad_src_route:
17958 	q = WR(q);
17959 	if (q->q_next != NULL)
17960 		ill = q->q_ptr;
17961 	else
17962 		ill = NULL;
17963 
17964 	/* make sure we clear any indication of a hardware checksum */
17965 	DB_CKSUMFLAGS(mp) = 0;
17966 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
17967 	if (zoneid == ALL_ZONES)
17968 		freemsg(mp);
17969 	else
17970 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17971 	return (-1);
17972 }
17973 
17974 /*
17975  * IP & ICMP info in >=14 msg's ...
17976  *  - ip fixed part (mib2_ip_t)
17977  *  - icmp fixed part (mib2_icmp_t)
17978  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
17979  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
17980  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
17981  *  - ipRouteAttributeTable (ip 102)	labeled routes
17982  *  - ip multicast membership (ip_member_t)
17983  *  - ip multicast source filtering (ip_grpsrc_t)
17984  *  - igmp fixed part (struct igmpstat)
17985  *  - multicast routing stats (struct mrtstat)
17986  *  - multicast routing vifs (array of struct vifctl)
17987  *  - multicast routing routes (array of struct mfcctl)
17988  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
17989  *					One per ill plus one generic
17990  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
17991  *					One per ill plus one generic
17992  *  - ipv6RouteEntry			all IPv6 IREs
17993  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
17994  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
17995  *  - ipv6AddrEntry			all IPv6 ipifs
17996  *  - ipv6 multicast membership (ipv6_member_t)
17997  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
17998  *
17999  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
18000  *
18001  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
18002  * already filled in by the caller.
18003  * Return value of 0 indicates that no messages were sent and caller
18004  * should free mpctl.
18005  */
18006 int
18007 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level)
18008 {
18009 	ip_stack_t *ipst;
18010 	sctp_stack_t *sctps;
18011 
18012 	if (q->q_next != NULL) {
18013 		ipst = ILLQ_TO_IPST(q);
18014 	} else {
18015 		ipst = CONNQ_TO_IPST(q);
18016 	}
18017 	ASSERT(ipst != NULL);
18018 	sctps = ipst->ips_netstack->netstack_sctp;
18019 
18020 	if (mpctl == NULL || mpctl->b_cont == NULL) {
18021 		return (0);
18022 	}
18023 
18024 	/*
18025 	 * For the purposes of the (broken) packet shell use
18026 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
18027 	 * to make TCP and UDP appear first in the list of mib items.
18028 	 * TBD: We could expand this and use it in netstat so that
18029 	 * the kernel doesn't have to produce large tables (connections,
18030 	 * routes, etc) when netstat only wants the statistics or a particular
18031 	 * table.
18032 	 */
18033 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
18034 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
18035 			return (1);
18036 		}
18037 	}
18038 
18039 	if (level != MIB2_TCP) {
18040 		if ((mpctl = udp_snmp_get(q, mpctl)) == NULL) {
18041 			return (1);
18042 		}
18043 	}
18044 
18045 	if (level != MIB2_UDP) {
18046 		if ((mpctl = tcp_snmp_get(q, mpctl)) == NULL) {
18047 			return (1);
18048 		}
18049 	}
18050 
18051 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
18052 	    ipst)) == NULL) {
18053 		return (1);
18054 	}
18055 
18056 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
18057 		return (1);
18058 	}
18059 
18060 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
18061 		return (1);
18062 	}
18063 
18064 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
18065 		return (1);
18066 	}
18067 
18068 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
18069 		return (1);
18070 	}
18071 
18072 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
18073 		return (1);
18074 	}
18075 
18076 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
18077 		return (1);
18078 	}
18079 
18080 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
18081 		return (1);
18082 	}
18083 
18084 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
18085 		return (1);
18086 	}
18087 
18088 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18089 		return (1);
18090 	}
18091 
18092 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18093 		return (1);
18094 	}
18095 
18096 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18097 		return (1);
18098 	}
18099 
18100 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18101 		return (1);
18102 	}
18103 
18104 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18105 		return (1);
18106 	}
18107 
18108 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, ipst)) == NULL) {
18109 		return (1);
18110 	}
18111 
18112 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, ipst);
18113 	if (mpctl == NULL) {
18114 		return (1);
18115 	}
18116 
18117 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18118 		return (1);
18119 	}
18120 	freemsg(mpctl);
18121 	return (1);
18122 }
18123 
18124 
18125 /* Get global (legacy) IPv4 statistics */
18126 static mblk_t *
18127 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18128     ip_stack_t *ipst)
18129 {
18130 	mib2_ip_t		old_ip_mib;
18131 	struct opthdr		*optp;
18132 	mblk_t			*mp2ctl;
18133 
18134 	/*
18135 	 * make a copy of the original message
18136 	 */
18137 	mp2ctl = copymsg(mpctl);
18138 
18139 	/* fixed length IP structure... */
18140 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18141 	optp->level = MIB2_IP;
18142 	optp->name = 0;
18143 	SET_MIB(old_ip_mib.ipForwarding,
18144 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18145 	SET_MIB(old_ip_mib.ipDefaultTTL,
18146 	    (uint32_t)ipst->ips_ip_def_ttl);
18147 	SET_MIB(old_ip_mib.ipReasmTimeout,
18148 	    ipst->ips_ip_g_frag_timeout);
18149 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18150 	    sizeof (mib2_ipAddrEntry_t));
18151 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18152 	    sizeof (mib2_ipRouteEntry_t));
18153 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18154 	    sizeof (mib2_ipNetToMediaEntry_t));
18155 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18156 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18157 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18158 	    sizeof (mib2_ipAttributeEntry_t));
18159 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18160 
18161 	/*
18162 	 * Grab the statistics from the new IP MIB
18163 	 */
18164 	SET_MIB(old_ip_mib.ipInReceives,
18165 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18166 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18167 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18168 	SET_MIB(old_ip_mib.ipForwDatagrams,
18169 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18170 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18171 	    ipmib->ipIfStatsInUnknownProtos);
18172 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18173 	SET_MIB(old_ip_mib.ipInDelivers,
18174 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18175 	SET_MIB(old_ip_mib.ipOutRequests,
18176 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18177 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18178 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18179 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18180 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18181 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18182 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18183 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18184 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18185 
18186 	/* ipRoutingDiscards is not being used */
18187 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18188 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18189 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18190 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18191 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18192 	    ipmib->ipIfStatsReasmDuplicates);
18193 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18194 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18195 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18196 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18197 	SET_MIB(old_ip_mib.rawipInOverflows,
18198 	    ipmib->rawipIfStatsInOverflows);
18199 
18200 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18201 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18202 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18203 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18204 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18205 	    ipmib->ipIfStatsOutSwitchIPVersion);
18206 
18207 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18208 	    (int)sizeof (old_ip_mib))) {
18209 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18210 		    (uint_t)sizeof (old_ip_mib)));
18211 	}
18212 
18213 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18214 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18215 	    (int)optp->level, (int)optp->name, (int)optp->len));
18216 	qreply(q, mpctl);
18217 	return (mp2ctl);
18218 }
18219 
18220 /* Per interface IPv4 statistics */
18221 static mblk_t *
18222 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18223 {
18224 	struct opthdr		*optp;
18225 	mblk_t			*mp2ctl;
18226 	ill_t			*ill;
18227 	ill_walk_context_t	ctx;
18228 	mblk_t			*mp_tail = NULL;
18229 	mib2_ipIfStatsEntry_t	global_ip_mib;
18230 
18231 	/*
18232 	 * Make a copy of the original message
18233 	 */
18234 	mp2ctl = copymsg(mpctl);
18235 
18236 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18237 	optp->level = MIB2_IP;
18238 	optp->name = MIB2_IP_TRAFFIC_STATS;
18239 	/* Include "unknown interface" ip_mib */
18240 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18241 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18242 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18243 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18244 	    (ipst->ips_ip_g_forward ? 1 : 2));
18245 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18246 	    (uint32_t)ipst->ips_ip_def_ttl);
18247 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18248 	    sizeof (mib2_ipIfStatsEntry_t));
18249 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18250 	    sizeof (mib2_ipAddrEntry_t));
18251 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18252 	    sizeof (mib2_ipRouteEntry_t));
18253 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18254 	    sizeof (mib2_ipNetToMediaEntry_t));
18255 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18256 	    sizeof (ip_member_t));
18257 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18258 	    sizeof (ip_grpsrc_t));
18259 
18260 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18261 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18262 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18263 		    "failed to allocate %u bytes\n",
18264 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18265 	}
18266 
18267 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18268 
18269 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18270 	ill = ILL_START_WALK_V4(&ctx, ipst);
18271 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18272 		ill->ill_ip_mib->ipIfStatsIfIndex =
18273 		    ill->ill_phyint->phyint_ifindex;
18274 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18275 		    (ipst->ips_ip_g_forward ? 1 : 2));
18276 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18277 		    (uint32_t)ipst->ips_ip_def_ttl);
18278 
18279 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18280 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18281 		    (char *)ill->ill_ip_mib,
18282 		    (int)sizeof (*ill->ill_ip_mib))) {
18283 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18284 			    "failed to allocate %u bytes\n",
18285 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18286 		}
18287 	}
18288 	rw_exit(&ipst->ips_ill_g_lock);
18289 
18290 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18291 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18292 	    "level %d, name %d, len %d\n",
18293 	    (int)optp->level, (int)optp->name, (int)optp->len));
18294 	qreply(q, mpctl);
18295 
18296 	if (mp2ctl == NULL)
18297 		return (NULL);
18298 
18299 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18300 }
18301 
18302 /* Global IPv4 ICMP statistics */
18303 static mblk_t *
18304 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18305 {
18306 	struct opthdr		*optp;
18307 	mblk_t			*mp2ctl;
18308 
18309 	/*
18310 	 * Make a copy of the original message
18311 	 */
18312 	mp2ctl = copymsg(mpctl);
18313 
18314 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18315 	optp->level = MIB2_ICMP;
18316 	optp->name = 0;
18317 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18318 	    (int)sizeof (ipst->ips_icmp_mib))) {
18319 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18320 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18321 	}
18322 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18323 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18324 	    (int)optp->level, (int)optp->name, (int)optp->len));
18325 	qreply(q, mpctl);
18326 	return (mp2ctl);
18327 }
18328 
18329 /* Global IPv4 IGMP statistics */
18330 static mblk_t *
18331 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18332 {
18333 	struct opthdr		*optp;
18334 	mblk_t			*mp2ctl;
18335 
18336 	/*
18337 	 * make a copy of the original message
18338 	 */
18339 	mp2ctl = copymsg(mpctl);
18340 
18341 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18342 	optp->level = EXPER_IGMP;
18343 	optp->name = 0;
18344 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18345 	    (int)sizeof (ipst->ips_igmpstat))) {
18346 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18347 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18348 	}
18349 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18350 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18351 	    (int)optp->level, (int)optp->name, (int)optp->len));
18352 	qreply(q, mpctl);
18353 	return (mp2ctl);
18354 }
18355 
18356 /* Global IPv4 Multicast Routing statistics */
18357 static mblk_t *
18358 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18359 {
18360 	struct opthdr		*optp;
18361 	mblk_t			*mp2ctl;
18362 
18363 	/*
18364 	 * make a copy of the original message
18365 	 */
18366 	mp2ctl = copymsg(mpctl);
18367 
18368 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18369 	optp->level = EXPER_DVMRP;
18370 	optp->name = 0;
18371 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18372 		ip0dbg(("ip_mroute_stats: failed\n"));
18373 	}
18374 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18375 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18376 	    (int)optp->level, (int)optp->name, (int)optp->len));
18377 	qreply(q, mpctl);
18378 	return (mp2ctl);
18379 }
18380 
18381 /* IPv4 address information */
18382 static mblk_t *
18383 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18384 {
18385 	struct opthdr		*optp;
18386 	mblk_t			*mp2ctl;
18387 	mblk_t			*mp_tail = NULL;
18388 	ill_t			*ill;
18389 	ipif_t			*ipif;
18390 	uint_t			bitval;
18391 	mib2_ipAddrEntry_t	mae;
18392 	zoneid_t		zoneid;
18393 	ill_walk_context_t ctx;
18394 
18395 	/*
18396 	 * make a copy of the original message
18397 	 */
18398 	mp2ctl = copymsg(mpctl);
18399 
18400 	/* ipAddrEntryTable */
18401 
18402 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18403 	optp->level = MIB2_IP;
18404 	optp->name = MIB2_IP_ADDR;
18405 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18406 
18407 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18408 	ill = ILL_START_WALK_V4(&ctx, ipst);
18409 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18410 		for (ipif = ill->ill_ipif; ipif != NULL;
18411 		    ipif = ipif->ipif_next) {
18412 			if (ipif->ipif_zoneid != zoneid &&
18413 			    ipif->ipif_zoneid != ALL_ZONES)
18414 				continue;
18415 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18416 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18417 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18418 
18419 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
18420 			    OCTET_LENGTH);
18421 			mae.ipAdEntIfIndex.o_length =
18422 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18423 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18424 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18425 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18426 			mae.ipAdEntInfo.ae_subnet_len =
18427 			    ip_mask_to_plen(ipif->ipif_net_mask);
18428 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18429 			for (bitval = 1;
18430 			    bitval &&
18431 			    !(bitval & ipif->ipif_brd_addr);
18432 			    bitval <<= 1)
18433 				noop;
18434 			mae.ipAdEntBcastAddr = bitval;
18435 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18436 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18437 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18438 			mae.ipAdEntInfo.ae_broadcast_addr =
18439 			    ipif->ipif_brd_addr;
18440 			mae.ipAdEntInfo.ae_pp_dst_addr =
18441 			    ipif->ipif_pp_dst_addr;
18442 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18443 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18444 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18445 
18446 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18447 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18448 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18449 				    "allocate %u bytes\n",
18450 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18451 			}
18452 		}
18453 	}
18454 	rw_exit(&ipst->ips_ill_g_lock);
18455 
18456 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18457 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18458 	    (int)optp->level, (int)optp->name, (int)optp->len));
18459 	qreply(q, mpctl);
18460 	return (mp2ctl);
18461 }
18462 
18463 /* IPv6 address information */
18464 static mblk_t *
18465 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18466 {
18467 	struct opthdr		*optp;
18468 	mblk_t			*mp2ctl;
18469 	mblk_t			*mp_tail = NULL;
18470 	ill_t			*ill;
18471 	ipif_t			*ipif;
18472 	mib2_ipv6AddrEntry_t	mae6;
18473 	zoneid_t		zoneid;
18474 	ill_walk_context_t	ctx;
18475 
18476 	/*
18477 	 * make a copy of the original message
18478 	 */
18479 	mp2ctl = copymsg(mpctl);
18480 
18481 	/* ipv6AddrEntryTable */
18482 
18483 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18484 	optp->level = MIB2_IP6;
18485 	optp->name = MIB2_IP6_ADDR;
18486 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18487 
18488 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18489 	ill = ILL_START_WALK_V6(&ctx, ipst);
18490 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18491 		for (ipif = ill->ill_ipif; ipif != NULL;
18492 		    ipif = ipif->ipif_next) {
18493 			if (ipif->ipif_zoneid != zoneid &&
18494 			    ipif->ipif_zoneid != ALL_ZONES)
18495 				continue;
18496 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18497 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18498 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18499 
18500 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
18501 			    OCTET_LENGTH);
18502 			mae6.ipv6AddrIfIndex.o_length =
18503 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18504 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18505 			mae6.ipv6AddrPfxLength =
18506 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18507 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18508 			mae6.ipv6AddrInfo.ae_subnet_len =
18509 			    mae6.ipv6AddrPfxLength;
18510 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18511 
18512 			/* Type: stateless(1), stateful(2), unknown(3) */
18513 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18514 				mae6.ipv6AddrType = 1;
18515 			else
18516 				mae6.ipv6AddrType = 2;
18517 			/* Anycast: true(1), false(2) */
18518 			if (ipif->ipif_flags & IPIF_ANYCAST)
18519 				mae6.ipv6AddrAnycastFlag = 1;
18520 			else
18521 				mae6.ipv6AddrAnycastFlag = 2;
18522 
18523 			/*
18524 			 * Address status: preferred(1), deprecated(2),
18525 			 * invalid(3), inaccessible(4), unknown(5)
18526 			 */
18527 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18528 				mae6.ipv6AddrStatus = 3;
18529 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18530 				mae6.ipv6AddrStatus = 2;
18531 			else
18532 				mae6.ipv6AddrStatus = 1;
18533 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18534 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18535 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18536 			    ipif->ipif_v6pp_dst_addr;
18537 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18538 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18539 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18540 			mae6.ipv6AddrIdentifier = ill->ill_token;
18541 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18542 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18543 			mae6.ipv6AddrRetransmitTime =
18544 			    ill->ill_reachable_retrans_time;
18545 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18546 			    (char *)&mae6,
18547 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
18548 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18549 				    "allocate %u bytes\n",
18550 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18551 			}
18552 		}
18553 	}
18554 	rw_exit(&ipst->ips_ill_g_lock);
18555 
18556 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18557 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18558 	    (int)optp->level, (int)optp->name, (int)optp->len));
18559 	qreply(q, mpctl);
18560 	return (mp2ctl);
18561 }
18562 
18563 /* IPv4 multicast group membership. */
18564 static mblk_t *
18565 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18566 {
18567 	struct opthdr		*optp;
18568 	mblk_t			*mp2ctl;
18569 	ill_t			*ill;
18570 	ipif_t			*ipif;
18571 	ilm_t			*ilm;
18572 	ip_member_t		ipm;
18573 	mblk_t			*mp_tail = NULL;
18574 	ill_walk_context_t	ctx;
18575 	zoneid_t		zoneid;
18576 
18577 	/*
18578 	 * make a copy of the original message
18579 	 */
18580 	mp2ctl = copymsg(mpctl);
18581 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18582 
18583 	/* ipGroupMember table */
18584 	optp = (struct opthdr *)&mpctl->b_rptr[
18585 	    sizeof (struct T_optmgmt_ack)];
18586 	optp->level = MIB2_IP;
18587 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18588 
18589 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18590 	ill = ILL_START_WALK_V4(&ctx, ipst);
18591 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18592 		ILM_WALKER_HOLD(ill);
18593 		for (ipif = ill->ill_ipif; ipif != NULL;
18594 		    ipif = ipif->ipif_next) {
18595 			if (ipif->ipif_zoneid != zoneid &&
18596 			    ipif->ipif_zoneid != ALL_ZONES)
18597 				continue;	/* not this zone */
18598 			ipif_get_name(ipif, ipm.ipGroupMemberIfIndex.o_bytes,
18599 			    OCTET_LENGTH);
18600 			ipm.ipGroupMemberIfIndex.o_length =
18601 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18602 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18603 				ASSERT(ilm->ilm_ipif != NULL);
18604 				ASSERT(ilm->ilm_ill == NULL);
18605 				if (ilm->ilm_ipif != ipif)
18606 					continue;
18607 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18608 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18609 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18610 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18611 				    (char *)&ipm, (int)sizeof (ipm))) {
18612 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18613 					    "failed to allocate %u bytes\n",
18614 					    (uint_t)sizeof (ipm)));
18615 				}
18616 			}
18617 		}
18618 		ILM_WALKER_RELE(ill);
18619 	}
18620 	rw_exit(&ipst->ips_ill_g_lock);
18621 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18622 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18623 	    (int)optp->level, (int)optp->name, (int)optp->len));
18624 	qreply(q, mpctl);
18625 	return (mp2ctl);
18626 }
18627 
18628 /* IPv6 multicast group membership. */
18629 static mblk_t *
18630 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18631 {
18632 	struct opthdr		*optp;
18633 	mblk_t			*mp2ctl;
18634 	ill_t			*ill;
18635 	ilm_t			*ilm;
18636 	ipv6_member_t		ipm6;
18637 	mblk_t			*mp_tail = NULL;
18638 	ill_walk_context_t	ctx;
18639 	zoneid_t		zoneid;
18640 
18641 	/*
18642 	 * make a copy of the original message
18643 	 */
18644 	mp2ctl = copymsg(mpctl);
18645 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18646 
18647 	/* ip6GroupMember table */
18648 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18649 	optp->level = MIB2_IP6;
18650 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18651 
18652 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18653 	ill = ILL_START_WALK_V6(&ctx, ipst);
18654 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18655 		ILM_WALKER_HOLD(ill);
18656 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18657 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18658 			ASSERT(ilm->ilm_ipif == NULL);
18659 			ASSERT(ilm->ilm_ill != NULL);
18660 			if (ilm->ilm_zoneid != zoneid)
18661 				continue;	/* not this zone */
18662 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18663 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18664 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18665 			if (!snmp_append_data2(mpctl->b_cont,
18666 			    &mp_tail,
18667 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18668 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18669 				    "failed to allocate %u bytes\n",
18670 				    (uint_t)sizeof (ipm6)));
18671 			}
18672 		}
18673 		ILM_WALKER_RELE(ill);
18674 	}
18675 	rw_exit(&ipst->ips_ill_g_lock);
18676 
18677 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18678 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18679 	    (int)optp->level, (int)optp->name, (int)optp->len));
18680 	qreply(q, mpctl);
18681 	return (mp2ctl);
18682 }
18683 
18684 /* IP multicast filtered sources */
18685 static mblk_t *
18686 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18687 {
18688 	struct opthdr		*optp;
18689 	mblk_t			*mp2ctl;
18690 	ill_t			*ill;
18691 	ipif_t			*ipif;
18692 	ilm_t			*ilm;
18693 	ip_grpsrc_t		ips;
18694 	mblk_t			*mp_tail = NULL;
18695 	ill_walk_context_t	ctx;
18696 	zoneid_t		zoneid;
18697 	int			i;
18698 	slist_t			*sl;
18699 
18700 	/*
18701 	 * make a copy of the original message
18702 	 */
18703 	mp2ctl = copymsg(mpctl);
18704 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18705 
18706 	/* ipGroupSource table */
18707 	optp = (struct opthdr *)&mpctl->b_rptr[
18708 	    sizeof (struct T_optmgmt_ack)];
18709 	optp->level = MIB2_IP;
18710 	optp->name = EXPER_IP_GROUP_SOURCES;
18711 
18712 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18713 	ill = ILL_START_WALK_V4(&ctx, ipst);
18714 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18715 		ILM_WALKER_HOLD(ill);
18716 		for (ipif = ill->ill_ipif; ipif != NULL;
18717 		    ipif = ipif->ipif_next) {
18718 			if (ipif->ipif_zoneid != zoneid)
18719 				continue;	/* not this zone */
18720 			ipif_get_name(ipif, ips.ipGroupSourceIfIndex.o_bytes,
18721 			    OCTET_LENGTH);
18722 			ips.ipGroupSourceIfIndex.o_length =
18723 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18724 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18725 				ASSERT(ilm->ilm_ipif != NULL);
18726 				ASSERT(ilm->ilm_ill == NULL);
18727 				sl = ilm->ilm_filter;
18728 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18729 					continue;
18730 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18731 				for (i = 0; i < sl->sl_numsrc; i++) {
18732 					if (!IN6_IS_ADDR_V4MAPPED(
18733 					    &sl->sl_addr[i]))
18734 						continue;
18735 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18736 					    ips.ipGroupSourceAddress);
18737 					if (snmp_append_data2(mpctl->b_cont,
18738 					    &mp_tail, (char *)&ips,
18739 					    (int)sizeof (ips)) == 0) {
18740 						ip1dbg(("ip_snmp_get_mib2_"
18741 						    "ip_group_src: failed to "
18742 						    "allocate %u bytes\n",
18743 						    (uint_t)sizeof (ips)));
18744 					}
18745 				}
18746 			}
18747 		}
18748 		ILM_WALKER_RELE(ill);
18749 	}
18750 	rw_exit(&ipst->ips_ill_g_lock);
18751 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18752 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18753 	    (int)optp->level, (int)optp->name, (int)optp->len));
18754 	qreply(q, mpctl);
18755 	return (mp2ctl);
18756 }
18757 
18758 /* IPv6 multicast filtered sources. */
18759 static mblk_t *
18760 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18761 {
18762 	struct opthdr		*optp;
18763 	mblk_t			*mp2ctl;
18764 	ill_t			*ill;
18765 	ilm_t			*ilm;
18766 	ipv6_grpsrc_t		ips6;
18767 	mblk_t			*mp_tail = NULL;
18768 	ill_walk_context_t	ctx;
18769 	zoneid_t		zoneid;
18770 	int			i;
18771 	slist_t			*sl;
18772 
18773 	/*
18774 	 * make a copy of the original message
18775 	 */
18776 	mp2ctl = copymsg(mpctl);
18777 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18778 
18779 	/* ip6GroupMember table */
18780 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18781 	optp->level = MIB2_IP6;
18782 	optp->name = EXPER_IP6_GROUP_SOURCES;
18783 
18784 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18785 	ill = ILL_START_WALK_V6(&ctx, ipst);
18786 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18787 		ILM_WALKER_HOLD(ill);
18788 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18789 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18790 			ASSERT(ilm->ilm_ipif == NULL);
18791 			ASSERT(ilm->ilm_ill != NULL);
18792 			sl = ilm->ilm_filter;
18793 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
18794 				continue;
18795 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
18796 			for (i = 0; i < sl->sl_numsrc; i++) {
18797 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
18798 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18799 				    (char *)&ips6, (int)sizeof (ips6))) {
18800 					ip1dbg(("ip_snmp_get_mib2_ip6_"
18801 					    "group_src: failed to allocate "
18802 					    "%u bytes\n",
18803 					    (uint_t)sizeof (ips6)));
18804 				}
18805 			}
18806 		}
18807 		ILM_WALKER_RELE(ill);
18808 	}
18809 	rw_exit(&ipst->ips_ill_g_lock);
18810 
18811 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18812 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18813 	    (int)optp->level, (int)optp->name, (int)optp->len));
18814 	qreply(q, mpctl);
18815 	return (mp2ctl);
18816 }
18817 
18818 /* Multicast routing virtual interface table. */
18819 static mblk_t *
18820 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18821 {
18822 	struct opthdr		*optp;
18823 	mblk_t			*mp2ctl;
18824 
18825 	/*
18826 	 * make a copy of the original message
18827 	 */
18828 	mp2ctl = copymsg(mpctl);
18829 
18830 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18831 	optp->level = EXPER_DVMRP;
18832 	optp->name = EXPER_DVMRP_VIF;
18833 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
18834 		ip0dbg(("ip_mroute_vif: failed\n"));
18835 	}
18836 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18837 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
18838 	    (int)optp->level, (int)optp->name, (int)optp->len));
18839 	qreply(q, mpctl);
18840 	return (mp2ctl);
18841 }
18842 
18843 /* Multicast routing table. */
18844 static mblk_t *
18845 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18846 {
18847 	struct opthdr		*optp;
18848 	mblk_t			*mp2ctl;
18849 
18850 	/*
18851 	 * make a copy of the original message
18852 	 */
18853 	mp2ctl = copymsg(mpctl);
18854 
18855 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18856 	optp->level = EXPER_DVMRP;
18857 	optp->name = EXPER_DVMRP_MRT;
18858 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
18859 		ip0dbg(("ip_mroute_mrt: failed\n"));
18860 	}
18861 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18862 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
18863 	    (int)optp->level, (int)optp->name, (int)optp->len));
18864 	qreply(q, mpctl);
18865 	return (mp2ctl);
18866 }
18867 
18868 /*
18869  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
18870  * in one IRE walk.
18871  */
18872 static mblk_t *
18873 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18874 {
18875 	struct opthdr	*optp;
18876 	mblk_t		*mp2ctl;	/* Returned */
18877 	mblk_t		*mp3ctl;	/* nettomedia */
18878 	mblk_t		*mp4ctl;	/* routeattrs */
18879 	iproutedata_t	ird;
18880 	zoneid_t	zoneid;
18881 
18882 	/*
18883 	 * make copies of the original message
18884 	 *	- mp2ctl is returned unchanged to the caller for his use
18885 	 *	- mpctl is sent upstream as ipRouteEntryTable
18886 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
18887 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
18888 	 */
18889 	mp2ctl = copymsg(mpctl);
18890 	mp3ctl = copymsg(mpctl);
18891 	mp4ctl = copymsg(mpctl);
18892 	if (mp3ctl == NULL || mp4ctl == NULL) {
18893 		freemsg(mp4ctl);
18894 		freemsg(mp3ctl);
18895 		freemsg(mp2ctl);
18896 		freemsg(mpctl);
18897 		return (NULL);
18898 	}
18899 
18900 	bzero(&ird, sizeof (ird));
18901 
18902 	ird.ird_route.lp_head = mpctl->b_cont;
18903 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18904 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18905 
18906 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18907 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
18908 
18909 	/* ipRouteEntryTable in mpctl */
18910 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18911 	optp->level = MIB2_IP;
18912 	optp->name = MIB2_IP_ROUTE;
18913 	optp->len = msgdsize(ird.ird_route.lp_head);
18914 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18915 	    (int)optp->level, (int)optp->name, (int)optp->len));
18916 	qreply(q, mpctl);
18917 
18918 	/* ipNetToMediaEntryTable in mp3ctl */
18919 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18920 	optp->level = MIB2_IP;
18921 	optp->name = MIB2_IP_MEDIA;
18922 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18923 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18924 	    (int)optp->level, (int)optp->name, (int)optp->len));
18925 	qreply(q, mp3ctl);
18926 
18927 	/* ipRouteAttributeTable in mp4ctl */
18928 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18929 	optp->level = MIB2_IP;
18930 	optp->name = EXPER_IP_RTATTR;
18931 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18932 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18933 	    (int)optp->level, (int)optp->name, (int)optp->len));
18934 	if (optp->len == 0)
18935 		freemsg(mp4ctl);
18936 	else
18937 		qreply(q, mp4ctl);
18938 
18939 	return (mp2ctl);
18940 }
18941 
18942 /*
18943  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
18944  * ipv6NetToMediaEntryTable in an NDP walk.
18945  */
18946 static mblk_t *
18947 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18948 {
18949 	struct opthdr	*optp;
18950 	mblk_t		*mp2ctl;	/* Returned */
18951 	mblk_t		*mp3ctl;	/* nettomedia */
18952 	mblk_t		*mp4ctl;	/* routeattrs */
18953 	iproutedata_t	ird;
18954 	zoneid_t	zoneid;
18955 
18956 	/*
18957 	 * make copies of the original message
18958 	 *	- mp2ctl is returned unchanged to the caller for his use
18959 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
18960 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
18961 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
18962 	 */
18963 	mp2ctl = copymsg(mpctl);
18964 	mp3ctl = copymsg(mpctl);
18965 	mp4ctl = copymsg(mpctl);
18966 	if (mp3ctl == NULL || mp4ctl == NULL) {
18967 		freemsg(mp4ctl);
18968 		freemsg(mp3ctl);
18969 		freemsg(mp2ctl);
18970 		freemsg(mpctl);
18971 		return (NULL);
18972 	}
18973 
18974 	bzero(&ird, sizeof (ird));
18975 
18976 	ird.ird_route.lp_head = mpctl->b_cont;
18977 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18978 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18979 
18980 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18981 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
18982 
18983 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18984 	optp->level = MIB2_IP6;
18985 	optp->name = MIB2_IP6_ROUTE;
18986 	optp->len = msgdsize(ird.ird_route.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 	qreply(q, mpctl);
18990 
18991 	/* ipv6NetToMediaEntryTable in mp3ctl */
18992 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
18993 
18994 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18995 	optp->level = MIB2_IP6;
18996 	optp->name = MIB2_IP6_MEDIA;
18997 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18998 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18999 	    (int)optp->level, (int)optp->name, (int)optp->len));
19000 	qreply(q, mp3ctl);
19001 
19002 	/* ipv6RouteAttributeTable in mp4ctl */
19003 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19004 	optp->level = MIB2_IP6;
19005 	optp->name = EXPER_IP_RTATTR;
19006 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19007 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19008 	    (int)optp->level, (int)optp->name, (int)optp->len));
19009 	if (optp->len == 0)
19010 		freemsg(mp4ctl);
19011 	else
19012 		qreply(q, mp4ctl);
19013 
19014 	return (mp2ctl);
19015 }
19016 
19017 /*
19018  * IPv6 mib: One per ill
19019  */
19020 static mblk_t *
19021 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19022 {
19023 	struct opthdr		*optp;
19024 	mblk_t			*mp2ctl;
19025 	ill_t			*ill;
19026 	ill_walk_context_t	ctx;
19027 	mblk_t			*mp_tail = NULL;
19028 
19029 	/*
19030 	 * Make a copy of the original message
19031 	 */
19032 	mp2ctl = copymsg(mpctl);
19033 
19034 	/* fixed length IPv6 structure ... */
19035 
19036 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19037 	optp->level = MIB2_IP6;
19038 	optp->name = 0;
19039 	/* Include "unknown interface" ip6_mib */
19040 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
19041 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
19042 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
19043 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
19044 	    ipst->ips_ipv6_forward ? 1 : 2);
19045 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
19046 	    ipst->ips_ipv6_def_hops);
19047 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
19048 	    sizeof (mib2_ipIfStatsEntry_t));
19049 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
19050 	    sizeof (mib2_ipv6AddrEntry_t));
19051 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
19052 	    sizeof (mib2_ipv6RouteEntry_t));
19053 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
19054 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19055 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
19056 	    sizeof (ipv6_member_t));
19057 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
19058 	    sizeof (ipv6_grpsrc_t));
19059 
19060 	/*
19061 	 * Synchronize 64- and 32-bit counters
19062 	 */
19063 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
19064 	    ipIfStatsHCInReceives);
19065 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
19066 	    ipIfStatsHCInDelivers);
19067 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
19068 	    ipIfStatsHCOutRequests);
19069 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
19070 	    ipIfStatsHCOutForwDatagrams);
19071 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
19072 	    ipIfStatsHCOutMcastPkts);
19073 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19074 	    ipIfStatsHCInMcastPkts);
19075 
19076 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19077 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19078 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19079 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19080 	}
19081 
19082 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19083 	ill = ILL_START_WALK_V6(&ctx, ipst);
19084 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19085 		ill->ill_ip_mib->ipIfStatsIfIndex =
19086 		    ill->ill_phyint->phyint_ifindex;
19087 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19088 		    ipst->ips_ipv6_forward ? 1 : 2);
19089 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19090 		    ill->ill_max_hops);
19091 
19092 		/*
19093 		 * Synchronize 64- and 32-bit counters
19094 		 */
19095 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19096 		    ipIfStatsHCInReceives);
19097 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19098 		    ipIfStatsHCInDelivers);
19099 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19100 		    ipIfStatsHCOutRequests);
19101 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19102 		    ipIfStatsHCOutForwDatagrams);
19103 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19104 		    ipIfStatsHCOutMcastPkts);
19105 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19106 		    ipIfStatsHCInMcastPkts);
19107 
19108 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19109 		    (char *)ill->ill_ip_mib,
19110 		    (int)sizeof (*ill->ill_ip_mib))) {
19111 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19112 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
19113 		}
19114 	}
19115 	rw_exit(&ipst->ips_ill_g_lock);
19116 
19117 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19118 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19119 	    (int)optp->level, (int)optp->name, (int)optp->len));
19120 	qreply(q, mpctl);
19121 	return (mp2ctl);
19122 }
19123 
19124 /*
19125  * ICMPv6 mib: One per ill
19126  */
19127 static mblk_t *
19128 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19129 {
19130 	struct opthdr		*optp;
19131 	mblk_t			*mp2ctl;
19132 	ill_t			*ill;
19133 	ill_walk_context_t	ctx;
19134 	mblk_t			*mp_tail = NULL;
19135 	/*
19136 	 * Make a copy of the original message
19137 	 */
19138 	mp2ctl = copymsg(mpctl);
19139 
19140 	/* fixed length ICMPv6 structure ... */
19141 
19142 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19143 	optp->level = MIB2_ICMP6;
19144 	optp->name = 0;
19145 	/* Include "unknown interface" icmp6_mib */
19146 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19147 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19148 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19149 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19150 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19151 	    (char *)&ipst->ips_icmp6_mib,
19152 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19153 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19154 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19155 	}
19156 
19157 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19158 	ill = ILL_START_WALK_V6(&ctx, ipst);
19159 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19160 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19161 		    ill->ill_phyint->phyint_ifindex;
19162 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19163 		    (char *)ill->ill_icmp6_mib,
19164 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19165 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19166 			    "%u bytes\n",
19167 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19168 		}
19169 	}
19170 	rw_exit(&ipst->ips_ill_g_lock);
19171 
19172 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19173 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19174 	    (int)optp->level, (int)optp->name, (int)optp->len));
19175 	qreply(q, mpctl);
19176 	return (mp2ctl);
19177 }
19178 
19179 /*
19180  * ire_walk routine to create both ipRouteEntryTable and
19181  * ipRouteAttributeTable in one IRE walk
19182  */
19183 static void
19184 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19185 {
19186 	ill_t				*ill;
19187 	ipif_t				*ipif;
19188 	mib2_ipRouteEntry_t		*re;
19189 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19190 	ipaddr_t			gw_addr;
19191 	tsol_ire_gw_secattr_t		*attrp;
19192 	tsol_gc_t			*gc = NULL;
19193 	tsol_gcgrp_t			*gcgrp = NULL;
19194 	uint_t				sacnt = 0;
19195 	int				i;
19196 
19197 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19198 
19199 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19200 		return;
19201 
19202 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19203 		mutex_enter(&attrp->igsa_lock);
19204 		if ((gc = attrp->igsa_gc) != NULL) {
19205 			gcgrp = gc->gc_grp;
19206 			ASSERT(gcgrp != NULL);
19207 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19208 			sacnt = 1;
19209 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19210 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19211 			gc = gcgrp->gcgrp_head;
19212 			sacnt = gcgrp->gcgrp_count;
19213 		}
19214 		mutex_exit(&attrp->igsa_lock);
19215 
19216 		/* do nothing if there's no gc to report */
19217 		if (gc == NULL) {
19218 			ASSERT(sacnt == 0);
19219 			if (gcgrp != NULL) {
19220 				/* we might as well drop the lock now */
19221 				rw_exit(&gcgrp->gcgrp_rwlock);
19222 				gcgrp = NULL;
19223 			}
19224 			attrp = NULL;
19225 		}
19226 
19227 		ASSERT(gc == NULL || (gcgrp != NULL &&
19228 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19229 	}
19230 	ASSERT(sacnt == 0 || gc != NULL);
19231 
19232 	if (sacnt != 0 &&
19233 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19234 		kmem_free(re, sizeof (*re));
19235 		rw_exit(&gcgrp->gcgrp_rwlock);
19236 		return;
19237 	}
19238 
19239 	/*
19240 	 * Return all IRE types for route table... let caller pick and choose
19241 	 */
19242 	re->ipRouteDest = ire->ire_addr;
19243 	ipif = ire->ire_ipif;
19244 	re->ipRouteIfIndex.o_length = 0;
19245 	if (ire->ire_type == IRE_CACHE) {
19246 		ill = (ill_t *)ire->ire_stq->q_ptr;
19247 		re->ipRouteIfIndex.o_length =
19248 		    ill->ill_name_length == 0 ? 0 :
19249 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19250 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19251 		    re->ipRouteIfIndex.o_length);
19252 	} else if (ipif != NULL) {
19253 		ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
19254 		re->ipRouteIfIndex.o_length =
19255 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19256 	}
19257 	re->ipRouteMetric1 = -1;
19258 	re->ipRouteMetric2 = -1;
19259 	re->ipRouteMetric3 = -1;
19260 	re->ipRouteMetric4 = -1;
19261 
19262 	gw_addr = ire->ire_gateway_addr;
19263 
19264 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19265 		re->ipRouteNextHop = ire->ire_src_addr;
19266 	else
19267 		re->ipRouteNextHop = gw_addr;
19268 	/* indirect(4), direct(3), or invalid(2) */
19269 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19270 		re->ipRouteType = 2;
19271 	else
19272 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19273 	re->ipRouteProto = -1;
19274 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19275 	re->ipRouteMask = ire->ire_mask;
19276 	re->ipRouteMetric5 = -1;
19277 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19278 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19279 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19280 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19281 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19282 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19283 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19284 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19285 
19286 	if (ire->ire_flags & RTF_DYNAMIC) {
19287 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19288 	} else {
19289 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19290 	}
19291 
19292 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19293 	    (char *)re, (int)sizeof (*re))) {
19294 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19295 		    (uint_t)sizeof (*re)));
19296 	}
19297 
19298 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19299 		iaeptr->iae_routeidx = ird->ird_idx;
19300 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19301 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19302 	}
19303 
19304 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19305 	    (char *)iae, sacnt * sizeof (*iae))) {
19306 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19307 		    (unsigned)(sacnt * sizeof (*iae))));
19308 	}
19309 
19310 	/* bump route index for next pass */
19311 	ird->ird_idx++;
19312 
19313 	kmem_free(re, sizeof (*re));
19314 	if (sacnt != 0)
19315 		kmem_free(iae, sacnt * sizeof (*iae));
19316 
19317 	if (gcgrp != NULL)
19318 		rw_exit(&gcgrp->gcgrp_rwlock);
19319 }
19320 
19321 /*
19322  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19323  */
19324 static void
19325 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19326 {
19327 	ill_t				*ill;
19328 	ipif_t				*ipif;
19329 	mib2_ipv6RouteEntry_t		*re;
19330 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19331 	in6_addr_t			gw_addr_v6;
19332 	tsol_ire_gw_secattr_t		*attrp;
19333 	tsol_gc_t			*gc = NULL;
19334 	tsol_gcgrp_t			*gcgrp = NULL;
19335 	uint_t				sacnt = 0;
19336 	int				i;
19337 
19338 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19339 
19340 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19341 		return;
19342 
19343 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19344 		mutex_enter(&attrp->igsa_lock);
19345 		if ((gc = attrp->igsa_gc) != NULL) {
19346 			gcgrp = gc->gc_grp;
19347 			ASSERT(gcgrp != NULL);
19348 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19349 			sacnt = 1;
19350 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19351 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19352 			gc = gcgrp->gcgrp_head;
19353 			sacnt = gcgrp->gcgrp_count;
19354 		}
19355 		mutex_exit(&attrp->igsa_lock);
19356 
19357 		/* do nothing if there's no gc to report */
19358 		if (gc == NULL) {
19359 			ASSERT(sacnt == 0);
19360 			if (gcgrp != NULL) {
19361 				/* we might as well drop the lock now */
19362 				rw_exit(&gcgrp->gcgrp_rwlock);
19363 				gcgrp = NULL;
19364 			}
19365 			attrp = NULL;
19366 		}
19367 
19368 		ASSERT(gc == NULL || (gcgrp != NULL &&
19369 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19370 	}
19371 	ASSERT(sacnt == 0 || gc != NULL);
19372 
19373 	if (sacnt != 0 &&
19374 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19375 		kmem_free(re, sizeof (*re));
19376 		rw_exit(&gcgrp->gcgrp_rwlock);
19377 		return;
19378 	}
19379 
19380 	/*
19381 	 * Return all IRE types for route table... let caller pick and choose
19382 	 */
19383 	re->ipv6RouteDest = ire->ire_addr_v6;
19384 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19385 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19386 	re->ipv6RouteIfIndex.o_length = 0;
19387 	ipif = ire->ire_ipif;
19388 	if (ire->ire_type == IRE_CACHE) {
19389 		ill = (ill_t *)ire->ire_stq->q_ptr;
19390 		re->ipv6RouteIfIndex.o_length =
19391 		    ill->ill_name_length == 0 ? 0 :
19392 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19393 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19394 		    re->ipv6RouteIfIndex.o_length);
19395 	} else if (ipif != NULL) {
19396 		ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
19397 		re->ipv6RouteIfIndex.o_length =
19398 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19399 	}
19400 
19401 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19402 
19403 	mutex_enter(&ire->ire_lock);
19404 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19405 	mutex_exit(&ire->ire_lock);
19406 
19407 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19408 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19409 	else
19410 		re->ipv6RouteNextHop = gw_addr_v6;
19411 
19412 	/* remote(4), local(3), or discard(2) */
19413 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19414 		re->ipv6RouteType = 2;
19415 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19416 		re->ipv6RouteType = 3;
19417 	else
19418 		re->ipv6RouteType = 4;
19419 
19420 	re->ipv6RouteProtocol	= -1;
19421 	re->ipv6RoutePolicy	= 0;
19422 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19423 	re->ipv6RouteNextHopRDI	= 0;
19424 	re->ipv6RouteWeight	= 0;
19425 	re->ipv6RouteMetric	= 0;
19426 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19427 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19428 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19429 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19430 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19431 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19432 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19433 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19434 
19435 	if (ire->ire_flags & RTF_DYNAMIC) {
19436 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19437 	} else {
19438 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19439 	}
19440 
19441 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19442 	    (char *)re, (int)sizeof (*re))) {
19443 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19444 		    (uint_t)sizeof (*re)));
19445 	}
19446 
19447 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19448 		iaeptr->iae_routeidx = ird->ird_idx;
19449 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19450 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19451 	}
19452 
19453 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19454 	    (char *)iae, sacnt * sizeof (*iae))) {
19455 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19456 		    (unsigned)(sacnt * sizeof (*iae))));
19457 	}
19458 
19459 	/* bump route index for next pass */
19460 	ird->ird_idx++;
19461 
19462 	kmem_free(re, sizeof (*re));
19463 	if (sacnt != 0)
19464 		kmem_free(iae, sacnt * sizeof (*iae));
19465 
19466 	if (gcgrp != NULL)
19467 		rw_exit(&gcgrp->gcgrp_rwlock);
19468 }
19469 
19470 /*
19471  * ndp_walk routine to create ipv6NetToMediaEntryTable
19472  */
19473 static int
19474 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19475 {
19476 	ill_t				*ill;
19477 	mib2_ipv6NetToMediaEntry_t	ntme;
19478 	dl_unitdata_req_t		*dl;
19479 
19480 	ill = nce->nce_ill;
19481 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19482 		return (0);
19483 
19484 	/*
19485 	 * Neighbor cache entry attached to IRE with on-link
19486 	 * destination.
19487 	 */
19488 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19489 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19490 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19491 	    (nce->nce_res_mp != NULL)) {
19492 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19493 		ntme.ipv6NetToMediaPhysAddress.o_length =
19494 		    dl->dl_dest_addr_length;
19495 	} else {
19496 		ntme.ipv6NetToMediaPhysAddress.o_length =
19497 		    ill->ill_phys_addr_length;
19498 	}
19499 	if (nce->nce_res_mp != NULL) {
19500 		bcopy((char *)nce->nce_res_mp->b_rptr +
19501 		    NCE_LL_ADDR_OFFSET(ill),
19502 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19503 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19504 	} else {
19505 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19506 		    ill->ill_phys_addr_length);
19507 	}
19508 	/*
19509 	 * Note: Returns ND_* states. Should be:
19510 	 * reachable(1), stale(2), delay(3), probe(4),
19511 	 * invalid(5), unknown(6)
19512 	 */
19513 	ntme.ipv6NetToMediaState = nce->nce_state;
19514 	ntme.ipv6NetToMediaLastUpdated = 0;
19515 
19516 	/* other(1), dynamic(2), static(3), local(4) */
19517 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19518 		ntme.ipv6NetToMediaType = 4;
19519 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19520 		ntme.ipv6NetToMediaType = 1;
19521 	} else {
19522 		ntme.ipv6NetToMediaType = 2;
19523 	}
19524 
19525 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19526 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19527 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19528 		    (uint_t)sizeof (ntme)));
19529 	}
19530 	return (0);
19531 }
19532 
19533 /*
19534  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19535  */
19536 /* ARGSUSED */
19537 int
19538 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19539 {
19540 	switch (level) {
19541 	case MIB2_IP:
19542 	case MIB2_ICMP:
19543 		switch (name) {
19544 		default:
19545 			break;
19546 		}
19547 		return (1);
19548 	default:
19549 		return (1);
19550 	}
19551 }
19552 
19553 /*
19554  * When there exists both a 64- and 32-bit counter of a particular type
19555  * (i.e., InReceives), only the 64-bit counters are added.
19556  */
19557 void
19558 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19559 {
19560 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19561 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19562 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19563 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19564 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19565 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19566 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19567 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19568 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19569 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19570 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19571 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19572 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19573 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19574 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
19575 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
19576 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
19577 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
19578 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
19579 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
19580 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
19581 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
19582 	    o2->ipIfStatsInWrongIPVersion);
19583 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
19584 	    o2->ipIfStatsInWrongIPVersion);
19585 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
19586 	    o2->ipIfStatsOutSwitchIPVersion);
19587 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
19588 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
19589 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
19590 	    o2->ipIfStatsHCInForwDatagrams);
19591 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
19592 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
19593 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
19594 	    o2->ipIfStatsHCOutForwDatagrams);
19595 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
19596 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
19597 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
19598 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
19599 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
19600 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
19601 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
19602 	    o2->ipIfStatsHCOutMcastOctets);
19603 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
19604 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
19605 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
19606 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
19607 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
19608 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
19609 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
19610 }
19611 
19612 void
19613 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
19614 {
19615 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
19616 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
19617 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
19618 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
19619 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
19620 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
19621 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
19622 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
19623 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
19624 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
19625 	    o2->ipv6IfIcmpInRouterSolicits);
19626 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
19627 	    o2->ipv6IfIcmpInRouterAdvertisements);
19628 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
19629 	    o2->ipv6IfIcmpInNeighborSolicits);
19630 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
19631 	    o2->ipv6IfIcmpInNeighborAdvertisements);
19632 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
19633 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
19634 	    o2->ipv6IfIcmpInGroupMembQueries);
19635 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
19636 	    o2->ipv6IfIcmpInGroupMembResponses);
19637 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
19638 	    o2->ipv6IfIcmpInGroupMembReductions);
19639 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
19640 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
19641 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
19642 	    o2->ipv6IfIcmpOutDestUnreachs);
19643 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
19644 	    o2->ipv6IfIcmpOutAdminProhibs);
19645 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
19646 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
19647 	    o2->ipv6IfIcmpOutParmProblems);
19648 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
19649 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
19650 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
19651 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
19652 	    o2->ipv6IfIcmpOutRouterSolicits);
19653 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
19654 	    o2->ipv6IfIcmpOutRouterAdvertisements);
19655 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
19656 	    o2->ipv6IfIcmpOutNeighborSolicits);
19657 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
19658 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
19659 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
19660 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
19661 	    o2->ipv6IfIcmpOutGroupMembQueries);
19662 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
19663 	    o2->ipv6IfIcmpOutGroupMembResponses);
19664 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
19665 	    o2->ipv6IfIcmpOutGroupMembReductions);
19666 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
19667 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
19668 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
19669 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
19670 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
19671 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
19672 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
19673 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
19674 	    o2->ipv6IfIcmpInGroupMembTotal);
19675 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
19676 	    o2->ipv6IfIcmpInGroupMembBadQueries);
19677 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
19678 	    o2->ipv6IfIcmpInGroupMembBadReports);
19679 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
19680 	    o2->ipv6IfIcmpInGroupMembOurReports);
19681 }
19682 
19683 /*
19684  * Called before the options are updated to check if this packet will
19685  * be source routed from here.
19686  * This routine assumes that the options are well formed i.e. that they
19687  * have already been checked.
19688  */
19689 static boolean_t
19690 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
19691 {
19692 	ipoptp_t	opts;
19693 	uchar_t		*opt;
19694 	uint8_t		optval;
19695 	uint8_t		optlen;
19696 	ipaddr_t	dst;
19697 	ire_t		*ire;
19698 
19699 	if (IS_SIMPLE_IPH(ipha)) {
19700 		ip2dbg(("not source routed\n"));
19701 		return (B_FALSE);
19702 	}
19703 	dst = ipha->ipha_dst;
19704 	for (optval = ipoptp_first(&opts, ipha);
19705 	    optval != IPOPT_EOL;
19706 	    optval = ipoptp_next(&opts)) {
19707 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19708 		opt = opts.ipoptp_cur;
19709 		optlen = opts.ipoptp_len;
19710 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19711 		    optval, optlen));
19712 		switch (optval) {
19713 			uint32_t off;
19714 		case IPOPT_SSRR:
19715 		case IPOPT_LSRR:
19716 			/*
19717 			 * If dst is one of our addresses and there are some
19718 			 * entries left in the source route return (true).
19719 			 */
19720 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19721 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
19722 			if (ire == NULL) {
19723 				ip2dbg(("ip_source_routed: not next"
19724 				    " source route 0x%x\n",
19725 				    ntohl(dst)));
19726 				return (B_FALSE);
19727 			}
19728 			ire_refrele(ire);
19729 			off = opt[IPOPT_OFFSET];
19730 			off--;
19731 			if (optlen < IP_ADDR_LEN ||
19732 			    off > optlen - IP_ADDR_LEN) {
19733 				/* End of source route */
19734 				ip1dbg(("ip_source_routed: end of SR\n"));
19735 				return (B_FALSE);
19736 			}
19737 			return (B_TRUE);
19738 		}
19739 	}
19740 	ip2dbg(("not source routed\n"));
19741 	return (B_FALSE);
19742 }
19743 
19744 /*
19745  * Check if the packet contains any source route.
19746  */
19747 static boolean_t
19748 ip_source_route_included(ipha_t *ipha)
19749 {
19750 	ipoptp_t	opts;
19751 	uint8_t		optval;
19752 
19753 	if (IS_SIMPLE_IPH(ipha))
19754 		return (B_FALSE);
19755 	for (optval = ipoptp_first(&opts, ipha);
19756 	    optval != IPOPT_EOL;
19757 	    optval = ipoptp_next(&opts)) {
19758 		switch (optval) {
19759 		case IPOPT_SSRR:
19760 		case IPOPT_LSRR:
19761 			return (B_TRUE);
19762 		}
19763 	}
19764 	return (B_FALSE);
19765 }
19766 
19767 /*
19768  * Called when the IRE expiration timer fires.
19769  */
19770 void
19771 ip_trash_timer_expire(void *args)
19772 {
19773 	int			flush_flag = 0;
19774 	ire_expire_arg_t	iea;
19775 	ip_stack_t		*ipst = (ip_stack_t *)args;
19776 
19777 	iea.iea_ipst = ipst;	/* No netstack_hold */
19778 
19779 	/*
19780 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
19781 	 * This lock makes sure that a new invocation of this function
19782 	 * that occurs due to an almost immediate timer firing will not
19783 	 * progress beyond this point until the current invocation is done
19784 	 */
19785 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19786 	ipst->ips_ip_ire_expire_id = 0;
19787 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19788 
19789 	/* Periodic timer */
19790 	if (ipst->ips_ip_ire_arp_time_elapsed >=
19791 	    ipst->ips_ip_ire_arp_interval) {
19792 		/*
19793 		 * Remove all IRE_CACHE entries since they might
19794 		 * contain arp information.
19795 		 */
19796 		flush_flag |= FLUSH_ARP_TIME;
19797 		ipst->ips_ip_ire_arp_time_elapsed = 0;
19798 		IP_STAT(ipst, ip_ire_arp_timer_expired);
19799 	}
19800 	if (ipst->ips_ip_ire_rd_time_elapsed >=
19801 	    ipst->ips_ip_ire_redir_interval) {
19802 		/* Remove all redirects */
19803 		flush_flag |= FLUSH_REDIRECT_TIME;
19804 		ipst->ips_ip_ire_rd_time_elapsed = 0;
19805 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
19806 	}
19807 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
19808 	    ipst->ips_ip_ire_pathmtu_interval) {
19809 		/* Increase path mtu */
19810 		flush_flag |= FLUSH_MTU_TIME;
19811 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
19812 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
19813 	}
19814 
19815 	/*
19816 	 * Optimize for the case when there are no redirects in the
19817 	 * ftable, that is, no need to walk the ftable in that case.
19818 	 */
19819 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
19820 		iea.iea_flush_flag = flush_flag;
19821 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
19822 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
19823 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
19824 		    NULL, ALL_ZONES, ipst);
19825 	}
19826 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
19827 	    ipst->ips_ip_redirect_cnt > 0) {
19828 		iea.iea_flush_flag = flush_flag;
19829 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
19830 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
19831 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
19832 	}
19833 	if (flush_flag & FLUSH_MTU_TIME) {
19834 		/*
19835 		 * Walk all IPv6 IRE's and update them
19836 		 * Note that ARP and redirect timers are not
19837 		 * needed since NUD handles stale entries.
19838 		 */
19839 		flush_flag = FLUSH_MTU_TIME;
19840 		iea.iea_flush_flag = flush_flag;
19841 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
19842 		    ALL_ZONES, ipst);
19843 	}
19844 
19845 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
19846 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
19847 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
19848 
19849 	/*
19850 	 * Hold the lock to serialize timeout calls and prevent
19851 	 * stale values in ip_ire_expire_id. Otherwise it is possible
19852 	 * for the timer to fire and a new invocation of this function
19853 	 * to start before the return value of timeout has been stored
19854 	 * in ip_ire_expire_id by the current invocation.
19855 	 */
19856 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19857 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
19858 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
19859 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19860 }
19861 
19862 /*
19863  * Called by the memory allocator subsystem directly, when the system
19864  * is running low on memory.
19865  */
19866 /* ARGSUSED */
19867 void
19868 ip_trash_ire_reclaim(void *args)
19869 {
19870 	netstack_handle_t nh;
19871 	netstack_t *ns;
19872 
19873 	netstack_next_init(&nh);
19874 	while ((ns = netstack_next(&nh)) != NULL) {
19875 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
19876 		netstack_rele(ns);
19877 	}
19878 	netstack_next_fini(&nh);
19879 }
19880 
19881 static void
19882 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
19883 {
19884 	ire_cache_count_t icc;
19885 	ire_cache_reclaim_t icr;
19886 	ncc_cache_count_t ncc;
19887 	nce_cache_reclaim_t ncr;
19888 	uint_t delete_cnt;
19889 	/*
19890 	 * Memory reclaim call back.
19891 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
19892 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
19893 	 * entries, determine what fraction to free for
19894 	 * each category of IRE_CACHE entries giving absolute priority
19895 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
19896 	 * entry will be freed unless all offlink entries are freed).
19897 	 */
19898 	icc.icc_total = 0;
19899 	icc.icc_unused = 0;
19900 	icc.icc_offlink = 0;
19901 	icc.icc_pmtu = 0;
19902 	icc.icc_onlink = 0;
19903 	ire_walk(ire_cache_count, (char *)&icc, ipst);
19904 
19905 	/*
19906 	 * Free NCEs for IPv6 like the onlink ires.
19907 	 */
19908 	ncc.ncc_total = 0;
19909 	ncc.ncc_host = 0;
19910 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
19911 
19912 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
19913 	    icc.icc_pmtu + icc.icc_onlink);
19914 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
19915 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
19916 	if (delete_cnt == 0)
19917 		return;
19918 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
19919 	/* Always delete all unused offlink entries */
19920 	icr.icr_ipst = ipst;
19921 	icr.icr_unused = 1;
19922 	if (delete_cnt <= icc.icc_unused) {
19923 		/*
19924 		 * Only need to free unused entries.  In other words,
19925 		 * there are enough unused entries to free to meet our
19926 		 * target number of freed ire cache entries.
19927 		 */
19928 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
19929 		ncr.ncr_host = 0;
19930 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
19931 		/*
19932 		 * Only need to free unused entries, plus a fraction of offlink
19933 		 * entries.  It follows from the first if statement that
19934 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
19935 		 */
19936 		delete_cnt -= icc.icc_unused;
19937 		/* Round up # deleted by truncating fraction */
19938 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
19939 		icr.icr_pmtu = icr.icr_onlink = 0;
19940 		ncr.ncr_host = 0;
19941 	} else if (delete_cnt <=
19942 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
19943 		/*
19944 		 * Free all unused and offlink entries, plus a fraction of
19945 		 * pmtu entries.  It follows from the previous if statement
19946 		 * that icc_pmtu is non-zero, and that
19947 		 * delete_cnt != icc_unused + icc_offlink.
19948 		 */
19949 		icr.icr_offlink = 1;
19950 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
19951 		/* Round up # deleted by truncating fraction */
19952 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
19953 		icr.icr_onlink = 0;
19954 		ncr.ncr_host = 0;
19955 	} else {
19956 		/*
19957 		 * Free all unused, offlink, and pmtu entries, plus a fraction
19958 		 * of onlink entries.  If we're here, then we know that
19959 		 * icc_onlink is non-zero, and that
19960 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
19961 		 */
19962 		icr.icr_offlink = icr.icr_pmtu = 1;
19963 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
19964 		    icc.icc_pmtu;
19965 		/* Round up # deleted by truncating fraction */
19966 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
19967 		/* Using the same delete fraction as for onlink IREs */
19968 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
19969 	}
19970 #ifdef DEBUG
19971 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
19972 	    "fractions %d/%d/%d/%d\n",
19973 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
19974 	    icc.icc_unused, icc.icc_offlink,
19975 	    icc.icc_pmtu, icc.icc_onlink,
19976 	    icr.icr_unused, icr.icr_offlink,
19977 	    icr.icr_pmtu, icr.icr_onlink));
19978 #endif
19979 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
19980 	if (ncr.ncr_host != 0)
19981 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
19982 		    (uchar_t *)&ncr, ipst);
19983 #ifdef DEBUG
19984 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
19985 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
19986 	ire_walk(ire_cache_count, (char *)&icc, ipst);
19987 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
19988 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
19989 	    icc.icc_pmtu, icc.icc_onlink));
19990 #endif
19991 }
19992 
19993 /*
19994  * ip_unbind is called when a copy of an unbind request is received from the
19995  * upper level protocol.  We remove this conn from any fanout hash list it is
19996  * on, and zero out the bind information.  No reply is expected up above.
19997  */
19998 mblk_t *
19999 ip_unbind(queue_t *q, mblk_t *mp)
20000 {
20001 	conn_t	*connp = Q_TO_CONN(q);
20002 
20003 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
20004 
20005 	if (is_system_labeled() && connp->conn_anon_port) {
20006 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
20007 		    connp->conn_mlp_type, connp->conn_ulp,
20008 		    ntohs(connp->conn_lport), B_FALSE);
20009 		connp->conn_anon_port = 0;
20010 	}
20011 	connp->conn_mlp_type = mlptSingle;
20012 
20013 	ipcl_hash_remove(connp);
20014 
20015 	ASSERT(mp->b_cont == NULL);
20016 	/*
20017 	 * Convert mp into a T_OK_ACK
20018 	 */
20019 	mp = mi_tpi_ok_ack_alloc(mp);
20020 
20021 	/*
20022 	 * should not happen in practice... T_OK_ACK is smaller than the
20023 	 * original message.
20024 	 */
20025 	if (mp == NULL)
20026 		return (NULL);
20027 
20028 	return (mp);
20029 }
20030 
20031 /*
20032  * Write side put procedure.  Outbound data, IOCTLs, responses from
20033  * resolvers, etc, come down through here.
20034  *
20035  * arg2 is always a queue_t *.
20036  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
20037  * the zoneid.
20038  * When that queue is not an ill_t, then arg must be a conn_t pointer.
20039  */
20040 void
20041 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
20042 {
20043 	ip_output_options(arg, mp, arg2, caller, &zero_info);
20044 }
20045 
20046 void
20047 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20048     ip_opt_info_t *infop)
20049 {
20050 	conn_t		*connp = NULL;
20051 	queue_t		*q = (queue_t *)arg2;
20052 	ipha_t		*ipha;
20053 #define	rptr	((uchar_t *)ipha)
20054 	ire_t		*ire = NULL;
20055 	ire_t		*sctp_ire = NULL;
20056 	uint32_t	v_hlen_tos_len;
20057 	ipaddr_t	dst;
20058 	mblk_t		*first_mp = NULL;
20059 	boolean_t	mctl_present;
20060 	ipsec_out_t	*io;
20061 	int		match_flags;
20062 	ill_t		*attach_ill = NULL;
20063 					/* Bind to IPIF_NOFAILOVER ill etc. */
20064 	ill_t		*xmit_ill = NULL;	/* IP_PKTINFO etc. */
20065 	ipif_t		*dst_ipif;
20066 	boolean_t	multirt_need_resolve = B_FALSE;
20067 	mblk_t		*copy_mp = NULL;
20068 	int		err;
20069 	zoneid_t	zoneid;
20070 	int	adjust;
20071 	uint16_t iplen;
20072 	boolean_t	need_decref = B_FALSE;
20073 	boolean_t	ignore_dontroute = B_FALSE;
20074 	boolean_t	ignore_nexthop = B_FALSE;
20075 	boolean_t	ip_nexthop = B_FALSE;
20076 	ipaddr_t	nexthop_addr;
20077 	ip_stack_t	*ipst;
20078 
20079 #ifdef	_BIG_ENDIAN
20080 #define	V_HLEN	(v_hlen_tos_len >> 24)
20081 #else
20082 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20083 #endif
20084 
20085 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20086 	    "ip_wput_start: q %p", q);
20087 
20088 	/*
20089 	 * ip_wput fast path
20090 	 */
20091 
20092 	/* is packet from ARP ? */
20093 	if (q->q_next != NULL) {
20094 		zoneid = (zoneid_t)(uintptr_t)arg;
20095 		goto qnext;
20096 	}
20097 
20098 	connp = (conn_t *)arg;
20099 	ASSERT(connp != NULL);
20100 	zoneid = connp->conn_zoneid;
20101 	ipst = connp->conn_netstack->netstack_ip;
20102 
20103 	/* is queue flow controlled? */
20104 	if ((q->q_first != NULL || connp->conn_draining) &&
20105 	    (caller == IP_WPUT)) {
20106 		ASSERT(!need_decref);
20107 		(void) putq(q, mp);
20108 		return;
20109 	}
20110 
20111 	/* Multidata transmit? */
20112 	if (DB_TYPE(mp) == M_MULTIDATA) {
20113 		/*
20114 		 * We should never get here, since all Multidata messages
20115 		 * originating from tcp should have been directed over to
20116 		 * tcp_multisend() in the first place.
20117 		 */
20118 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20119 		freemsg(mp);
20120 		return;
20121 	} else if (DB_TYPE(mp) != M_DATA)
20122 		goto notdata;
20123 
20124 	if (mp->b_flag & MSGHASREF) {
20125 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20126 		mp->b_flag &= ~MSGHASREF;
20127 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20128 		need_decref = B_TRUE;
20129 	}
20130 	ipha = (ipha_t *)mp->b_rptr;
20131 
20132 	/* is IP header non-aligned or mblk smaller than basic IP header */
20133 #ifndef SAFETY_BEFORE_SPEED
20134 	if (!OK_32PTR(rptr) ||
20135 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20136 		goto hdrtoosmall;
20137 #endif
20138 
20139 	ASSERT(OK_32PTR(ipha));
20140 
20141 	/*
20142 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20143 	 * wrong version, we'll catch it again in ip_output_v6.
20144 	 *
20145 	 * Note that this is *only* locally-generated output here, and never
20146 	 * forwarded data, and that we need to deal only with transports that
20147 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20148 	 * label.)
20149 	 */
20150 	if (is_system_labeled() &&
20151 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20152 	    !connp->conn_ulp_labeled) {
20153 		err = tsol_check_label(BEST_CRED(mp, connp), &mp, &adjust,
20154 		    connp->conn_mac_exempt, ipst);
20155 		ipha = (ipha_t *)mp->b_rptr;
20156 		if (err != 0) {
20157 			first_mp = mp;
20158 			if (err == EINVAL)
20159 				goto icmp_parameter_problem;
20160 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20161 			goto discard_pkt;
20162 		}
20163 		iplen = ntohs(ipha->ipha_length) + adjust;
20164 		ipha->ipha_length = htons(iplen);
20165 	}
20166 
20167 	ASSERT(infop != NULL);
20168 
20169 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20170 		/*
20171 		 * IP_PKTINFO ancillary option is present.
20172 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20173 		 * allows using address of any zone as the source address.
20174 		 */
20175 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20176 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20177 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20178 		if (ire == NULL)
20179 			goto drop_pkt;
20180 		ire_refrele(ire);
20181 		ire = NULL;
20182 	}
20183 
20184 	/*
20185 	 * IP_DONTFAILOVER_IF and IP_BOUND_IF have precedence over ill index
20186 	 * passed in IP_PKTINFO.
20187 	 */
20188 	if (infop->ip_opt_ill_index != 0 &&
20189 	    connp->conn_outgoing_ill == NULL &&
20190 	    connp->conn_nofailover_ill == NULL) {
20191 
20192 		xmit_ill = ill_lookup_on_ifindex(
20193 		    infop->ip_opt_ill_index, B_FALSE, NULL, NULL, NULL, NULL,
20194 		    ipst);
20195 
20196 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20197 			goto drop_pkt;
20198 		/*
20199 		 * check that there is an ipif belonging
20200 		 * to our zone. IPCL_ZONEID is not used because
20201 		 * IP_ALLZONES option is valid only when the ill is
20202 		 * accessible from all zones i.e has a valid ipif in
20203 		 * all zones.
20204 		 */
20205 		if (!ipif_lookup_zoneid_group(xmit_ill, zoneid, 0, NULL)) {
20206 			goto drop_pkt;
20207 		}
20208 	}
20209 
20210 	/*
20211 	 * If there is a policy, try to attach an ipsec_out in
20212 	 * the front. At the end, first_mp either points to a
20213 	 * M_DATA message or IPSEC_OUT message linked to a
20214 	 * M_DATA message. We have to do it now as we might
20215 	 * lose the "conn" if we go through ip_newroute.
20216 	 */
20217 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20218 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
20219 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20220 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20221 			if (need_decref)
20222 				CONN_DEC_REF(connp);
20223 			return;
20224 		} else {
20225 			ASSERT(mp->b_datap->db_type == M_CTL);
20226 			first_mp = mp;
20227 			mp = mp->b_cont;
20228 			mctl_present = B_TRUE;
20229 		}
20230 	} else {
20231 		first_mp = mp;
20232 		mctl_present = B_FALSE;
20233 	}
20234 
20235 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20236 
20237 	/* is wrong version or IP options present */
20238 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20239 		goto version_hdrlen_check;
20240 	dst = ipha->ipha_dst;
20241 
20242 	if (connp->conn_nofailover_ill != NULL) {
20243 		attach_ill = conn_get_held_ill(connp,
20244 		    &connp->conn_nofailover_ill, &err);
20245 		if (err == ILL_LOOKUP_FAILED) {
20246 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20247 			if (need_decref)
20248 				CONN_DEC_REF(connp);
20249 			freemsg(first_mp);
20250 			return;
20251 		}
20252 	}
20253 
20254 	/* If IP_BOUND_IF has been set, use that ill. */
20255 	if (connp->conn_outgoing_ill != NULL) {
20256 		xmit_ill = conn_get_held_ill(connp,
20257 		    &connp->conn_outgoing_ill, &err);
20258 		if (err == ILL_LOOKUP_FAILED)
20259 			goto drop_pkt;
20260 
20261 		goto send_from_ill;
20262 	}
20263 
20264 	/* is packet multicast? */
20265 	if (CLASSD(dst))
20266 		goto multicast;
20267 
20268 	/*
20269 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20270 	 * takes precedence over conn_dontroute and conn_nexthop_set
20271 	 */
20272 	if (xmit_ill != NULL)
20273 		goto send_from_ill;
20274 
20275 	if (connp->conn_dontroute || connp->conn_nexthop_set) {
20276 		/*
20277 		 * If the destination is a broadcast, local, or loopback
20278 		 * address, SO_DONTROUTE and IP_NEXTHOP go through the
20279 		 * standard path.
20280 		 */
20281 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20282 		if ((ire == NULL) || (ire->ire_type &
20283 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK)) == 0) {
20284 			if (ire != NULL) {
20285 				ire_refrele(ire);
20286 				/* No more access to ire */
20287 				ire = NULL;
20288 			}
20289 			/*
20290 			 * bypass routing checks and go directly to interface.
20291 			 */
20292 			if (connp->conn_dontroute)
20293 				goto dontroute;
20294 
20295 			ASSERT(connp->conn_nexthop_set);
20296 			ip_nexthop = B_TRUE;
20297 			nexthop_addr = connp->conn_nexthop_v4;
20298 			goto send_from_ill;
20299 		}
20300 
20301 		/* Must be a broadcast, a loopback or a local ire */
20302 		ire_refrele(ire);
20303 		/* No more access to ire */
20304 		ire = NULL;
20305 	}
20306 
20307 	if (attach_ill != NULL)
20308 		goto send_from_ill;
20309 
20310 	/*
20311 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20312 	 * this for the tcp global queue and listen end point
20313 	 * as it does not really have a real destination to
20314 	 * talk to.  This is also true for SCTP.
20315 	 */
20316 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20317 	    !connp->conn_fully_bound) {
20318 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20319 		if (ire == NULL)
20320 			goto noirefound;
20321 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20322 		    "ip_wput_end: q %p (%S)", q, "end");
20323 
20324 		/*
20325 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20326 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20327 		 */
20328 		if (ire->ire_flags & RTF_MULTIRT) {
20329 
20330 			/*
20331 			 * Force the TTL of multirouted packets if required.
20332 			 * The TTL of such packets is bounded by the
20333 			 * ip_multirt_ttl ndd variable.
20334 			 */
20335 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20336 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20337 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20338 				    "(was %d), dst 0x%08x\n",
20339 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20340 				    ntohl(ire->ire_addr)));
20341 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20342 			}
20343 			/*
20344 			 * We look at this point if there are pending
20345 			 * unresolved routes. ire_multirt_resolvable()
20346 			 * checks in O(n) that all IRE_OFFSUBNET ire
20347 			 * entries for the packet's destination and
20348 			 * flagged RTF_MULTIRT are currently resolved.
20349 			 * If some remain unresolved, we make a copy
20350 			 * of the current message. It will be used
20351 			 * to initiate additional route resolutions.
20352 			 */
20353 			multirt_need_resolve =
20354 			    ire_multirt_need_resolve(ire->ire_addr,
20355 			    MBLK_GETLABEL(first_mp), ipst);
20356 			ip2dbg(("ip_wput[TCP]: ire %p, "
20357 			    "multirt_need_resolve %d, first_mp %p\n",
20358 			    (void *)ire, multirt_need_resolve,
20359 			    (void *)first_mp));
20360 			if (multirt_need_resolve) {
20361 				copy_mp = copymsg(first_mp);
20362 				if (copy_mp != NULL) {
20363 					MULTIRT_DEBUG_TAG(copy_mp);
20364 				}
20365 			}
20366 		}
20367 
20368 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20369 
20370 		/*
20371 		 * Try to resolve another multiroute if
20372 		 * ire_multirt_need_resolve() deemed it necessary.
20373 		 */
20374 		if (copy_mp != NULL)
20375 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20376 		if (need_decref)
20377 			CONN_DEC_REF(connp);
20378 		return;
20379 	}
20380 
20381 	/*
20382 	 * Access to conn_ire_cache. (protected by conn_lock)
20383 	 *
20384 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20385 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20386 	 * send a packet or two with the IRE_CACHE that is going away.
20387 	 * Access to the ire requires an ire refhold on the ire prior to
20388 	 * its use since an interface unplumb thread may delete the cached
20389 	 * ire and release the refhold at any time.
20390 	 *
20391 	 * Caching an ire in the conn_ire_cache
20392 	 *
20393 	 * o Caching an ire pointer in the conn requires a strict check for
20394 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20395 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20396 	 * in the conn is done after making sure under the bucket lock that the
20397 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20398 	 * caching an ire after the unplumb thread has cleaned up the conn.
20399 	 * If the conn does not send a packet subsequently the unplumb thread
20400 	 * will be hanging waiting for the ire count to drop to zero.
20401 	 *
20402 	 * o We also need to atomically test for a null conn_ire_cache and
20403 	 * set the conn_ire_cache under the the protection of the conn_lock
20404 	 * to avoid races among concurrent threads trying to simultaneously
20405 	 * cache an ire in the conn_ire_cache.
20406 	 */
20407 	mutex_enter(&connp->conn_lock);
20408 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20409 
20410 	if (ire != NULL && ire->ire_addr == dst &&
20411 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20412 
20413 		IRE_REFHOLD(ire);
20414 		mutex_exit(&connp->conn_lock);
20415 
20416 	} else {
20417 		boolean_t cached = B_FALSE;
20418 		connp->conn_ire_cache = NULL;
20419 		mutex_exit(&connp->conn_lock);
20420 		/* Release the old ire */
20421 		if (ire != NULL && sctp_ire == NULL)
20422 			IRE_REFRELE_NOTR(ire);
20423 
20424 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20425 		if (ire == NULL)
20426 			goto noirefound;
20427 		IRE_REFHOLD_NOTR(ire);
20428 
20429 		mutex_enter(&connp->conn_lock);
20430 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20431 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20432 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20433 				if (connp->conn_ulp == IPPROTO_TCP)
20434 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20435 				connp->conn_ire_cache = ire;
20436 				cached = B_TRUE;
20437 			}
20438 			rw_exit(&ire->ire_bucket->irb_lock);
20439 		}
20440 		mutex_exit(&connp->conn_lock);
20441 
20442 		/*
20443 		 * We can continue to use the ire but since it was
20444 		 * not cached, we should drop the extra reference.
20445 		 */
20446 		if (!cached)
20447 			IRE_REFRELE_NOTR(ire);
20448 	}
20449 
20450 
20451 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20452 	    "ip_wput_end: q %p (%S)", q, "end");
20453 
20454 	/*
20455 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20456 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20457 	 */
20458 	if (ire->ire_flags & RTF_MULTIRT) {
20459 
20460 		/*
20461 		 * Force the TTL of multirouted packets if required.
20462 		 * The TTL of such packets is bounded by the
20463 		 * ip_multirt_ttl ndd variable.
20464 		 */
20465 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20466 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20467 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20468 			    "(was %d), dst 0x%08x\n",
20469 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20470 			    ntohl(ire->ire_addr)));
20471 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20472 		}
20473 
20474 		/*
20475 		 * At this point, we check to see if there are any pending
20476 		 * unresolved routes. ire_multirt_resolvable()
20477 		 * checks in O(n) that all IRE_OFFSUBNET ire
20478 		 * entries for the packet's destination and
20479 		 * flagged RTF_MULTIRT are currently resolved.
20480 		 * If some remain unresolved, we make a copy
20481 		 * of the current message. It will be used
20482 		 * to initiate additional route resolutions.
20483 		 */
20484 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20485 		    MBLK_GETLABEL(first_mp), ipst);
20486 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20487 		    "multirt_need_resolve %d, first_mp %p\n",
20488 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20489 		if (multirt_need_resolve) {
20490 			copy_mp = copymsg(first_mp);
20491 			if (copy_mp != NULL) {
20492 				MULTIRT_DEBUG_TAG(copy_mp);
20493 			}
20494 		}
20495 	}
20496 
20497 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20498 
20499 	/*
20500 	 * Try to resolve another multiroute if
20501 	 * ire_multirt_resolvable() deemed it necessary
20502 	 */
20503 	if (copy_mp != NULL)
20504 		ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20505 	if (need_decref)
20506 		CONN_DEC_REF(connp);
20507 	return;
20508 
20509 qnext:
20510 	/*
20511 	 * Upper Level Protocols pass down complete IP datagrams
20512 	 * as M_DATA messages.	Everything else is a sideshow.
20513 	 *
20514 	 * 1) We could be re-entering ip_wput because of ip_neworute
20515 	 *    in which case we could have a IPSEC_OUT message. We
20516 	 *    need to pass through ip_wput like other datagrams and
20517 	 *    hence cannot branch to ip_wput_nondata.
20518 	 *
20519 	 * 2) ARP, AH, ESP, and other clients who are on the module
20520 	 *    instance of IP stream, give us something to deal with.
20521 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20522 	 *
20523 	 * 3) ICMP replies also could come here.
20524 	 */
20525 	ipst = ILLQ_TO_IPST(q);
20526 
20527 	if (DB_TYPE(mp) != M_DATA) {
20528 notdata:
20529 		if (DB_TYPE(mp) == M_CTL) {
20530 			/*
20531 			 * M_CTL messages are used by ARP, AH and ESP to
20532 			 * communicate with IP. We deal with IPSEC_IN and
20533 			 * IPSEC_OUT here. ip_wput_nondata handles other
20534 			 * cases.
20535 			 */
20536 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20537 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20538 				first_mp = mp->b_cont;
20539 				first_mp->b_flag &= ~MSGHASREF;
20540 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20541 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20542 				CONN_DEC_REF(connp);
20543 				connp = NULL;
20544 			}
20545 			if (ii->ipsec_info_type == IPSEC_IN) {
20546 				/*
20547 				 * Either this message goes back to
20548 				 * IPsec for further processing or to
20549 				 * ULP after policy checks.
20550 				 */
20551 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20552 				return;
20553 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20554 				io = (ipsec_out_t *)ii;
20555 				if (io->ipsec_out_proc_begin) {
20556 					/*
20557 					 * IPsec processing has already started.
20558 					 * Complete it.
20559 					 * IPQoS notes: We don't care what is
20560 					 * in ipsec_out_ill_index since this
20561 					 * won't be processed for IPQoS policies
20562 					 * in ipsec_out_process.
20563 					 */
20564 					ipsec_out_process(q, mp, NULL,
20565 					    io->ipsec_out_ill_index);
20566 					return;
20567 				} else {
20568 					connp = (q->q_next != NULL) ?
20569 					    NULL : Q_TO_CONN(q);
20570 					first_mp = mp;
20571 					mp = mp->b_cont;
20572 					mctl_present = B_TRUE;
20573 				}
20574 				zoneid = io->ipsec_out_zoneid;
20575 				ASSERT(zoneid != ALL_ZONES);
20576 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20577 				/*
20578 				 * It's an IPsec control message requesting
20579 				 * an SADB update to be sent to the IPsec
20580 				 * hardware acceleration capable ills.
20581 				 */
20582 				ipsec_ctl_t *ipsec_ctl =
20583 				    (ipsec_ctl_t *)mp->b_rptr;
20584 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20585 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20586 				mblk_t *cmp = mp->b_cont;
20587 
20588 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20589 				ASSERT(cmp != NULL);
20590 
20591 				freeb(mp);
20592 				ill_ipsec_capab_send_all(satype, cmp, sa,
20593 				    ipst->ips_netstack);
20594 				return;
20595 			} else {
20596 				/*
20597 				 * This must be ARP or special TSOL signaling.
20598 				 */
20599 				ip_wput_nondata(NULL, q, mp, NULL);
20600 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20601 				    "ip_wput_end: q %p (%S)", q, "nondata");
20602 				return;
20603 			}
20604 		} else {
20605 			/*
20606 			 * This must be non-(ARP/AH/ESP) messages.
20607 			 */
20608 			ASSERT(!need_decref);
20609 			ip_wput_nondata(NULL, q, mp, NULL);
20610 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20611 			    "ip_wput_end: q %p (%S)", q, "nondata");
20612 			return;
20613 		}
20614 	} else {
20615 		first_mp = mp;
20616 		mctl_present = B_FALSE;
20617 	}
20618 
20619 	ASSERT(first_mp != NULL);
20620 	/*
20621 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
20622 	 * to make sure that this packet goes out on the same interface it
20623 	 * came in. We handle that here.
20624 	 */
20625 	if (mctl_present) {
20626 		uint_t ifindex;
20627 
20628 		io = (ipsec_out_t *)first_mp->b_rptr;
20629 		if (io->ipsec_out_attach_if || io->ipsec_out_ip_nexthop) {
20630 			/*
20631 			 * We may have lost the conn context if we are
20632 			 * coming here from ip_newroute(). Copy the
20633 			 * nexthop information.
20634 			 */
20635 			if (io->ipsec_out_ip_nexthop) {
20636 				ip_nexthop = B_TRUE;
20637 				nexthop_addr = io->ipsec_out_nexthop_addr;
20638 
20639 				ipha = (ipha_t *)mp->b_rptr;
20640 				dst = ipha->ipha_dst;
20641 				goto send_from_ill;
20642 			} else {
20643 				ASSERT(io->ipsec_out_ill_index != 0);
20644 				ifindex = io->ipsec_out_ill_index;
20645 				attach_ill = ill_lookup_on_ifindex(ifindex,
20646 				    B_FALSE, NULL, NULL, NULL, NULL, ipst);
20647 				if (attach_ill == NULL) {
20648 					ASSERT(xmit_ill == NULL);
20649 					ip1dbg(("ip_output: bad ifindex for "
20650 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
20651 					    ifindex));
20652 					freemsg(first_mp);
20653 					BUMP_MIB(&ipst->ips_ip_mib,
20654 					    ipIfStatsOutDiscards);
20655 					ASSERT(!need_decref);
20656 					return;
20657 				}
20658 			}
20659 		}
20660 	}
20661 
20662 	ASSERT(xmit_ill == NULL);
20663 
20664 	/* We have a complete IP datagram heading outbound. */
20665 	ipha = (ipha_t *)mp->b_rptr;
20666 
20667 #ifndef SPEED_BEFORE_SAFETY
20668 	/*
20669 	 * Make sure we have a full-word aligned message and that at least
20670 	 * a simple IP header is accessible in the first message.  If not,
20671 	 * try a pullup.
20672 	 */
20673 	if (!OK_32PTR(rptr) ||
20674 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
20675 hdrtoosmall:
20676 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20677 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20678 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20679 			if (first_mp == NULL)
20680 				first_mp = mp;
20681 			goto discard_pkt;
20682 		}
20683 
20684 		/* This function assumes that mp points to an IPv4 packet. */
20685 		if (is_system_labeled() && q->q_next == NULL &&
20686 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20687 		    !connp->conn_ulp_labeled) {
20688 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20689 			    &adjust, connp->conn_mac_exempt, ipst);
20690 			ipha = (ipha_t *)mp->b_rptr;
20691 			if (first_mp != NULL)
20692 				first_mp->b_cont = mp;
20693 			if (err != 0) {
20694 				if (first_mp == NULL)
20695 					first_mp = mp;
20696 				if (err == EINVAL)
20697 					goto icmp_parameter_problem;
20698 				ip2dbg(("ip_wput: label check failed (%d)\n",
20699 				    err));
20700 				goto discard_pkt;
20701 			}
20702 			iplen = ntohs(ipha->ipha_length) + adjust;
20703 			ipha->ipha_length = htons(iplen);
20704 		}
20705 
20706 		ipha = (ipha_t *)mp->b_rptr;
20707 		if (first_mp == NULL) {
20708 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
20709 			/*
20710 			 * If we got here because of "goto hdrtoosmall"
20711 			 * We need to attach a IPSEC_OUT.
20712 			 */
20713 			if (connp->conn_out_enforce_policy) {
20714 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
20715 				    NULL, ipha->ipha_protocol,
20716 				    ipst->ips_netstack)) == NULL)) {
20717 					BUMP_MIB(&ipst->ips_ip_mib,
20718 					    ipIfStatsOutDiscards);
20719 					if (need_decref)
20720 						CONN_DEC_REF(connp);
20721 					return;
20722 				} else {
20723 					ASSERT(mp->b_datap->db_type == M_CTL);
20724 					first_mp = mp;
20725 					mp = mp->b_cont;
20726 					mctl_present = B_TRUE;
20727 				}
20728 			} else {
20729 				first_mp = mp;
20730 				mctl_present = B_FALSE;
20731 			}
20732 		}
20733 	}
20734 #endif
20735 
20736 	/* Most of the code below is written for speed, not readability */
20737 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20738 
20739 	/*
20740 	 * If ip_newroute() fails, we're going to need a full
20741 	 * header for the icmp wraparound.
20742 	 */
20743 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
20744 		uint_t	v_hlen;
20745 version_hdrlen_check:
20746 		ASSERT(first_mp != NULL);
20747 		v_hlen = V_HLEN;
20748 		/*
20749 		 * siphon off IPv6 packets coming down from transport
20750 		 * layer modules here.
20751 		 * Note: high-order bit carries NUD reachability confirmation
20752 		 */
20753 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
20754 			/*
20755 			 * FIXME: assume that callers of ip_output* call
20756 			 * the right version?
20757 			 */
20758 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
20759 			ASSERT(xmit_ill == NULL);
20760 			if (attach_ill != NULL)
20761 				ill_refrele(attach_ill);
20762 			if (need_decref)
20763 				mp->b_flag |= MSGHASREF;
20764 			(void) ip_output_v6(arg, first_mp, arg2, caller);
20765 			return;
20766 		}
20767 
20768 		if ((v_hlen >> 4) != IP_VERSION) {
20769 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20770 			    "ip_wput_end: q %p (%S)", q, "badvers");
20771 			goto discard_pkt;
20772 		}
20773 		/*
20774 		 * Is the header length at least 20 bytes?
20775 		 *
20776 		 * Are there enough bytes accessible in the header?  If
20777 		 * not, try a pullup.
20778 		 */
20779 		v_hlen &= 0xF;
20780 		v_hlen <<= 2;
20781 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
20782 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20783 			    "ip_wput_end: q %p (%S)", q, "badlen");
20784 			goto discard_pkt;
20785 		}
20786 		if (v_hlen > (mp->b_wptr - rptr)) {
20787 			if (!pullupmsg(mp, v_hlen)) {
20788 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20789 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
20790 				goto discard_pkt;
20791 			}
20792 			ipha = (ipha_t *)mp->b_rptr;
20793 		}
20794 		/*
20795 		 * Move first entry from any source route into ipha_dst and
20796 		 * verify the options
20797 		 */
20798 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
20799 		    zoneid, ipst)) {
20800 			ASSERT(xmit_ill == NULL);
20801 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20802 			if (attach_ill != NULL)
20803 				ill_refrele(attach_ill);
20804 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20805 			    "ip_wput_end: q %p (%S)", q, "badopts");
20806 			if (need_decref)
20807 				CONN_DEC_REF(connp);
20808 			return;
20809 		}
20810 	}
20811 	dst = ipha->ipha_dst;
20812 
20813 	/*
20814 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
20815 	 * we have to run the packet through ip_newroute which will take
20816 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
20817 	 * a resolver, or assigning a default gateway, etc.
20818 	 */
20819 	if (CLASSD(dst)) {
20820 		ipif_t	*ipif;
20821 		uint32_t setsrc = 0;
20822 
20823 multicast:
20824 		ASSERT(first_mp != NULL);
20825 		ip2dbg(("ip_wput: CLASSD\n"));
20826 		if (connp == NULL) {
20827 			/*
20828 			 * Use the first good ipif on the ill.
20829 			 * XXX Should this ever happen? (Appears
20830 			 * to show up with just ppp and no ethernet due
20831 			 * to in.rdisc.)
20832 			 * However, ire_send should be able to
20833 			 * call ip_wput_ire directly.
20834 			 *
20835 			 * XXX Also, this can happen for ICMP and other packets
20836 			 * with multicast source addresses.  Perhaps we should
20837 			 * fix things so that we drop the packet in question,
20838 			 * but for now, just run with it.
20839 			 */
20840 			ill_t *ill = (ill_t *)q->q_ptr;
20841 
20842 			/*
20843 			 * Don't honor attach_if for this case. If ill
20844 			 * is part of the group, ipif could belong to
20845 			 * any ill and we cannot maintain attach_ill
20846 			 * and ipif_ill same anymore and the assert
20847 			 * below would fail.
20848 			 */
20849 			if (mctl_present && io->ipsec_out_attach_if) {
20850 				io->ipsec_out_ill_index = 0;
20851 				io->ipsec_out_attach_if = B_FALSE;
20852 				ASSERT(attach_ill != NULL);
20853 				ill_refrele(attach_ill);
20854 				attach_ill = NULL;
20855 			}
20856 
20857 			ASSERT(attach_ill == NULL);
20858 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
20859 			if (ipif == NULL) {
20860 				if (need_decref)
20861 					CONN_DEC_REF(connp);
20862 				freemsg(first_mp);
20863 				return;
20864 			}
20865 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
20866 			    ntohl(dst), ill->ill_name));
20867 		} else {
20868 			/*
20869 			 * The order of precedence is IP_BOUND_IF, IP_PKTINFO
20870 			 * and IP_MULTICAST_IF.  The block comment above this
20871 			 * function explains the locking mechanism used here.
20872 			 */
20873 			if (xmit_ill == NULL) {
20874 				xmit_ill = conn_get_held_ill(connp,
20875 				    &connp->conn_outgoing_ill, &err);
20876 				if (err == ILL_LOOKUP_FAILED) {
20877 					ip1dbg(("ip_wput: No ill for "
20878 					    "IP_BOUND_IF\n"));
20879 					BUMP_MIB(&ipst->ips_ip_mib,
20880 					    ipIfStatsOutNoRoutes);
20881 					goto drop_pkt;
20882 				}
20883 			}
20884 
20885 			if (xmit_ill == NULL) {
20886 				ipif = conn_get_held_ipif(connp,
20887 				    &connp->conn_multicast_ipif, &err);
20888 				if (err == IPIF_LOOKUP_FAILED) {
20889 					ip1dbg(("ip_wput: No ipif for "
20890 					    "multicast\n"));
20891 					BUMP_MIB(&ipst->ips_ip_mib,
20892 					    ipIfStatsOutNoRoutes);
20893 					goto drop_pkt;
20894 				}
20895 			}
20896 			if (xmit_ill != NULL) {
20897 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
20898 				if (ipif == NULL) {
20899 					ip1dbg(("ip_wput: No ipif for "
20900 					    "xmit_ill\n"));
20901 					BUMP_MIB(&ipst->ips_ip_mib,
20902 					    ipIfStatsOutNoRoutes);
20903 					goto drop_pkt;
20904 				}
20905 			} else if (ipif == NULL || ipif->ipif_isv6) {
20906 				/*
20907 				 * We must do this ipif determination here
20908 				 * else we could pass through ip_newroute
20909 				 * and come back here without the conn context.
20910 				 *
20911 				 * Note: we do late binding i.e. we bind to
20912 				 * the interface when the first packet is sent.
20913 				 * For performance reasons we do not rebind on
20914 				 * each packet but keep the binding until the
20915 				 * next IP_MULTICAST_IF option.
20916 				 *
20917 				 * conn_multicast_{ipif,ill} are shared between
20918 				 * IPv4 and IPv6 and AF_INET6 sockets can
20919 				 * send both IPv4 and IPv6 packets. Hence
20920 				 * we have to check that "isv6" matches above.
20921 				 */
20922 				if (ipif != NULL)
20923 					ipif_refrele(ipif);
20924 				ipif = ipif_lookup_group(dst, zoneid, ipst);
20925 				if (ipif == NULL) {
20926 					ip1dbg(("ip_wput: No ipif for "
20927 					    "multicast\n"));
20928 					BUMP_MIB(&ipst->ips_ip_mib,
20929 					    ipIfStatsOutNoRoutes);
20930 					goto drop_pkt;
20931 				}
20932 				err = conn_set_held_ipif(connp,
20933 				    &connp->conn_multicast_ipif, ipif);
20934 				if (err == IPIF_LOOKUP_FAILED) {
20935 					ipif_refrele(ipif);
20936 					ip1dbg(("ip_wput: No ipif for "
20937 					    "multicast\n"));
20938 					BUMP_MIB(&ipst->ips_ip_mib,
20939 					    ipIfStatsOutNoRoutes);
20940 					goto drop_pkt;
20941 				}
20942 			}
20943 		}
20944 		ASSERT(!ipif->ipif_isv6);
20945 		/*
20946 		 * As we may lose the conn by the time we reach ip_wput_ire,
20947 		 * we copy conn_multicast_loop and conn_dontroute on to an
20948 		 * ipsec_out. In case if this datagram goes out secure,
20949 		 * we need the ill_index also. Copy that also into the
20950 		 * ipsec_out.
20951 		 */
20952 		if (mctl_present) {
20953 			io = (ipsec_out_t *)first_mp->b_rptr;
20954 			ASSERT(first_mp->b_datap->db_type == M_CTL);
20955 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
20956 		} else {
20957 			ASSERT(mp == first_mp);
20958 			if ((first_mp = allocb(sizeof (ipsec_info_t),
20959 			    BPRI_HI)) == NULL) {
20960 				ipif_refrele(ipif);
20961 				first_mp = mp;
20962 				goto discard_pkt;
20963 			}
20964 			first_mp->b_datap->db_type = M_CTL;
20965 			first_mp->b_wptr += sizeof (ipsec_info_t);
20966 			/* ipsec_out_secure is B_FALSE now */
20967 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
20968 			io = (ipsec_out_t *)first_mp->b_rptr;
20969 			io->ipsec_out_type = IPSEC_OUT;
20970 			io->ipsec_out_len = sizeof (ipsec_out_t);
20971 			io->ipsec_out_use_global_policy = B_TRUE;
20972 			io->ipsec_out_ns = ipst->ips_netstack;
20973 			first_mp->b_cont = mp;
20974 			mctl_present = B_TRUE;
20975 		}
20976 		if (attach_ill != NULL) {
20977 			ASSERT(attach_ill == ipif->ipif_ill);
20978 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
20979 
20980 			/*
20981 			 * Check if we need an ire that will not be
20982 			 * looked up by anybody else i.e. HIDDEN.
20983 			 */
20984 			if (ill_is_probeonly(attach_ill)) {
20985 				match_flags |= MATCH_IRE_MARK_HIDDEN;
20986 			}
20987 			io->ipsec_out_ill_index =
20988 			    attach_ill->ill_phyint->phyint_ifindex;
20989 			io->ipsec_out_attach_if = B_TRUE;
20990 		} else {
20991 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
20992 			io->ipsec_out_ill_index =
20993 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
20994 		}
20995 		if (connp != NULL) {
20996 			io->ipsec_out_multicast_loop =
20997 			    connp->conn_multicast_loop;
20998 			io->ipsec_out_dontroute = connp->conn_dontroute;
20999 			io->ipsec_out_zoneid = connp->conn_zoneid;
21000 		}
21001 		/*
21002 		 * If the application uses IP_MULTICAST_IF with
21003 		 * different logical addresses of the same ILL, we
21004 		 * need to make sure that the soruce address of
21005 		 * the packet matches the logical IP address used
21006 		 * in the option. We do it by initializing ipha_src
21007 		 * here. This should keep IPsec also happy as
21008 		 * when we return from IPsec processing, we don't
21009 		 * have to worry about getting the right address on
21010 		 * the packet. Thus it is sufficient to look for
21011 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
21012 		 * MATCH_IRE_IPIF.
21013 		 *
21014 		 * NOTE : We need to do it for non-secure case also as
21015 		 * this might go out secure if there is a global policy
21016 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
21017 		 * address, the source should be initialized already and
21018 		 * hence we won't be initializing here.
21019 		 *
21020 		 * As we do not have the ire yet, it is possible that
21021 		 * we set the source address here and then later discover
21022 		 * that the ire implies the source address to be assigned
21023 		 * through the RTF_SETSRC flag.
21024 		 * In that case, the setsrc variable will remind us
21025 		 * that overwritting the source address by the one
21026 		 * of the RTF_SETSRC-flagged ire is allowed.
21027 		 */
21028 		if (ipha->ipha_src == INADDR_ANY &&
21029 		    (connp == NULL || !connp->conn_unspec_src)) {
21030 			ipha->ipha_src = ipif->ipif_src_addr;
21031 			setsrc = RTF_SETSRC;
21032 		}
21033 		/*
21034 		 * Find an IRE which matches the destination and the outgoing
21035 		 * queue (i.e. the outgoing interface.)
21036 		 * For loopback use a unicast IP address for
21037 		 * the ire lookup.
21038 		 */
21039 		if (IS_LOOPBACK(ipif->ipif_ill))
21040 			dst = ipif->ipif_lcl_addr;
21041 
21042 		/*
21043 		 * If xmit_ill is set, we branch out to ip_newroute_ipif.
21044 		 * We don't need to lookup ire in ctable as the packet
21045 		 * needs to be sent to the destination through the specified
21046 		 * ill irrespective of ires in the cache table.
21047 		 */
21048 		ire = NULL;
21049 		if (xmit_ill == NULL) {
21050 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21051 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21052 		}
21053 
21054 		/*
21055 		 * refrele attach_ill as its not needed anymore.
21056 		 */
21057 		if (attach_ill != NULL) {
21058 			ill_refrele(attach_ill);
21059 			attach_ill = NULL;
21060 		}
21061 
21062 		if (ire == NULL) {
21063 			/*
21064 			 * Multicast loopback and multicast forwarding is
21065 			 * done in ip_wput_ire.
21066 			 *
21067 			 * Mark this packet to make it be delivered to
21068 			 * ip_wput_ire after the new ire has been
21069 			 * created.
21070 			 *
21071 			 * The call to ip_newroute_ipif takes into account
21072 			 * the setsrc reminder. In any case, we take care
21073 			 * of the RTF_MULTIRT flag.
21074 			 */
21075 			mp->b_prev = mp->b_next = NULL;
21076 			if (xmit_ill == NULL ||
21077 			    xmit_ill->ill_ipif_up_count > 0) {
21078 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21079 				    setsrc | RTF_MULTIRT, zoneid, infop);
21080 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21081 				    "ip_wput_end: q %p (%S)", q, "noire");
21082 			} else {
21083 				freemsg(first_mp);
21084 			}
21085 			ipif_refrele(ipif);
21086 			if (xmit_ill != NULL)
21087 				ill_refrele(xmit_ill);
21088 			if (need_decref)
21089 				CONN_DEC_REF(connp);
21090 			return;
21091 		}
21092 
21093 		ipif_refrele(ipif);
21094 		ipif = NULL;
21095 		ASSERT(xmit_ill == NULL);
21096 
21097 		/*
21098 		 * Honor the RTF_SETSRC flag for multicast packets,
21099 		 * if allowed by the setsrc reminder.
21100 		 */
21101 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21102 			ipha->ipha_src = ire->ire_src_addr;
21103 		}
21104 
21105 		/*
21106 		 * Unconditionally force the TTL to 1 for
21107 		 * multirouted multicast packets:
21108 		 * multirouted multicast should not cross
21109 		 * multicast routers.
21110 		 */
21111 		if (ire->ire_flags & RTF_MULTIRT) {
21112 			if (ipha->ipha_ttl > 1) {
21113 				ip2dbg(("ip_wput: forcing multicast "
21114 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21115 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21116 				ipha->ipha_ttl = 1;
21117 			}
21118 		}
21119 	} else {
21120 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
21121 		if ((ire != NULL) && (ire->ire_type &
21122 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21123 			ignore_dontroute = B_TRUE;
21124 			ignore_nexthop = B_TRUE;
21125 		}
21126 		if (ire != NULL) {
21127 			ire_refrele(ire);
21128 			ire = NULL;
21129 		}
21130 		/*
21131 		 * Guard against coming in from arp in which case conn is NULL.
21132 		 * Also guard against non M_DATA with dontroute set but
21133 		 * destined to local, loopback or broadcast addresses.
21134 		 */
21135 		if (connp != NULL && connp->conn_dontroute &&
21136 		    !ignore_dontroute) {
21137 dontroute:
21138 			/*
21139 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21140 			 * routing protocols from seeing false direct
21141 			 * connectivity.
21142 			 */
21143 			ipha->ipha_ttl = 1;
21144 
21145 			/* If suitable ipif not found, drop packet */
21146 			dst_ipif = ipif_lookup_onlink_addr(dst, zoneid, ipst);
21147 			if (dst_ipif == NULL) {
21148 noroute:
21149 				ip1dbg(("ip_wput: no route for dst using"
21150 				    " SO_DONTROUTE\n"));
21151 				BUMP_MIB(&ipst->ips_ip_mib,
21152 				    ipIfStatsOutNoRoutes);
21153 				mp->b_prev = mp->b_next = NULL;
21154 				if (first_mp == NULL)
21155 					first_mp = mp;
21156 				goto drop_pkt;
21157 			} else {
21158 				/*
21159 				 * If suitable ipif has been found, set
21160 				 * xmit_ill to the corresponding
21161 				 * ipif_ill because we'll be using the
21162 				 * send_from_ill logic below.
21163 				 */
21164 				ASSERT(xmit_ill == NULL);
21165 				xmit_ill = dst_ipif->ipif_ill;
21166 				mutex_enter(&xmit_ill->ill_lock);
21167 				if (!ILL_CAN_LOOKUP(xmit_ill)) {
21168 					mutex_exit(&xmit_ill->ill_lock);
21169 					xmit_ill = NULL;
21170 					ipif_refrele(dst_ipif);
21171 					goto noroute;
21172 				}
21173 				ill_refhold_locked(xmit_ill);
21174 				mutex_exit(&xmit_ill->ill_lock);
21175 				ipif_refrele(dst_ipif);
21176 			}
21177 		}
21178 		/*
21179 		 * If we are bound to IPIF_NOFAILOVER address, look for
21180 		 * an IRE_CACHE matching the ill.
21181 		 */
21182 send_from_ill:
21183 		if (attach_ill != NULL) {
21184 			ipif_t	*attach_ipif;
21185 
21186 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21187 
21188 			/*
21189 			 * Check if we need an ire that will not be
21190 			 * looked up by anybody else i.e. HIDDEN.
21191 			 */
21192 			if (ill_is_probeonly(attach_ill)) {
21193 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21194 			}
21195 
21196 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
21197 			if (attach_ipif == NULL) {
21198 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
21199 				goto discard_pkt;
21200 			}
21201 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
21202 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21203 			ipif_refrele(attach_ipif);
21204 		} else if (xmit_ill != NULL) {
21205 			ipif_t *ipif;
21206 
21207 			/*
21208 			 * Mark this packet as originated locally
21209 			 */
21210 			mp->b_prev = mp->b_next = NULL;
21211 
21212 			/*
21213 			 * Could be SO_DONTROUTE case also.
21214 			 * Verify that at least one ipif is up on the ill.
21215 			 */
21216 			if (xmit_ill->ill_ipif_up_count == 0) {
21217 				ip1dbg(("ip_output: xmit_ill %s is down\n",
21218 				    xmit_ill->ill_name));
21219 				goto drop_pkt;
21220 			}
21221 
21222 			ipif = ipif_get_next_ipif(NULL, xmit_ill);
21223 			if (ipif == NULL) {
21224 				ip1dbg(("ip_output: xmit_ill %s NULL ipif\n",
21225 				    xmit_ill->ill_name));
21226 				goto drop_pkt;
21227 			}
21228 
21229 			/*
21230 			 * Look for a ire that is part of the group,
21231 			 * if found use it else call ip_newroute_ipif.
21232 			 * IPCL_ZONEID is not used for matching because
21233 			 * IP_ALLZONES option is valid only when the
21234 			 * ill is accessible from all zones i.e has a
21235 			 * valid ipif in all zones.
21236 			 */
21237 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
21238 			ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21239 			    MBLK_GETLABEL(mp), match_flags, ipst);
21240 			/*
21241 			 * If an ire exists use it or else create
21242 			 * an ire but don't add it to the cache.
21243 			 * Adding an ire may cause issues with
21244 			 * asymmetric routing.
21245 			 * In case of multiroute always act as if
21246 			 * ire does not exist.
21247 			 */
21248 			if (ire == NULL || ire->ire_flags & RTF_MULTIRT) {
21249 				if (ire != NULL)
21250 					ire_refrele(ire);
21251 				ip_newroute_ipif(q, first_mp, ipif,
21252 				    dst, connp, 0, zoneid, infop);
21253 				ipif_refrele(ipif);
21254 				ip1dbg(("ip_output: xmit_ill via %s\n",
21255 				    xmit_ill->ill_name));
21256 				ill_refrele(xmit_ill);
21257 				if (need_decref)
21258 					CONN_DEC_REF(connp);
21259 				return;
21260 			}
21261 			ipif_refrele(ipif);
21262 		} else if (ip_nexthop || (connp != NULL &&
21263 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21264 			if (!ip_nexthop) {
21265 				ip_nexthop = B_TRUE;
21266 				nexthop_addr = connp->conn_nexthop_v4;
21267 			}
21268 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21269 			    MATCH_IRE_GW;
21270 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21271 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21272 		} else {
21273 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp),
21274 			    ipst);
21275 		}
21276 		if (!ire) {
21277 			/*
21278 			 * Make sure we don't load spread if this
21279 			 * is IPIF_NOFAILOVER case.
21280 			 */
21281 			if ((attach_ill != NULL) ||
21282 			    (ip_nexthop && !ignore_nexthop)) {
21283 				if (mctl_present) {
21284 					io = (ipsec_out_t *)first_mp->b_rptr;
21285 					ASSERT(first_mp->b_datap->db_type ==
21286 					    M_CTL);
21287 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21288 				} else {
21289 					ASSERT(mp == first_mp);
21290 					first_mp = allocb(
21291 					    sizeof (ipsec_info_t), BPRI_HI);
21292 					if (first_mp == NULL) {
21293 						first_mp = mp;
21294 						goto discard_pkt;
21295 					}
21296 					first_mp->b_datap->db_type = M_CTL;
21297 					first_mp->b_wptr +=
21298 					    sizeof (ipsec_info_t);
21299 					/* ipsec_out_secure is B_FALSE now */
21300 					bzero(first_mp->b_rptr,
21301 					    sizeof (ipsec_info_t));
21302 					io = (ipsec_out_t *)first_mp->b_rptr;
21303 					io->ipsec_out_type = IPSEC_OUT;
21304 					io->ipsec_out_len =
21305 					    sizeof (ipsec_out_t);
21306 					io->ipsec_out_use_global_policy =
21307 					    B_TRUE;
21308 					io->ipsec_out_ns = ipst->ips_netstack;
21309 					first_mp->b_cont = mp;
21310 					mctl_present = B_TRUE;
21311 				}
21312 				if (attach_ill != NULL) {
21313 					io->ipsec_out_ill_index = attach_ill->
21314 					    ill_phyint->phyint_ifindex;
21315 					io->ipsec_out_attach_if = B_TRUE;
21316 				} else {
21317 					io->ipsec_out_ip_nexthop = ip_nexthop;
21318 					io->ipsec_out_nexthop_addr =
21319 					    nexthop_addr;
21320 				}
21321 			}
21322 noirefound:
21323 			/*
21324 			 * Mark this packet as having originated on
21325 			 * this machine.  This will be noted in
21326 			 * ire_add_then_send, which needs to know
21327 			 * whether to run it back through ip_wput or
21328 			 * ip_rput following successful resolution.
21329 			 */
21330 			mp->b_prev = NULL;
21331 			mp->b_next = NULL;
21332 			ip_newroute(q, first_mp, dst, connp, zoneid, ipst);
21333 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21334 			    "ip_wput_end: q %p (%S)", q, "newroute");
21335 			if (attach_ill != NULL)
21336 				ill_refrele(attach_ill);
21337 			if (xmit_ill != NULL)
21338 				ill_refrele(xmit_ill);
21339 			if (need_decref)
21340 				CONN_DEC_REF(connp);
21341 			return;
21342 		}
21343 	}
21344 
21345 	/* We now know where we are going with it. */
21346 
21347 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21348 	    "ip_wput_end: q %p (%S)", q, "end");
21349 
21350 	/*
21351 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21352 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21353 	 */
21354 	if (ire->ire_flags & RTF_MULTIRT) {
21355 		/*
21356 		 * Force the TTL of multirouted packets if required.
21357 		 * The TTL of such packets is bounded by the
21358 		 * ip_multirt_ttl ndd variable.
21359 		 */
21360 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21361 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21362 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21363 			    "(was %d), dst 0x%08x\n",
21364 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21365 			    ntohl(ire->ire_addr)));
21366 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21367 		}
21368 		/*
21369 		 * At this point, we check to see if there are any pending
21370 		 * unresolved routes. ire_multirt_resolvable()
21371 		 * checks in O(n) that all IRE_OFFSUBNET ire
21372 		 * entries for the packet's destination and
21373 		 * flagged RTF_MULTIRT are currently resolved.
21374 		 * If some remain unresolved, we make a copy
21375 		 * of the current message. It will be used
21376 		 * to initiate additional route resolutions.
21377 		 */
21378 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21379 		    MBLK_GETLABEL(first_mp), ipst);
21380 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21381 		    "multirt_need_resolve %d, first_mp %p\n",
21382 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21383 		if (multirt_need_resolve) {
21384 			copy_mp = copymsg(first_mp);
21385 			if (copy_mp != NULL) {
21386 				MULTIRT_DEBUG_TAG(copy_mp);
21387 			}
21388 		}
21389 	}
21390 
21391 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21392 	/*
21393 	 * Try to resolve another multiroute if
21394 	 * ire_multirt_resolvable() deemed it necessary.
21395 	 * At this point, we need to distinguish
21396 	 * multicasts from other packets. For multicasts,
21397 	 * we call ip_newroute_ipif() and request that both
21398 	 * multirouting and setsrc flags are checked.
21399 	 */
21400 	if (copy_mp != NULL) {
21401 		if (CLASSD(dst)) {
21402 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21403 			if (ipif) {
21404 				ASSERT(infop->ip_opt_ill_index == 0);
21405 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21406 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21407 				ipif_refrele(ipif);
21408 			} else {
21409 				MULTIRT_DEBUG_UNTAG(copy_mp);
21410 				freemsg(copy_mp);
21411 				copy_mp = NULL;
21412 			}
21413 		} else {
21414 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
21415 		}
21416 	}
21417 	if (attach_ill != NULL)
21418 		ill_refrele(attach_ill);
21419 	if (xmit_ill != NULL)
21420 		ill_refrele(xmit_ill);
21421 	if (need_decref)
21422 		CONN_DEC_REF(connp);
21423 	return;
21424 
21425 icmp_parameter_problem:
21426 	/* could not have originated externally */
21427 	ASSERT(mp->b_prev == NULL);
21428 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21429 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21430 		/* it's the IP header length that's in trouble */
21431 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21432 		first_mp = NULL;
21433 	}
21434 
21435 discard_pkt:
21436 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21437 drop_pkt:
21438 	ip1dbg(("ip_wput: dropped packet\n"));
21439 	if (ire != NULL)
21440 		ire_refrele(ire);
21441 	if (need_decref)
21442 		CONN_DEC_REF(connp);
21443 	freemsg(first_mp);
21444 	if (attach_ill != NULL)
21445 		ill_refrele(attach_ill);
21446 	if (xmit_ill != NULL)
21447 		ill_refrele(xmit_ill);
21448 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21449 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21450 }
21451 
21452 /*
21453  * If this is a conn_t queue, then we pass in the conn. This includes the
21454  * zoneid.
21455  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21456  * in which case we use the global zoneid since those are all part of
21457  * the global zone.
21458  */
21459 void
21460 ip_wput(queue_t *q, mblk_t *mp)
21461 {
21462 	if (CONN_Q(q))
21463 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21464 	else
21465 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21466 }
21467 
21468 /*
21469  *
21470  * The following rules must be observed when accessing any ipif or ill
21471  * that has been cached in the conn. Typically conn_nofailover_ill,
21472  * conn_outgoing_ill, conn_multicast_ipif and conn_multicast_ill.
21473  *
21474  * Access: The ipif or ill pointed to from the conn can be accessed under
21475  * the protection of the conn_lock or after it has been refheld under the
21476  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21477  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21478  * The reason for this is that a concurrent unplumb could actually be
21479  * cleaning up these cached pointers by walking the conns and might have
21480  * finished cleaning up the conn in question. The macros check that an
21481  * unplumb has not yet started on the ipif or ill.
21482  *
21483  * Caching: An ipif or ill pointer may be cached in the conn only after
21484  * making sure that an unplumb has not started. So the caching is done
21485  * while holding both the conn_lock and the ill_lock and after using the
21486  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21487  * flag before starting the cleanup of conns.
21488  *
21489  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21490  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21491  * or a reference to the ipif or a reference to an ire that references the
21492  * ipif. An ipif does not change its ill except for failover/failback. Since
21493  * failover/failback happens only after bringing down the ipif and making sure
21494  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
21495  * the above holds.
21496  */
21497 ipif_t *
21498 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21499 {
21500 	ipif_t	*ipif;
21501 	ill_t	*ill;
21502 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21503 
21504 	*err = 0;
21505 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21506 	mutex_enter(&connp->conn_lock);
21507 	ipif = *ipifp;
21508 	if (ipif != NULL) {
21509 		ill = ipif->ipif_ill;
21510 		mutex_enter(&ill->ill_lock);
21511 		if (IPIF_CAN_LOOKUP(ipif)) {
21512 			ipif_refhold_locked(ipif);
21513 			mutex_exit(&ill->ill_lock);
21514 			mutex_exit(&connp->conn_lock);
21515 			rw_exit(&ipst->ips_ill_g_lock);
21516 			return (ipif);
21517 		} else {
21518 			*err = IPIF_LOOKUP_FAILED;
21519 		}
21520 		mutex_exit(&ill->ill_lock);
21521 	}
21522 	mutex_exit(&connp->conn_lock);
21523 	rw_exit(&ipst->ips_ill_g_lock);
21524 	return (NULL);
21525 }
21526 
21527 ill_t *
21528 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21529 {
21530 	ill_t	*ill;
21531 
21532 	*err = 0;
21533 	mutex_enter(&connp->conn_lock);
21534 	ill = *illp;
21535 	if (ill != NULL) {
21536 		mutex_enter(&ill->ill_lock);
21537 		if (ILL_CAN_LOOKUP(ill)) {
21538 			ill_refhold_locked(ill);
21539 			mutex_exit(&ill->ill_lock);
21540 			mutex_exit(&connp->conn_lock);
21541 			return (ill);
21542 		} else {
21543 			*err = ILL_LOOKUP_FAILED;
21544 		}
21545 		mutex_exit(&ill->ill_lock);
21546 	}
21547 	mutex_exit(&connp->conn_lock);
21548 	return (NULL);
21549 }
21550 
21551 static int
21552 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21553 {
21554 	ill_t	*ill;
21555 
21556 	ill = ipif->ipif_ill;
21557 	mutex_enter(&connp->conn_lock);
21558 	mutex_enter(&ill->ill_lock);
21559 	if (IPIF_CAN_LOOKUP(ipif)) {
21560 		*ipifp = ipif;
21561 		mutex_exit(&ill->ill_lock);
21562 		mutex_exit(&connp->conn_lock);
21563 		return (0);
21564 	}
21565 	mutex_exit(&ill->ill_lock);
21566 	mutex_exit(&connp->conn_lock);
21567 	return (IPIF_LOOKUP_FAILED);
21568 }
21569 
21570 /*
21571  * This is called if the outbound datagram needs fragmentation.
21572  *
21573  * NOTE : This function does not ire_refrele the ire argument passed in.
21574  */
21575 static void
21576 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21577     ip_stack_t *ipst)
21578 {
21579 	ipha_t		*ipha;
21580 	mblk_t		*mp;
21581 	uint32_t	v_hlen_tos_len;
21582 	uint32_t	max_frag;
21583 	uint32_t	frag_flag;
21584 	boolean_t	dont_use;
21585 
21586 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21587 		mp = ipsec_mp->b_cont;
21588 	} else {
21589 		mp = ipsec_mp;
21590 	}
21591 
21592 	ipha = (ipha_t *)mp->b_rptr;
21593 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21594 
21595 #ifdef	_BIG_ENDIAN
21596 #define	V_HLEN	(v_hlen_tos_len >> 24)
21597 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21598 #else
21599 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21600 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21601 #endif
21602 
21603 #ifndef SPEED_BEFORE_SAFETY
21604 	/*
21605 	 * Check that ipha_length is consistent with
21606 	 * the mblk length
21607 	 */
21608 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21609 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21610 		    LENGTH, msgdsize(mp)));
21611 		freemsg(ipsec_mp);
21612 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21613 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21614 		    "packet length mismatch");
21615 		return;
21616 	}
21617 #endif
21618 	/*
21619 	 * Don't use frag_flag if pre-built packet or source
21620 	 * routed or if multicast (since multicast packets do not solicit
21621 	 * ICMP "packet too big" messages). Get the values of
21622 	 * max_frag and frag_flag atomically by acquiring the
21623 	 * ire_lock.
21624 	 */
21625 	mutex_enter(&ire->ire_lock);
21626 	max_frag = ire->ire_max_frag;
21627 	frag_flag = ire->ire_frag_flag;
21628 	mutex_exit(&ire->ire_lock);
21629 
21630 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21631 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21632 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21633 
21634 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21635 	    (dont_use ? 0 : frag_flag), zoneid, ipst);
21636 }
21637 
21638 /*
21639  * Used for deciding the MSS size for the upper layer. Thus
21640  * we need to check the outbound policy values in the conn.
21641  */
21642 int
21643 conn_ipsec_length(conn_t *connp)
21644 {
21645 	ipsec_latch_t *ipl;
21646 
21647 	ipl = connp->conn_latch;
21648 	if (ipl == NULL)
21649 		return (0);
21650 
21651 	if (ipl->ipl_out_policy == NULL)
21652 		return (0);
21653 
21654 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21655 }
21656 
21657 /*
21658  * Returns an estimate of the IPsec headers size. This is used if
21659  * we don't want to call into IPsec to get the exact size.
21660  */
21661 int
21662 ipsec_out_extra_length(mblk_t *ipsec_mp)
21663 {
21664 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21665 	ipsec_action_t *a;
21666 
21667 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21668 	if (!io->ipsec_out_secure)
21669 		return (0);
21670 
21671 	a = io->ipsec_out_act;
21672 
21673 	if (a == NULL) {
21674 		ASSERT(io->ipsec_out_policy != NULL);
21675 		a = io->ipsec_out_policy->ipsp_act;
21676 	}
21677 	ASSERT(a != NULL);
21678 
21679 	return (a->ipa_ovhd);
21680 }
21681 
21682 /*
21683  * Returns an estimate of the IPsec headers size. This is used if
21684  * we don't want to call into IPsec to get the exact size.
21685  */
21686 int
21687 ipsec_in_extra_length(mblk_t *ipsec_mp)
21688 {
21689 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21690 	ipsec_action_t *a;
21691 
21692 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21693 
21694 	a = ii->ipsec_in_action;
21695 	return (a == NULL ? 0 : a->ipa_ovhd);
21696 }
21697 
21698 /*
21699  * If there are any source route options, return the true final
21700  * destination. Otherwise, return the destination.
21701  */
21702 ipaddr_t
21703 ip_get_dst(ipha_t *ipha)
21704 {
21705 	ipoptp_t	opts;
21706 	uchar_t		*opt;
21707 	uint8_t		optval;
21708 	uint8_t		optlen;
21709 	ipaddr_t	dst;
21710 	uint32_t off;
21711 
21712 	dst = ipha->ipha_dst;
21713 
21714 	if (IS_SIMPLE_IPH(ipha))
21715 		return (dst);
21716 
21717 	for (optval = ipoptp_first(&opts, ipha);
21718 	    optval != IPOPT_EOL;
21719 	    optval = ipoptp_next(&opts)) {
21720 		opt = opts.ipoptp_cur;
21721 		optlen = opts.ipoptp_len;
21722 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
21723 		switch (optval) {
21724 		case IPOPT_SSRR:
21725 		case IPOPT_LSRR:
21726 			off = opt[IPOPT_OFFSET];
21727 			/*
21728 			 * If one of the conditions is true, it means
21729 			 * end of options and dst already has the right
21730 			 * value.
21731 			 */
21732 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
21733 				off = optlen - IP_ADDR_LEN;
21734 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
21735 			}
21736 			return (dst);
21737 		default:
21738 			break;
21739 		}
21740 	}
21741 
21742 	return (dst);
21743 }
21744 
21745 mblk_t *
21746 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
21747     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
21748 {
21749 	ipsec_out_t	*io;
21750 	mblk_t		*first_mp;
21751 	boolean_t policy_present;
21752 	ip_stack_t	*ipst;
21753 	ipsec_stack_t	*ipss;
21754 
21755 	ASSERT(ire != NULL);
21756 	ipst = ire->ire_ipst;
21757 	ipss = ipst->ips_netstack->netstack_ipsec;
21758 
21759 	first_mp = mp;
21760 	if (mp->b_datap->db_type == M_CTL) {
21761 		io = (ipsec_out_t *)first_mp->b_rptr;
21762 		/*
21763 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
21764 		 *
21765 		 * 1) There is per-socket policy (including cached global
21766 		 *    policy) or a policy on the IP-in-IP tunnel.
21767 		 * 2) There is no per-socket policy, but it is
21768 		 *    a multicast packet that needs to go out
21769 		 *    on a specific interface. This is the case
21770 		 *    where (ip_wput and ip_wput_multicast) attaches
21771 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
21772 		 *
21773 		 * In case (2) we check with global policy to
21774 		 * see if there is a match and set the ill_index
21775 		 * appropriately so that we can lookup the ire
21776 		 * properly in ip_wput_ipsec_out.
21777 		 */
21778 
21779 		/*
21780 		 * ipsec_out_use_global_policy is set to B_FALSE
21781 		 * in ipsec_in_to_out(). Refer to that function for
21782 		 * details.
21783 		 */
21784 		if ((io->ipsec_out_latch == NULL) &&
21785 		    (io->ipsec_out_use_global_policy)) {
21786 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
21787 			    ire, connp, unspec_src, zoneid));
21788 		}
21789 		if (!io->ipsec_out_secure) {
21790 			/*
21791 			 * If this is not a secure packet, drop
21792 			 * the IPSEC_OUT mp and treat it as a clear
21793 			 * packet. This happens when we are sending
21794 			 * a ICMP reply back to a clear packet. See
21795 			 * ipsec_in_to_out() for details.
21796 			 */
21797 			mp = first_mp->b_cont;
21798 			freeb(first_mp);
21799 		}
21800 		return (mp);
21801 	}
21802 	/*
21803 	 * See whether we need to attach a global policy here. We
21804 	 * don't depend on the conn (as it could be null) for deciding
21805 	 * what policy this datagram should go through because it
21806 	 * should have happened in ip_wput if there was some
21807 	 * policy. This normally happens for connections which are not
21808 	 * fully bound preventing us from caching policies in
21809 	 * ip_bind. Packets coming from the TCP listener/global queue
21810 	 * - which are non-hard_bound - could also be affected by
21811 	 * applying policy here.
21812 	 *
21813 	 * If this packet is coming from tcp global queue or listener,
21814 	 * we will be applying policy here.  This may not be *right*
21815 	 * if these packets are coming from the detached connection as
21816 	 * it could have gone in clear before. This happens only if a
21817 	 * TCP connection started when there is no policy and somebody
21818 	 * added policy before it became detached. Thus packets of the
21819 	 * detached connection could go out secure and the other end
21820 	 * would drop it because it will be expecting in clear. The
21821 	 * converse is not true i.e if somebody starts a TCP
21822 	 * connection and deletes the policy, all the packets will
21823 	 * still go out with the policy that existed before deleting
21824 	 * because ip_unbind sends up policy information which is used
21825 	 * by TCP on subsequent ip_wputs. The right solution is to fix
21826 	 * TCP to attach a dummy IPSEC_OUT and set
21827 	 * ipsec_out_use_global_policy to B_FALSE. As this might
21828 	 * affect performance for normal cases, we are not doing it.
21829 	 * Thus, set policy before starting any TCP connections.
21830 	 *
21831 	 * NOTE - We might apply policy even for a hard bound connection
21832 	 * - for which we cached policy in ip_bind - if somebody added
21833 	 * global policy after we inherited the policy in ip_bind.
21834 	 * This means that the packets that were going out in clear
21835 	 * previously would start going secure and hence get dropped
21836 	 * on the other side. To fix this, TCP attaches a dummy
21837 	 * ipsec_out and make sure that we don't apply global policy.
21838 	 */
21839 	if (ipha != NULL)
21840 		policy_present = ipss->ipsec_outbound_v4_policy_present;
21841 	else
21842 		policy_present = ipss->ipsec_outbound_v6_policy_present;
21843 	if (!policy_present)
21844 		return (mp);
21845 
21846 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
21847 	    zoneid));
21848 }
21849 
21850 ire_t *
21851 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
21852 {
21853 	ipaddr_t addr;
21854 	ire_t *save_ire;
21855 	irb_t *irb;
21856 	ill_group_t *illgrp;
21857 	int	err;
21858 
21859 	save_ire = ire;
21860 	addr = ire->ire_addr;
21861 
21862 	ASSERT(ire->ire_type == IRE_BROADCAST);
21863 
21864 	illgrp = connp->conn_outgoing_ill->ill_group;
21865 	if (illgrp == NULL) {
21866 		*conn_outgoing_ill = conn_get_held_ill(connp,
21867 		    &connp->conn_outgoing_ill, &err);
21868 		if (err == ILL_LOOKUP_FAILED) {
21869 			ire_refrele(save_ire);
21870 			return (NULL);
21871 		}
21872 		return (save_ire);
21873 	}
21874 	/*
21875 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
21876 	 * If it is part of the group, we need to send on the ire
21877 	 * that has been cleared of IRE_MARK_NORECV and that belongs
21878 	 * to this group. This is okay as IP_BOUND_IF really means
21879 	 * any ill in the group. We depend on the fact that the
21880 	 * first ire in the group is always cleared of IRE_MARK_NORECV
21881 	 * if such an ire exists. This is possible only if you have
21882 	 * at least one ill in the group that has not failed.
21883 	 *
21884 	 * First get to the ire that matches the address and group.
21885 	 *
21886 	 * We don't look for an ire with a matching zoneid because a given zone
21887 	 * won't always have broadcast ires on all ills in the group.
21888 	 */
21889 	irb = ire->ire_bucket;
21890 	rw_enter(&irb->irb_lock, RW_READER);
21891 	if (ire->ire_marks & IRE_MARK_NORECV) {
21892 		/*
21893 		 * If the current zone only has an ire broadcast for this
21894 		 * address marked NORECV, the ire we want is ahead in the
21895 		 * bucket, so we look it up deliberately ignoring the zoneid.
21896 		 */
21897 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
21898 			if (ire->ire_addr != addr)
21899 				continue;
21900 			/* skip over deleted ires */
21901 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
21902 				continue;
21903 		}
21904 	}
21905 	while (ire != NULL) {
21906 		/*
21907 		 * If a new interface is coming up, we could end up
21908 		 * seeing the loopback ire and the non-loopback ire
21909 		 * may not have been added yet. So check for ire_stq
21910 		 */
21911 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
21912 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
21913 			break;
21914 		}
21915 		ire = ire->ire_next;
21916 	}
21917 	if (ire != NULL && ire->ire_addr == addr &&
21918 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
21919 		IRE_REFHOLD(ire);
21920 		rw_exit(&irb->irb_lock);
21921 		ire_refrele(save_ire);
21922 		*conn_outgoing_ill = ire_to_ill(ire);
21923 		/*
21924 		 * Refhold the ill to make the conn_outgoing_ill
21925 		 * independent of the ire. ip_wput_ire goes in a loop
21926 		 * and may refrele the ire. Since we have an ire at this
21927 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
21928 		 */
21929 		ill_refhold(*conn_outgoing_ill);
21930 		return (ire);
21931 	}
21932 	rw_exit(&irb->irb_lock);
21933 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
21934 	/*
21935 	 * If we can't find a suitable ire, return the original ire.
21936 	 */
21937 	return (save_ire);
21938 }
21939 
21940 /*
21941  * This function does the ire_refrele of the ire passed in as the
21942  * argument. As this function looks up more ires i.e broadcast ires,
21943  * it needs to REFRELE them. Currently, for simplicity we don't
21944  * differentiate the one passed in and looked up here. We always
21945  * REFRELE.
21946  * IPQoS Notes:
21947  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
21948  * IPsec packets are done in ipsec_out_process.
21949  *
21950  */
21951 void
21952 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
21953     zoneid_t zoneid)
21954 {
21955 	ipha_t		*ipha;
21956 #define	rptr	((uchar_t *)ipha)
21957 	queue_t		*stq;
21958 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
21959 	uint32_t	v_hlen_tos_len;
21960 	uint32_t	ttl_protocol;
21961 	ipaddr_t	src;
21962 	ipaddr_t	dst;
21963 	uint32_t	cksum;
21964 	ipaddr_t	orig_src;
21965 	ire_t		*ire1;
21966 	mblk_t		*next_mp;
21967 	uint_t		hlen;
21968 	uint16_t	*up;
21969 	uint32_t	max_frag = ire->ire_max_frag;
21970 	ill_t		*ill = ire_to_ill(ire);
21971 	int		clusterwide;
21972 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
21973 	int		ipsec_len;
21974 	mblk_t		*first_mp;
21975 	ipsec_out_t	*io;
21976 	boolean_t	conn_dontroute;		/* conn value for multicast */
21977 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
21978 	boolean_t	multicast_forward;	/* Should we forward ? */
21979 	boolean_t	unspec_src;
21980 	ill_t		*conn_outgoing_ill = NULL;
21981 	ill_t		*ire_ill;
21982 	ill_t		*ire1_ill;
21983 	ill_t		*out_ill;
21984 	uint32_t 	ill_index = 0;
21985 	boolean_t	multirt_send = B_FALSE;
21986 	int		err;
21987 	ipxmit_state_t	pktxmit_state;
21988 	ip_stack_t	*ipst = ire->ire_ipst;
21989 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
21990 
21991 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
21992 	    "ip_wput_ire_start: q %p", q);
21993 
21994 	multicast_forward = B_FALSE;
21995 	unspec_src = (connp != NULL && connp->conn_unspec_src);
21996 
21997 	if (ire->ire_flags & RTF_MULTIRT) {
21998 		/*
21999 		 * Multirouting case. The bucket where ire is stored
22000 		 * probably holds other RTF_MULTIRT flagged ire
22001 		 * to the destination. In this call to ip_wput_ire,
22002 		 * we attempt to send the packet through all
22003 		 * those ires. Thus, we first ensure that ire is the
22004 		 * first RTF_MULTIRT ire in the bucket,
22005 		 * before walking the ire list.
22006 		 */
22007 		ire_t *first_ire;
22008 		irb_t *irb = ire->ire_bucket;
22009 		ASSERT(irb != NULL);
22010 
22011 		/* Make sure we do not omit any multiroute ire. */
22012 		IRB_REFHOLD(irb);
22013 		for (first_ire = irb->irb_ire;
22014 		    first_ire != NULL;
22015 		    first_ire = first_ire->ire_next) {
22016 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22017 			    (first_ire->ire_addr == ire->ire_addr) &&
22018 			    !(first_ire->ire_marks &
22019 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
22020 				break;
22021 			}
22022 		}
22023 
22024 		if ((first_ire != NULL) && (first_ire != ire)) {
22025 			IRE_REFHOLD(first_ire);
22026 			ire_refrele(ire);
22027 			ire = first_ire;
22028 			ill = ire_to_ill(ire);
22029 		}
22030 		IRB_REFRELE(irb);
22031 	}
22032 
22033 	/*
22034 	 * conn_outgoing_ill variable is used only in the broadcast loop.
22035 	 * for performance we don't grab the mutexs in the fastpath
22036 	 */
22037 	if ((connp != NULL) &&
22038 	    (ire->ire_type == IRE_BROADCAST) &&
22039 	    ((connp->conn_nofailover_ill != NULL) ||
22040 	    (connp->conn_outgoing_ill != NULL))) {
22041 		/*
22042 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
22043 		 * option. So, see if this endpoint is bound to a
22044 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
22045 		 * that if the interface is failed, we will still send
22046 		 * the packet on the same ill which is what we want.
22047 		 */
22048 		conn_outgoing_ill = conn_get_held_ill(connp,
22049 		    &connp->conn_nofailover_ill, &err);
22050 		if (err == ILL_LOOKUP_FAILED) {
22051 			ire_refrele(ire);
22052 			freemsg(mp);
22053 			return;
22054 		}
22055 		if (conn_outgoing_ill == NULL) {
22056 			/*
22057 			 * Choose a good ill in the group to send the
22058 			 * packets on.
22059 			 */
22060 			ire = conn_set_outgoing_ill(connp, ire,
22061 			    &conn_outgoing_ill);
22062 			if (ire == NULL) {
22063 				freemsg(mp);
22064 				return;
22065 			}
22066 		}
22067 	}
22068 
22069 	if (mp->b_datap->db_type != M_CTL) {
22070 		ipha = (ipha_t *)mp->b_rptr;
22071 	} else {
22072 		io = (ipsec_out_t *)mp->b_rptr;
22073 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22074 		ASSERT(zoneid == io->ipsec_out_zoneid);
22075 		ASSERT(zoneid != ALL_ZONES);
22076 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22077 		dst = ipha->ipha_dst;
22078 		/*
22079 		 * For the multicast case, ipsec_out carries conn_dontroute and
22080 		 * conn_multicast_loop as conn may not be available here. We
22081 		 * need this for multicast loopback and forwarding which is done
22082 		 * later in the code.
22083 		 */
22084 		if (CLASSD(dst)) {
22085 			conn_dontroute = io->ipsec_out_dontroute;
22086 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22087 			/*
22088 			 * If conn_dontroute is not set or conn_multicast_loop
22089 			 * is set, we need to do forwarding/loopback. For
22090 			 * datagrams from ip_wput_multicast, conn_dontroute is
22091 			 * set to B_TRUE and conn_multicast_loop is set to
22092 			 * B_FALSE so that we neither do forwarding nor
22093 			 * loopback.
22094 			 */
22095 			if (!conn_dontroute || conn_multicast_loop)
22096 				multicast_forward = B_TRUE;
22097 		}
22098 	}
22099 
22100 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22101 	    ire->ire_zoneid != ALL_ZONES) {
22102 		/*
22103 		 * When a zone sends a packet to another zone, we try to deliver
22104 		 * the packet under the same conditions as if the destination
22105 		 * was a real node on the network. To do so, we look for a
22106 		 * matching route in the forwarding table.
22107 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22108 		 * ip_newroute() does.
22109 		 * Note that IRE_LOCAL are special, since they are used
22110 		 * when the zoneid doesn't match in some cases. This means that
22111 		 * we need to handle ipha_src differently since ire_src_addr
22112 		 * belongs to the receiving zone instead of the sending zone.
22113 		 * When ip_restrict_interzone_loopback is set, then
22114 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22115 		 * for loopback between zones when the logical "Ethernet" would
22116 		 * have looped them back.
22117 		 */
22118 		ire_t *src_ire;
22119 
22120 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22121 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22122 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22123 		if (src_ire != NULL &&
22124 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22125 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22126 		    ire_local_same_ill_group(ire, src_ire))) {
22127 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22128 				ipha->ipha_src = src_ire->ire_src_addr;
22129 			ire_refrele(src_ire);
22130 		} else {
22131 			ire_refrele(ire);
22132 			if (conn_outgoing_ill != NULL)
22133 				ill_refrele(conn_outgoing_ill);
22134 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22135 			if (src_ire != NULL) {
22136 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22137 					ire_refrele(src_ire);
22138 					freemsg(mp);
22139 					return;
22140 				}
22141 				ire_refrele(src_ire);
22142 			}
22143 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22144 				/* Failed */
22145 				freemsg(mp);
22146 				return;
22147 			}
22148 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22149 			    ipst);
22150 			return;
22151 		}
22152 	}
22153 
22154 	if (mp->b_datap->db_type == M_CTL ||
22155 	    ipss->ipsec_outbound_v4_policy_present) {
22156 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22157 		    unspec_src, zoneid);
22158 		if (mp == NULL) {
22159 			ire_refrele(ire);
22160 			if (conn_outgoing_ill != NULL)
22161 				ill_refrele(conn_outgoing_ill);
22162 			return;
22163 		}
22164 	}
22165 
22166 	first_mp = mp;
22167 	ipsec_len = 0;
22168 
22169 	if (first_mp->b_datap->db_type == M_CTL) {
22170 		io = (ipsec_out_t *)first_mp->b_rptr;
22171 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22172 		mp = first_mp->b_cont;
22173 		ipsec_len = ipsec_out_extra_length(first_mp);
22174 		ASSERT(ipsec_len >= 0);
22175 		/* We already picked up the zoneid from the M_CTL above */
22176 		ASSERT(zoneid == io->ipsec_out_zoneid);
22177 		ASSERT(zoneid != ALL_ZONES);
22178 
22179 		/*
22180 		 * Drop M_CTL here if IPsec processing is not needed.
22181 		 * (Non-IPsec use of M_CTL extracted any information it
22182 		 * needed above).
22183 		 */
22184 		if (ipsec_len == 0) {
22185 			freeb(first_mp);
22186 			first_mp = mp;
22187 		}
22188 	}
22189 
22190 	/*
22191 	 * Fast path for ip_wput_ire
22192 	 */
22193 
22194 	ipha = (ipha_t *)mp->b_rptr;
22195 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22196 	dst = ipha->ipha_dst;
22197 
22198 	/*
22199 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22200 	 * if the socket is a SOCK_RAW type. The transport checksum should
22201 	 * be provided in the pre-built packet, so we don't need to compute it.
22202 	 * Also, other application set flags, like DF, should not be altered.
22203 	 * Other transport MUST pass down zero.
22204 	 */
22205 	ip_hdr_included = ipha->ipha_ident;
22206 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22207 
22208 	if (CLASSD(dst)) {
22209 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22210 		    ntohl(dst),
22211 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22212 		    ntohl(ire->ire_addr)));
22213 	}
22214 
22215 /* Macros to extract header fields from data already in registers */
22216 #ifdef	_BIG_ENDIAN
22217 #define	V_HLEN	(v_hlen_tos_len >> 24)
22218 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22219 #define	PROTO	(ttl_protocol & 0xFF)
22220 #else
22221 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22222 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22223 #define	PROTO	(ttl_protocol >> 8)
22224 #endif
22225 
22226 
22227 	orig_src = src = ipha->ipha_src;
22228 	/* (The loop back to "another" is explained down below.) */
22229 another:;
22230 	/*
22231 	 * Assign an ident value for this packet.  We assign idents on
22232 	 * a per destination basis out of the IRE.  There could be
22233 	 * other threads targeting the same destination, so we have to
22234 	 * arrange for a atomic increment.  Note that we use a 32-bit
22235 	 * atomic add because it has better performance than its
22236 	 * 16-bit sibling.
22237 	 *
22238 	 * If running in cluster mode and if the source address
22239 	 * belongs to a replicated service then vector through
22240 	 * cl_inet_ipident vector to allocate ip identifier
22241 	 * NOTE: This is a contract private interface with the
22242 	 * clustering group.
22243 	 */
22244 	clusterwide = 0;
22245 	if (cl_inet_ipident) {
22246 		ASSERT(cl_inet_isclusterwide);
22247 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
22248 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
22249 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
22250 			    AF_INET, (uint8_t *)(uintptr_t)src,
22251 			    (uint8_t *)(uintptr_t)dst);
22252 			clusterwide = 1;
22253 		}
22254 	}
22255 	if (!clusterwide) {
22256 		ipha->ipha_ident =
22257 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22258 	}
22259 
22260 #ifndef _BIG_ENDIAN
22261 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22262 #endif
22263 
22264 	/*
22265 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22266 	 * This is needed to obey conn_unspec_src when packets go through
22267 	 * ip_newroute + arp.
22268 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22269 	 */
22270 	if (src == INADDR_ANY && !unspec_src) {
22271 		/*
22272 		 * Assign the appropriate source address from the IRE if none
22273 		 * was specified.
22274 		 */
22275 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22276 
22277 		/*
22278 		 * With IP multipathing, broadcast packets are sent on the ire
22279 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
22280 		 * the group. However, this ire might not be in the same zone so
22281 		 * we can't always use its source address. We look for a
22282 		 * broadcast ire in the same group and in the right zone.
22283 		 */
22284 		if (ire->ire_type == IRE_BROADCAST &&
22285 		    ire->ire_zoneid != zoneid) {
22286 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
22287 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
22288 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
22289 			if (src_ire != NULL) {
22290 				src = src_ire->ire_src_addr;
22291 				ire_refrele(src_ire);
22292 			} else {
22293 				ire_refrele(ire);
22294 				if (conn_outgoing_ill != NULL)
22295 					ill_refrele(conn_outgoing_ill);
22296 				freemsg(first_mp);
22297 				if (ill != NULL) {
22298 					BUMP_MIB(ill->ill_ip_mib,
22299 					    ipIfStatsOutDiscards);
22300 				} else {
22301 					BUMP_MIB(&ipst->ips_ip_mib,
22302 					    ipIfStatsOutDiscards);
22303 				}
22304 				return;
22305 			}
22306 		} else {
22307 			src = ire->ire_src_addr;
22308 		}
22309 
22310 		if (connp == NULL) {
22311 			ip1dbg(("ip_wput_ire: no connp and no src "
22312 			    "address for dst 0x%x, using src 0x%x\n",
22313 			    ntohl(dst),
22314 			    ntohl(src)));
22315 		}
22316 		ipha->ipha_src = src;
22317 	}
22318 	stq = ire->ire_stq;
22319 
22320 	/*
22321 	 * We only allow ire chains for broadcasts since there will
22322 	 * be multiple IRE_CACHE entries for the same multicast
22323 	 * address (one per ipif).
22324 	 */
22325 	next_mp = NULL;
22326 
22327 	/* broadcast packet */
22328 	if (ire->ire_type == IRE_BROADCAST)
22329 		goto broadcast;
22330 
22331 	/* loopback ? */
22332 	if (stq == NULL)
22333 		goto nullstq;
22334 
22335 	/* The ill_index for outbound ILL */
22336 	ill_index = Q_TO_INDEX(stq);
22337 
22338 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22339 	ttl_protocol = ((uint16_t *)ipha)[4];
22340 
22341 	/* pseudo checksum (do it in parts for IP header checksum) */
22342 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22343 
22344 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22345 		queue_t *dev_q = stq->q_next;
22346 
22347 		/* flow controlled */
22348 		if ((dev_q->q_next || dev_q->q_first) &&
22349 		    !canput(dev_q))
22350 			goto blocked;
22351 		if ((PROTO == IPPROTO_UDP) &&
22352 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22353 			hlen = (V_HLEN & 0xF) << 2;
22354 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22355 			if (*up != 0) {
22356 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22357 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22358 				/* Software checksum? */
22359 				if (DB_CKSUMFLAGS(mp) == 0) {
22360 					IP_STAT(ipst, ip_out_sw_cksum);
22361 					IP_STAT_UPDATE(ipst,
22362 					    ip_udp_out_sw_cksum_bytes,
22363 					    LENGTH - hlen);
22364 				}
22365 			}
22366 		}
22367 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22368 		hlen = (V_HLEN & 0xF) << 2;
22369 		if (PROTO == IPPROTO_TCP) {
22370 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22371 			/*
22372 			 * The packet header is processed once and for all, even
22373 			 * in the multirouting case. We disable hardware
22374 			 * checksum if the packet is multirouted, as it will be
22375 			 * replicated via several interfaces, and not all of
22376 			 * them may have this capability.
22377 			 */
22378 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22379 			    LENGTH, max_frag, ipsec_len, cksum);
22380 			/* Software checksum? */
22381 			if (DB_CKSUMFLAGS(mp) == 0) {
22382 				IP_STAT(ipst, ip_out_sw_cksum);
22383 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22384 				    LENGTH - hlen);
22385 			}
22386 		} else {
22387 			sctp_hdr_t	*sctph;
22388 
22389 			ASSERT(PROTO == IPPROTO_SCTP);
22390 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22391 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22392 			/*
22393 			 * Zero out the checksum field to ensure proper
22394 			 * checksum calculation.
22395 			 */
22396 			sctph->sh_chksum = 0;
22397 #ifdef	DEBUG
22398 			if (!skip_sctp_cksum)
22399 #endif
22400 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22401 		}
22402 	}
22403 
22404 	/*
22405 	 * If this is a multicast packet and originated from ip_wput
22406 	 * we need to do loopback and forwarding checks. If it comes
22407 	 * from ip_wput_multicast, we SHOULD not do this.
22408 	 */
22409 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22410 
22411 	/* checksum */
22412 	cksum += ttl_protocol;
22413 
22414 	/* fragment the packet */
22415 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22416 		goto fragmentit;
22417 	/*
22418 	 * Don't use frag_flag if packet is pre-built or source
22419 	 * routed or if multicast (since multicast packets do
22420 	 * not solicit ICMP "packet too big" messages).
22421 	 */
22422 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22423 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22424 	    !ip_source_route_included(ipha)) &&
22425 	    !CLASSD(ipha->ipha_dst))
22426 		ipha->ipha_fragment_offset_and_flags |=
22427 		    htons(ire->ire_frag_flag);
22428 
22429 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22430 		/* calculate IP header checksum */
22431 		cksum += ipha->ipha_ident;
22432 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22433 		cksum += ipha->ipha_fragment_offset_and_flags;
22434 
22435 		/* IP options present */
22436 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22437 		if (hlen)
22438 			goto checksumoptions;
22439 
22440 		/* calculate hdr checksum */
22441 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22442 		cksum = ~(cksum + (cksum >> 16));
22443 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22444 	}
22445 	if (ipsec_len != 0) {
22446 		/*
22447 		 * We will do the rest of the processing after
22448 		 * we come back from IPsec in ip_wput_ipsec_out().
22449 		 */
22450 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22451 
22452 		io = (ipsec_out_t *)first_mp->b_rptr;
22453 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
22454 		    ill_phyint->phyint_ifindex;
22455 
22456 		ipsec_out_process(q, first_mp, ire, ill_index);
22457 		ire_refrele(ire);
22458 		if (conn_outgoing_ill != NULL)
22459 			ill_refrele(conn_outgoing_ill);
22460 		return;
22461 	}
22462 
22463 	/*
22464 	 * In most cases, the emission loop below is entered only
22465 	 * once. Only in the case where the ire holds the
22466 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22467 	 * flagged ires in the bucket, and send the packet
22468 	 * through all crossed RTF_MULTIRT routes.
22469 	 */
22470 	if (ire->ire_flags & RTF_MULTIRT) {
22471 		multirt_send = B_TRUE;
22472 	}
22473 	do {
22474 		if (multirt_send) {
22475 			irb_t *irb;
22476 			/*
22477 			 * We are in a multiple send case, need to get
22478 			 * the next ire and make a duplicate of the packet.
22479 			 * ire1 holds here the next ire to process in the
22480 			 * bucket. If multirouting is expected,
22481 			 * any non-RTF_MULTIRT ire that has the
22482 			 * right destination address is ignored.
22483 			 */
22484 			irb = ire->ire_bucket;
22485 			ASSERT(irb != NULL);
22486 
22487 			IRB_REFHOLD(irb);
22488 			for (ire1 = ire->ire_next;
22489 			    ire1 != NULL;
22490 			    ire1 = ire1->ire_next) {
22491 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22492 					continue;
22493 				if (ire1->ire_addr != ire->ire_addr)
22494 					continue;
22495 				if (ire1->ire_marks &
22496 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
22497 					continue;
22498 
22499 				/* Got one */
22500 				IRE_REFHOLD(ire1);
22501 				break;
22502 			}
22503 			IRB_REFRELE(irb);
22504 
22505 			if (ire1 != NULL) {
22506 				next_mp = copyb(mp);
22507 				if ((next_mp == NULL) ||
22508 				    ((mp->b_cont != NULL) &&
22509 				    ((next_mp->b_cont =
22510 				    dupmsg(mp->b_cont)) == NULL))) {
22511 					freemsg(next_mp);
22512 					next_mp = NULL;
22513 					ire_refrele(ire1);
22514 					ire1 = NULL;
22515 				}
22516 			}
22517 
22518 			/* Last multiroute ire; don't loop anymore. */
22519 			if (ire1 == NULL) {
22520 				multirt_send = B_FALSE;
22521 			}
22522 		}
22523 
22524 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22525 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22526 		    mblk_t *, mp);
22527 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22528 		    ipst->ips_ipv4firewall_physical_out,
22529 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, ipst);
22530 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22531 		if (mp == NULL)
22532 			goto release_ire_and_ill;
22533 
22534 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22535 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22536 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE);
22537 		if ((pktxmit_state == SEND_FAILED) ||
22538 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22539 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22540 			    "- packet dropped\n"));
22541 release_ire_and_ill:
22542 			ire_refrele(ire);
22543 			if (next_mp != NULL) {
22544 				freemsg(next_mp);
22545 				ire_refrele(ire1);
22546 			}
22547 			if (conn_outgoing_ill != NULL)
22548 				ill_refrele(conn_outgoing_ill);
22549 			return;
22550 		}
22551 
22552 		if (CLASSD(dst)) {
22553 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22554 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22555 			    LENGTH);
22556 		}
22557 
22558 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22559 		    "ip_wput_ire_end: q %p (%S)",
22560 		    q, "last copy out");
22561 		IRE_REFRELE(ire);
22562 
22563 		if (multirt_send) {
22564 			ASSERT(ire1);
22565 			/*
22566 			 * Proceed with the next RTF_MULTIRT ire,
22567 			 * Also set up the send-to queue accordingly.
22568 			 */
22569 			ire = ire1;
22570 			ire1 = NULL;
22571 			stq = ire->ire_stq;
22572 			mp = next_mp;
22573 			next_mp = NULL;
22574 			ipha = (ipha_t *)mp->b_rptr;
22575 			ill_index = Q_TO_INDEX(stq);
22576 			ill = (ill_t *)stq->q_ptr;
22577 		}
22578 	} while (multirt_send);
22579 	if (conn_outgoing_ill != NULL)
22580 		ill_refrele(conn_outgoing_ill);
22581 	return;
22582 
22583 	/*
22584 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22585 	 */
22586 broadcast:
22587 	{
22588 		/*
22589 		 * To avoid broadcast storms, we usually set the TTL to 1 for
22590 		 * broadcasts.  However, if SO_DONTROUTE isn't set, this value
22591 		 * can be overridden stack-wide through the ip_broadcast_ttl
22592 		 * ndd tunable, or on a per-connection basis through the
22593 		 * IP_BROADCAST_TTL socket option.
22594 		 *
22595 		 * In the event that we are replying to incoming ICMP packets,
22596 		 * connp could be NULL.
22597 		 */
22598 		ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22599 		if (connp != NULL) {
22600 			if (connp->conn_dontroute)
22601 				ipha->ipha_ttl = 1;
22602 			else if (connp->conn_broadcast_ttl != 0)
22603 				ipha->ipha_ttl = connp->conn_broadcast_ttl;
22604 		}
22605 
22606 		/*
22607 		 * Note that we are not doing a IRB_REFHOLD here.
22608 		 * Actually we don't care if the list changes i.e
22609 		 * if somebody deletes an IRE from the list while
22610 		 * we drop the lock, the next time we come around
22611 		 * ire_next will be NULL and hence we won't send
22612 		 * out multiple copies which is fine.
22613 		 */
22614 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22615 		ire1 = ire->ire_next;
22616 		if (conn_outgoing_ill != NULL) {
22617 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22618 				ASSERT(ire1 == ire->ire_next);
22619 				if (ire1 != NULL && ire1->ire_addr == dst) {
22620 					ire_refrele(ire);
22621 					ire = ire1;
22622 					IRE_REFHOLD(ire);
22623 					ire1 = ire->ire_next;
22624 					continue;
22625 				}
22626 				rw_exit(&ire->ire_bucket->irb_lock);
22627 				/* Did not find a matching ill */
22628 				ip1dbg(("ip_wput_ire: broadcast with no "
22629 				    "matching IP_BOUND_IF ill %s dst %x\n",
22630 				    conn_outgoing_ill->ill_name, dst));
22631 				freemsg(first_mp);
22632 				if (ire != NULL)
22633 					ire_refrele(ire);
22634 				ill_refrele(conn_outgoing_ill);
22635 				return;
22636 			}
22637 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22638 			/*
22639 			 * If the next IRE has the same address and is not one
22640 			 * of the two copies that we need to send, try to see
22641 			 * whether this copy should be sent at all. This
22642 			 * assumes that we insert loopbacks first and then
22643 			 * non-loopbacks. This is acheived by inserting the
22644 			 * loopback always before non-loopback.
22645 			 * This is used to send a single copy of a broadcast
22646 			 * packet out all physical interfaces that have an
22647 			 * matching IRE_BROADCAST while also looping
22648 			 * back one copy (to ip_wput_local) for each
22649 			 * matching physical interface. However, we avoid
22650 			 * sending packets out different logical that match by
22651 			 * having ipif_up/ipif_down supress duplicate
22652 			 * IRE_BROADCASTS.
22653 			 *
22654 			 * This feature is currently used to get broadcasts
22655 			 * sent to multiple interfaces, when the broadcast
22656 			 * address being used applies to multiple interfaces.
22657 			 * For example, a whole net broadcast will be
22658 			 * replicated on every connected subnet of
22659 			 * the target net.
22660 			 *
22661 			 * Each zone has its own set of IRE_BROADCASTs, so that
22662 			 * we're able to distribute inbound packets to multiple
22663 			 * zones who share a broadcast address. We avoid looping
22664 			 * back outbound packets in different zones but on the
22665 			 * same ill, as the application would see duplicates.
22666 			 *
22667 			 * If the interfaces are part of the same group,
22668 			 * we would want to send only one copy out for
22669 			 * whole group.
22670 			 *
22671 			 * This logic assumes that ire_add_v4() groups the
22672 			 * IRE_BROADCAST entries so that those with the same
22673 			 * ire_addr and ill_group are kept together.
22674 			 */
22675 			ire_ill = ire->ire_ipif->ipif_ill;
22676 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
22677 				if (ire_ill->ill_group != NULL &&
22678 				    (ire->ire_marks & IRE_MARK_NORECV)) {
22679 					/*
22680 					 * If the current zone only has an ire
22681 					 * broadcast for this address marked
22682 					 * NORECV, the ire we want is ahead in
22683 					 * the bucket, so we look it up
22684 					 * deliberately ignoring the zoneid.
22685 					 */
22686 					for (ire1 = ire->ire_bucket->irb_ire;
22687 					    ire1 != NULL;
22688 					    ire1 = ire1->ire_next) {
22689 						ire1_ill =
22690 						    ire1->ire_ipif->ipif_ill;
22691 						if (ire1->ire_addr != dst)
22692 							continue;
22693 						/* skip over the current ire */
22694 						if (ire1 == ire)
22695 							continue;
22696 						/* skip over deleted ires */
22697 						if (ire1->ire_marks &
22698 						    IRE_MARK_CONDEMNED)
22699 							continue;
22700 						/*
22701 						 * non-loopback ire in our
22702 						 * group: use it for the next
22703 						 * pass in the loop
22704 						 */
22705 						if (ire1->ire_stq != NULL &&
22706 						    ire1_ill->ill_group ==
22707 						    ire_ill->ill_group)
22708 							break;
22709 					}
22710 				}
22711 			} else {
22712 				while (ire1 != NULL && ire1->ire_addr == dst) {
22713 					ire1_ill = ire1->ire_ipif->ipif_ill;
22714 					/*
22715 					 * We can have two broadcast ires on the
22716 					 * same ill in different zones; here
22717 					 * we'll send a copy of the packet on
22718 					 * each ill and the fanout code will
22719 					 * call conn_wantpacket() to check that
22720 					 * the zone has the broadcast address
22721 					 * configured on the ill. If the two
22722 					 * ires are in the same group we only
22723 					 * send one copy up.
22724 					 */
22725 					if (ire1_ill != ire_ill &&
22726 					    (ire1_ill->ill_group == NULL ||
22727 					    ire_ill->ill_group == NULL ||
22728 					    ire1_ill->ill_group !=
22729 					    ire_ill->ill_group)) {
22730 						break;
22731 					}
22732 					ire1 = ire1->ire_next;
22733 				}
22734 			}
22735 		}
22736 		ASSERT(multirt_send == B_FALSE);
22737 		if (ire1 != NULL && ire1->ire_addr == dst) {
22738 			if ((ire->ire_flags & RTF_MULTIRT) &&
22739 			    (ire1->ire_flags & RTF_MULTIRT)) {
22740 				/*
22741 				 * We are in the multirouting case.
22742 				 * The message must be sent at least
22743 				 * on both ires. These ires have been
22744 				 * inserted AFTER the standard ones
22745 				 * in ip_rt_add(). There are thus no
22746 				 * other ire entries for the destination
22747 				 * address in the rest of the bucket
22748 				 * that do not have the RTF_MULTIRT
22749 				 * flag. We don't process a copy
22750 				 * of the message here. This will be
22751 				 * done in the final sending loop.
22752 				 */
22753 				multirt_send = B_TRUE;
22754 			} else {
22755 				next_mp = ip_copymsg(first_mp);
22756 				if (next_mp != NULL)
22757 					IRE_REFHOLD(ire1);
22758 			}
22759 		}
22760 		rw_exit(&ire->ire_bucket->irb_lock);
22761 	}
22762 
22763 	if (stq) {
22764 		/*
22765 		 * A non-NULL send-to queue means this packet is going
22766 		 * out of this machine.
22767 		 */
22768 		out_ill = (ill_t *)stq->q_ptr;
22769 
22770 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
22771 		ttl_protocol = ((uint16_t *)ipha)[4];
22772 		/*
22773 		 * We accumulate the pseudo header checksum in cksum.
22774 		 * This is pretty hairy code, so watch close.  One
22775 		 * thing to keep in mind is that UDP and TCP have
22776 		 * stored their respective datagram lengths in their
22777 		 * checksum fields.  This lines things up real nice.
22778 		 */
22779 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22780 		    (src >> 16) + (src & 0xFFFF);
22781 		/*
22782 		 * We assume the udp checksum field contains the
22783 		 * length, so to compute the pseudo header checksum,
22784 		 * all we need is the protocol number and src/dst.
22785 		 */
22786 		/* Provide the checksums for UDP and TCP. */
22787 		if ((PROTO == IPPROTO_TCP) &&
22788 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22789 			/* hlen gets the number of uchar_ts in the IP header */
22790 			hlen = (V_HLEN & 0xF) << 2;
22791 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22792 			IP_STAT(ipst, ip_out_sw_cksum);
22793 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22794 			    LENGTH - hlen);
22795 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22796 		} else if (PROTO == IPPROTO_SCTP &&
22797 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22798 			sctp_hdr_t	*sctph;
22799 
22800 			hlen = (V_HLEN & 0xF) << 2;
22801 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22802 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22803 			sctph->sh_chksum = 0;
22804 #ifdef	DEBUG
22805 			if (!skip_sctp_cksum)
22806 #endif
22807 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22808 		} else {
22809 			queue_t *dev_q = stq->q_next;
22810 
22811 			if ((dev_q->q_next || dev_q->q_first) &&
22812 			    !canput(dev_q)) {
22813 blocked:
22814 				ipha->ipha_ident = ip_hdr_included;
22815 				/*
22816 				 * If we don't have a conn to apply
22817 				 * backpressure, free the message.
22818 				 * In the ire_send path, we don't know
22819 				 * the position to requeue the packet. Rather
22820 				 * than reorder packets, we just drop this
22821 				 * packet.
22822 				 */
22823 				if (ipst->ips_ip_output_queue &&
22824 				    connp != NULL &&
22825 				    caller != IRE_SEND) {
22826 					if (caller == IP_WSRV) {
22827 						connp->conn_did_putbq = 1;
22828 						(void) putbq(connp->conn_wq,
22829 						    first_mp);
22830 						conn_drain_insert(connp);
22831 						/*
22832 						 * This is the service thread,
22833 						 * and the queue is already
22834 						 * noenabled. The check for
22835 						 * canput and the putbq is not
22836 						 * atomic. So we need to check
22837 						 * again.
22838 						 */
22839 						if (canput(stq->q_next))
22840 							connp->conn_did_putbq
22841 							    = 0;
22842 						IP_STAT(ipst, ip_conn_flputbq);
22843 					} else {
22844 						/*
22845 						 * We are not the service proc.
22846 						 * ip_wsrv will be scheduled or
22847 						 * is already running.
22848 						 */
22849 						(void) putq(connp->conn_wq,
22850 						    first_mp);
22851 					}
22852 				} else {
22853 					out_ill = (ill_t *)stq->q_ptr;
22854 					BUMP_MIB(out_ill->ill_ip_mib,
22855 					    ipIfStatsOutDiscards);
22856 					freemsg(first_mp);
22857 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22858 					    "ip_wput_ire_end: q %p (%S)",
22859 					    q, "discard");
22860 				}
22861 				ire_refrele(ire);
22862 				if (next_mp) {
22863 					ire_refrele(ire1);
22864 					freemsg(next_mp);
22865 				}
22866 				if (conn_outgoing_ill != NULL)
22867 					ill_refrele(conn_outgoing_ill);
22868 				return;
22869 			}
22870 			if ((PROTO == IPPROTO_UDP) &&
22871 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
22872 				/*
22873 				 * hlen gets the number of uchar_ts in the
22874 				 * IP header
22875 				 */
22876 				hlen = (V_HLEN & 0xF) << 2;
22877 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22878 				max_frag = ire->ire_max_frag;
22879 				if (*up != 0) {
22880 					IP_CKSUM_XMIT(out_ill, ire, mp, ipha,
22881 					    up, PROTO, hlen, LENGTH, max_frag,
22882 					    ipsec_len, cksum);
22883 					/* Software checksum? */
22884 					if (DB_CKSUMFLAGS(mp) == 0) {
22885 						IP_STAT(ipst, ip_out_sw_cksum);
22886 						IP_STAT_UPDATE(ipst,
22887 						    ip_udp_out_sw_cksum_bytes,
22888 						    LENGTH - hlen);
22889 					}
22890 				}
22891 			}
22892 		}
22893 		/*
22894 		 * Need to do this even when fragmenting. The local
22895 		 * loopback can be done without computing checksums
22896 		 * but forwarding out other interface must be done
22897 		 * after the IP checksum (and ULP checksums) have been
22898 		 * computed.
22899 		 *
22900 		 * NOTE : multicast_forward is set only if this packet
22901 		 * originated from ip_wput. For packets originating from
22902 		 * ip_wput_multicast, it is not set.
22903 		 */
22904 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
22905 multi_loopback:
22906 			ip2dbg(("ip_wput: multicast, loop %d\n",
22907 			    conn_multicast_loop));
22908 
22909 			/*  Forget header checksum offload */
22910 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
22911 
22912 			/*
22913 			 * Local loopback of multicasts?  Check the
22914 			 * ill.
22915 			 *
22916 			 * Note that the loopback function will not come
22917 			 * in through ip_rput - it will only do the
22918 			 * client fanout thus we need to do an mforward
22919 			 * as well.  The is different from the BSD
22920 			 * logic.
22921 			 */
22922 			if (ill != NULL) {
22923 				ilm_t	*ilm;
22924 
22925 				ILM_WALKER_HOLD(ill);
22926 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
22927 				    ALL_ZONES);
22928 				ILM_WALKER_RELE(ill);
22929 				if (ilm != NULL) {
22930 					/*
22931 					 * Pass along the virtual output q.
22932 					 * ip_wput_local() will distribute the
22933 					 * packet to all the matching zones,
22934 					 * except the sending zone when
22935 					 * IP_MULTICAST_LOOP is false.
22936 					 */
22937 					ip_multicast_loopback(q, ill, first_mp,
22938 					    conn_multicast_loop ? 0 :
22939 					    IP_FF_NO_MCAST_LOOP, zoneid);
22940 				}
22941 			}
22942 			if (ipha->ipha_ttl == 0) {
22943 				/*
22944 				 * 0 => only to this host i.e. we are
22945 				 * done. We are also done if this was the
22946 				 * loopback interface since it is sufficient
22947 				 * to loopback one copy of a multicast packet.
22948 				 */
22949 				freemsg(first_mp);
22950 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22951 				    "ip_wput_ire_end: q %p (%S)",
22952 				    q, "loopback");
22953 				ire_refrele(ire);
22954 				if (conn_outgoing_ill != NULL)
22955 					ill_refrele(conn_outgoing_ill);
22956 				return;
22957 			}
22958 			/*
22959 			 * ILLF_MULTICAST is checked in ip_newroute
22960 			 * i.e. we don't need to check it here since
22961 			 * all IRE_CACHEs come from ip_newroute.
22962 			 * For multicast traffic, SO_DONTROUTE is interpreted
22963 			 * to mean only send the packet out the interface
22964 			 * (optionally specified with IP_MULTICAST_IF)
22965 			 * and do not forward it out additional interfaces.
22966 			 * RSVP and the rsvp daemon is an example of a
22967 			 * protocol and user level process that
22968 			 * handles it's own routing. Hence, it uses the
22969 			 * SO_DONTROUTE option to accomplish this.
22970 			 */
22971 
22972 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
22973 			    ill != NULL) {
22974 				/* Unconditionally redo the checksum */
22975 				ipha->ipha_hdr_checksum = 0;
22976 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22977 
22978 				/*
22979 				 * If this needs to go out secure, we need
22980 				 * to wait till we finish the IPsec
22981 				 * processing.
22982 				 */
22983 				if (ipsec_len == 0 &&
22984 				    ip_mforward(ill, ipha, mp)) {
22985 					freemsg(first_mp);
22986 					ip1dbg(("ip_wput: mforward failed\n"));
22987 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22988 					    "ip_wput_ire_end: q %p (%S)",
22989 					    q, "mforward failed");
22990 					ire_refrele(ire);
22991 					if (conn_outgoing_ill != NULL)
22992 						ill_refrele(conn_outgoing_ill);
22993 					return;
22994 				}
22995 			}
22996 		}
22997 		max_frag = ire->ire_max_frag;
22998 		cksum += ttl_protocol;
22999 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
23000 			/* No fragmentation required for this one. */
23001 			/*
23002 			 * Don't use frag_flag if packet is pre-built or source
23003 			 * routed or if multicast (since multicast packets do
23004 			 * not solicit ICMP "packet too big" messages).
23005 			 */
23006 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
23007 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
23008 			    !ip_source_route_included(ipha)) &&
23009 			    !CLASSD(ipha->ipha_dst))
23010 				ipha->ipha_fragment_offset_and_flags |=
23011 				    htons(ire->ire_frag_flag);
23012 
23013 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
23014 				/* Complete the IP header checksum. */
23015 				cksum += ipha->ipha_ident;
23016 				cksum += (v_hlen_tos_len >> 16)+
23017 				    (v_hlen_tos_len & 0xFFFF);
23018 				cksum += ipha->ipha_fragment_offset_and_flags;
23019 				hlen = (V_HLEN & 0xF) -
23020 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
23021 				if (hlen) {
23022 checksumoptions:
23023 					/*
23024 					 * Account for the IP Options in the IP
23025 					 * header checksum.
23026 					 */
23027 					up = (uint16_t *)(rptr+
23028 					    IP_SIMPLE_HDR_LENGTH);
23029 					do {
23030 						cksum += up[0];
23031 						cksum += up[1];
23032 						up += 2;
23033 					} while (--hlen);
23034 				}
23035 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
23036 				cksum = ~(cksum + (cksum >> 16));
23037 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
23038 			}
23039 			if (ipsec_len != 0) {
23040 				ipsec_out_process(q, first_mp, ire, ill_index);
23041 				if (!next_mp) {
23042 					ire_refrele(ire);
23043 					if (conn_outgoing_ill != NULL)
23044 						ill_refrele(conn_outgoing_ill);
23045 					return;
23046 				}
23047 				goto next;
23048 			}
23049 
23050 			/*
23051 			 * multirt_send has already been handled
23052 			 * for broadcast, but not yet for multicast
23053 			 * or IP options.
23054 			 */
23055 			if (next_mp == NULL) {
23056 				if (ire->ire_flags & RTF_MULTIRT) {
23057 					multirt_send = B_TRUE;
23058 				}
23059 			}
23060 
23061 			/*
23062 			 * In most cases, the emission loop below is
23063 			 * entered only once. Only in the case where
23064 			 * the ire holds the RTF_MULTIRT flag, do we loop
23065 			 * to process all RTF_MULTIRT ires in the bucket,
23066 			 * and send the packet through all crossed
23067 			 * RTF_MULTIRT routes.
23068 			 */
23069 			do {
23070 				if (multirt_send) {
23071 					irb_t *irb;
23072 
23073 					irb = ire->ire_bucket;
23074 					ASSERT(irb != NULL);
23075 					/*
23076 					 * We are in a multiple send case,
23077 					 * need to get the next IRE and make
23078 					 * a duplicate of the packet.
23079 					 */
23080 					IRB_REFHOLD(irb);
23081 					for (ire1 = ire->ire_next;
23082 					    ire1 != NULL;
23083 					    ire1 = ire1->ire_next) {
23084 						if (!(ire1->ire_flags &
23085 						    RTF_MULTIRT)) {
23086 							continue;
23087 						}
23088 						if (ire1->ire_addr !=
23089 						    ire->ire_addr) {
23090 							continue;
23091 						}
23092 						if (ire1->ire_marks &
23093 						    (IRE_MARK_CONDEMNED|
23094 						    IRE_MARK_HIDDEN)) {
23095 							continue;
23096 						}
23097 
23098 						/* Got one */
23099 						IRE_REFHOLD(ire1);
23100 						break;
23101 					}
23102 					IRB_REFRELE(irb);
23103 
23104 					if (ire1 != NULL) {
23105 						next_mp = copyb(mp);
23106 						if ((next_mp == NULL) ||
23107 						    ((mp->b_cont != NULL) &&
23108 						    ((next_mp->b_cont =
23109 						    dupmsg(mp->b_cont))
23110 						    == NULL))) {
23111 							freemsg(next_mp);
23112 							next_mp = NULL;
23113 							ire_refrele(ire1);
23114 							ire1 = NULL;
23115 						}
23116 					}
23117 
23118 					/*
23119 					 * Last multiroute ire; don't loop
23120 					 * anymore. The emission is over
23121 					 * and next_mp is NULL.
23122 					 */
23123 					if (ire1 == NULL) {
23124 						multirt_send = B_FALSE;
23125 					}
23126 				}
23127 
23128 				out_ill = ire_to_ill(ire);
23129 				DTRACE_PROBE4(ip4__physical__out__start,
23130 				    ill_t *, NULL,
23131 				    ill_t *, out_ill,
23132 				    ipha_t *, ipha, mblk_t *, mp);
23133 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23134 				    ipst->ips_ipv4firewall_physical_out,
23135 				    NULL, out_ill, ipha, mp, mp, ipst);
23136 				DTRACE_PROBE1(ip4__physical__out__end,
23137 				    mblk_t *, mp);
23138 				if (mp == NULL)
23139 					goto release_ire_and_ill_2;
23140 
23141 				ASSERT(ipsec_len == 0);
23142 				mp->b_prev =
23143 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23144 				DTRACE_PROBE2(ip__xmit__2,
23145 				    mblk_t *, mp, ire_t *, ire);
23146 				pktxmit_state = ip_xmit_v4(mp, ire,
23147 				    NULL, B_TRUE);
23148 				if ((pktxmit_state == SEND_FAILED) ||
23149 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23150 release_ire_and_ill_2:
23151 					if (next_mp) {
23152 						freemsg(next_mp);
23153 						ire_refrele(ire1);
23154 					}
23155 					ire_refrele(ire);
23156 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23157 					    "ip_wput_ire_end: q %p (%S)",
23158 					    q, "discard MDATA");
23159 					if (conn_outgoing_ill != NULL)
23160 						ill_refrele(conn_outgoing_ill);
23161 					return;
23162 				}
23163 
23164 				if (CLASSD(dst)) {
23165 					BUMP_MIB(out_ill->ill_ip_mib,
23166 					    ipIfStatsHCOutMcastPkts);
23167 					UPDATE_MIB(out_ill->ill_ip_mib,
23168 					    ipIfStatsHCOutMcastOctets,
23169 					    LENGTH);
23170 				} else if (ire->ire_type == IRE_BROADCAST) {
23171 					BUMP_MIB(out_ill->ill_ip_mib,
23172 					    ipIfStatsHCOutBcastPkts);
23173 				}
23174 
23175 				if (multirt_send) {
23176 					/*
23177 					 * We are in a multiple send case,
23178 					 * need to re-enter the sending loop
23179 					 * using the next ire.
23180 					 */
23181 					ire_refrele(ire);
23182 					ire = ire1;
23183 					stq = ire->ire_stq;
23184 					mp = next_mp;
23185 					next_mp = NULL;
23186 					ipha = (ipha_t *)mp->b_rptr;
23187 					ill_index = Q_TO_INDEX(stq);
23188 				}
23189 			} while (multirt_send);
23190 
23191 			if (!next_mp) {
23192 				/*
23193 				 * Last copy going out (the ultra-common
23194 				 * case).  Note that we intentionally replicate
23195 				 * the putnext rather than calling it before
23196 				 * the next_mp check in hopes of a little
23197 				 * tail-call action out of the compiler.
23198 				 */
23199 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23200 				    "ip_wput_ire_end: q %p (%S)",
23201 				    q, "last copy out(1)");
23202 				ire_refrele(ire);
23203 				if (conn_outgoing_ill != NULL)
23204 					ill_refrele(conn_outgoing_ill);
23205 				return;
23206 			}
23207 			/* More copies going out below. */
23208 		} else {
23209 			int offset;
23210 fragmentit:
23211 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23212 			/*
23213 			 * If this would generate a icmp_frag_needed message,
23214 			 * we need to handle it before we do the IPsec
23215 			 * processing. Otherwise, we need to strip the IPsec
23216 			 * headers before we send up the message to the ULPs
23217 			 * which becomes messy and difficult.
23218 			 */
23219 			if (ipsec_len != 0) {
23220 				if ((max_frag < (unsigned int)(LENGTH +
23221 				    ipsec_len)) && (offset & IPH_DF)) {
23222 					out_ill = (ill_t *)stq->q_ptr;
23223 					BUMP_MIB(out_ill->ill_ip_mib,
23224 					    ipIfStatsOutFragFails);
23225 					BUMP_MIB(out_ill->ill_ip_mib,
23226 					    ipIfStatsOutFragReqds);
23227 					ipha->ipha_hdr_checksum = 0;
23228 					ipha->ipha_hdr_checksum =
23229 					    (uint16_t)ip_csum_hdr(ipha);
23230 					icmp_frag_needed(ire->ire_stq, first_mp,
23231 					    max_frag, zoneid, ipst);
23232 					if (!next_mp) {
23233 						ire_refrele(ire);
23234 						if (conn_outgoing_ill != NULL) {
23235 							ill_refrele(
23236 							    conn_outgoing_ill);
23237 						}
23238 						return;
23239 					}
23240 				} else {
23241 					/*
23242 					 * This won't cause a icmp_frag_needed
23243 					 * message. to be generated. Send it on
23244 					 * the wire. Note that this could still
23245 					 * cause fragmentation and all we
23246 					 * do is the generation of the message
23247 					 * to the ULP if needed before IPsec.
23248 					 */
23249 					if (!next_mp) {
23250 						ipsec_out_process(q, first_mp,
23251 						    ire, ill_index);
23252 						TRACE_2(TR_FAC_IP,
23253 						    TR_IP_WPUT_IRE_END,
23254 						    "ip_wput_ire_end: q %p "
23255 						    "(%S)", q,
23256 						    "last ipsec_out_process");
23257 						ire_refrele(ire);
23258 						if (conn_outgoing_ill != NULL) {
23259 							ill_refrele(
23260 							    conn_outgoing_ill);
23261 						}
23262 						return;
23263 					}
23264 					ipsec_out_process(q, first_mp,
23265 					    ire, ill_index);
23266 				}
23267 			} else {
23268 				/*
23269 				 * Initiate IPPF processing. For
23270 				 * fragmentable packets we finish
23271 				 * all QOS packet processing before
23272 				 * calling:
23273 				 * ip_wput_ire_fragmentit->ip_wput_frag
23274 				 */
23275 
23276 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23277 					ip_process(IPP_LOCAL_OUT, &mp,
23278 					    ill_index);
23279 					if (mp == NULL) {
23280 						out_ill = (ill_t *)stq->q_ptr;
23281 						BUMP_MIB(out_ill->ill_ip_mib,
23282 						    ipIfStatsOutDiscards);
23283 						if (next_mp != NULL) {
23284 							freemsg(next_mp);
23285 							ire_refrele(ire1);
23286 						}
23287 						ire_refrele(ire);
23288 						TRACE_2(TR_FAC_IP,
23289 						    TR_IP_WPUT_IRE_END,
23290 						    "ip_wput_ire: q %p (%S)",
23291 						    q, "discard MDATA");
23292 						if (conn_outgoing_ill != NULL) {
23293 							ill_refrele(
23294 							    conn_outgoing_ill);
23295 						}
23296 						return;
23297 					}
23298 				}
23299 				if (!next_mp) {
23300 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23301 					    "ip_wput_ire_end: q %p (%S)",
23302 					    q, "last fragmentation");
23303 					ip_wput_ire_fragmentit(mp, ire,
23304 					    zoneid, ipst);
23305 					ire_refrele(ire);
23306 					if (conn_outgoing_ill != NULL)
23307 						ill_refrele(conn_outgoing_ill);
23308 					return;
23309 				}
23310 				ip_wput_ire_fragmentit(mp, ire, zoneid, ipst);
23311 			}
23312 		}
23313 	} else {
23314 nullstq:
23315 		/* A NULL stq means the destination address is local. */
23316 		UPDATE_OB_PKT_COUNT(ire);
23317 		ire->ire_last_used_time = lbolt;
23318 		ASSERT(ire->ire_ipif != NULL);
23319 		if (!next_mp) {
23320 			/*
23321 			 * Is there an "in" and "out" for traffic local
23322 			 * to a host (loopback)?  The code in Solaris doesn't
23323 			 * explicitly draw a line in its code for in vs out,
23324 			 * so we've had to draw a line in the sand: ip_wput_ire
23325 			 * is considered to be the "output" side and
23326 			 * ip_wput_local to be the "input" side.
23327 			 */
23328 			out_ill = ire_to_ill(ire);
23329 
23330 			DTRACE_PROBE4(ip4__loopback__out__start,
23331 			    ill_t *, NULL, ill_t *, out_ill,
23332 			    ipha_t *, ipha, mblk_t *, first_mp);
23333 
23334 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23335 			    ipst->ips_ipv4firewall_loopback_out,
23336 			    NULL, out_ill, ipha, first_mp, mp, ipst);
23337 
23338 			DTRACE_PROBE1(ip4__loopback__out_end,
23339 			    mblk_t *, first_mp);
23340 
23341 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23342 			    "ip_wput_ire_end: q %p (%S)",
23343 			    q, "local address");
23344 
23345 			if (first_mp != NULL)
23346 				ip_wput_local(q, out_ill, ipha,
23347 				    first_mp, ire, 0, ire->ire_zoneid);
23348 			ire_refrele(ire);
23349 			if (conn_outgoing_ill != NULL)
23350 				ill_refrele(conn_outgoing_ill);
23351 			return;
23352 		}
23353 
23354 		out_ill = ire_to_ill(ire);
23355 
23356 		DTRACE_PROBE4(ip4__loopback__out__start,
23357 		    ill_t *, NULL, ill_t *, out_ill,
23358 		    ipha_t *, ipha, mblk_t *, first_mp);
23359 
23360 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23361 		    ipst->ips_ipv4firewall_loopback_out,
23362 		    NULL, out_ill, ipha, first_mp, mp, ipst);
23363 
23364 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23365 
23366 		if (first_mp != NULL)
23367 			ip_wput_local(q, out_ill, ipha,
23368 			    first_mp, ire, 0, ire->ire_zoneid);
23369 	}
23370 next:
23371 	/*
23372 	 * More copies going out to additional interfaces.
23373 	 * ire1 has already been held. We don't need the
23374 	 * "ire" anymore.
23375 	 */
23376 	ire_refrele(ire);
23377 	ire = ire1;
23378 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23379 	mp = next_mp;
23380 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23381 	ill = ire_to_ill(ire);
23382 	first_mp = mp;
23383 	if (ipsec_len != 0) {
23384 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23385 		mp = mp->b_cont;
23386 	}
23387 	dst = ire->ire_addr;
23388 	ipha = (ipha_t *)mp->b_rptr;
23389 	/*
23390 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23391 	 * Restore ipha_ident "no checksum" flag.
23392 	 */
23393 	src = orig_src;
23394 	ipha->ipha_ident = ip_hdr_included;
23395 	goto another;
23396 
23397 #undef	rptr
23398 #undef	Q_TO_INDEX
23399 }
23400 
23401 /*
23402  * Routine to allocate a message that is used to notify the ULP about MDT.
23403  * The caller may provide a pointer to the link-layer MDT capabilities,
23404  * or NULL if MDT is to be disabled on the stream.
23405  */
23406 mblk_t *
23407 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23408 {
23409 	mblk_t *mp;
23410 	ip_mdt_info_t *mdti;
23411 	ill_mdt_capab_t *idst;
23412 
23413 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23414 		DB_TYPE(mp) = M_CTL;
23415 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23416 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23417 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23418 		idst = &(mdti->mdt_capab);
23419 
23420 		/*
23421 		 * If the caller provides us with the capability, copy
23422 		 * it over into our notification message; otherwise
23423 		 * we zero out the capability portion.
23424 		 */
23425 		if (isrc != NULL)
23426 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23427 		else
23428 			bzero((caddr_t)idst, sizeof (*idst));
23429 	}
23430 	return (mp);
23431 }
23432 
23433 /*
23434  * Routine which determines whether MDT can be enabled on the destination
23435  * IRE and IPC combination, and if so, allocates and returns the MDT
23436  * notification mblk that may be used by ULP.  We also check if we need to
23437  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23438  * MDT usage in the past have been lifted.  This gets called during IP
23439  * and ULP binding.
23440  */
23441 mblk_t *
23442 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23443     ill_mdt_capab_t *mdt_cap)
23444 {
23445 	mblk_t *mp;
23446 	boolean_t rc = B_FALSE;
23447 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23448 
23449 	ASSERT(dst_ire != NULL);
23450 	ASSERT(connp != NULL);
23451 	ASSERT(mdt_cap != NULL);
23452 
23453 	/*
23454 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23455 	 * Multidata, which is handled in tcp_multisend().  This
23456 	 * is the reason why we do all these checks here, to ensure
23457 	 * that we don't enable Multidata for the cases which we
23458 	 * can't handle at the moment.
23459 	 */
23460 	do {
23461 		/* Only do TCP at the moment */
23462 		if (connp->conn_ulp != IPPROTO_TCP)
23463 			break;
23464 
23465 		/*
23466 		 * IPsec outbound policy present?  Note that we get here
23467 		 * after calling ipsec_conn_cache_policy() where the global
23468 		 * policy checking is performed.  conn_latch will be
23469 		 * non-NULL as long as there's a policy defined,
23470 		 * i.e. conn_out_enforce_policy may be NULL in such case
23471 		 * when the connection is non-secure, and hence we check
23472 		 * further if the latch refers to an outbound policy.
23473 		 */
23474 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23475 			break;
23476 
23477 		/* CGTP (multiroute) is enabled? */
23478 		if (dst_ire->ire_flags & RTF_MULTIRT)
23479 			break;
23480 
23481 		/* Outbound IPQoS enabled? */
23482 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23483 			/*
23484 			 * In this case, we disable MDT for this and all
23485 			 * future connections going over the interface.
23486 			 */
23487 			mdt_cap->ill_mdt_on = 0;
23488 			break;
23489 		}
23490 
23491 		/* socket option(s) present? */
23492 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23493 			break;
23494 
23495 		rc = B_TRUE;
23496 	/* CONSTCOND */
23497 	} while (0);
23498 
23499 	/* Remember the result */
23500 	connp->conn_mdt_ok = rc;
23501 
23502 	if (!rc)
23503 		return (NULL);
23504 	else if (!mdt_cap->ill_mdt_on) {
23505 		/*
23506 		 * If MDT has been previously turned off in the past, and we
23507 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23508 		 * then enable it for this interface.
23509 		 */
23510 		mdt_cap->ill_mdt_on = 1;
23511 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23512 		    "interface %s\n", ill_name));
23513 	}
23514 
23515 	/* Allocate the MDT info mblk */
23516 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23517 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23518 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23519 		return (NULL);
23520 	}
23521 	return (mp);
23522 }
23523 
23524 /*
23525  * Routine to allocate a message that is used to notify the ULP about LSO.
23526  * The caller may provide a pointer to the link-layer LSO capabilities,
23527  * or NULL if LSO is to be disabled on the stream.
23528  */
23529 mblk_t *
23530 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23531 {
23532 	mblk_t *mp;
23533 	ip_lso_info_t *lsoi;
23534 	ill_lso_capab_t *idst;
23535 
23536 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23537 		DB_TYPE(mp) = M_CTL;
23538 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23539 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23540 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23541 		idst = &(lsoi->lso_capab);
23542 
23543 		/*
23544 		 * If the caller provides us with the capability, copy
23545 		 * it over into our notification message; otherwise
23546 		 * we zero out the capability portion.
23547 		 */
23548 		if (isrc != NULL)
23549 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23550 		else
23551 			bzero((caddr_t)idst, sizeof (*idst));
23552 	}
23553 	return (mp);
23554 }
23555 
23556 /*
23557  * Routine which determines whether LSO can be enabled on the destination
23558  * IRE and IPC combination, and if so, allocates and returns the LSO
23559  * notification mblk that may be used by ULP.  We also check if we need to
23560  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23561  * LSO usage in the past have been lifted.  This gets called during IP
23562  * and ULP binding.
23563  */
23564 mblk_t *
23565 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23566     ill_lso_capab_t *lso_cap)
23567 {
23568 	mblk_t *mp;
23569 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23570 
23571 	ASSERT(dst_ire != NULL);
23572 	ASSERT(connp != NULL);
23573 	ASSERT(lso_cap != NULL);
23574 
23575 	connp->conn_lso_ok = B_TRUE;
23576 
23577 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23578 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23579 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23580 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23581 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23582 		connp->conn_lso_ok = B_FALSE;
23583 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23584 			/*
23585 			 * Disable LSO for this and all future connections going
23586 			 * over the interface.
23587 			 */
23588 			lso_cap->ill_lso_on = 0;
23589 		}
23590 	}
23591 
23592 	if (!connp->conn_lso_ok)
23593 		return (NULL);
23594 	else if (!lso_cap->ill_lso_on) {
23595 		/*
23596 		 * If LSO has been previously turned off in the past, and we
23597 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23598 		 * then enable it for this interface.
23599 		 */
23600 		lso_cap->ill_lso_on = 1;
23601 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23602 		    ill_name));
23603 	}
23604 
23605 	/* Allocate the LSO info mblk */
23606 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23607 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23608 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23609 
23610 	return (mp);
23611 }
23612 
23613 /*
23614  * Create destination address attribute, and fill it with the physical
23615  * destination address and SAP taken from the template DL_UNITDATA_REQ
23616  * message block.
23617  */
23618 boolean_t
23619 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23620 {
23621 	dl_unitdata_req_t *dlurp;
23622 	pattr_t *pa;
23623 	pattrinfo_t pa_info;
23624 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23625 	uint_t das_len, das_off;
23626 
23627 	ASSERT(dlmp != NULL);
23628 
23629 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23630 	das_len = dlurp->dl_dest_addr_length;
23631 	das_off = dlurp->dl_dest_addr_offset;
23632 
23633 	pa_info.type = PATTR_DSTADDRSAP;
23634 	pa_info.len = sizeof (**das) + das_len - 1;
23635 
23636 	/* create and associate the attribute */
23637 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23638 	if (pa != NULL) {
23639 		ASSERT(*das != NULL);
23640 		(*das)->addr_is_group = 0;
23641 		(*das)->addr_len = (uint8_t)das_len;
23642 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23643 	}
23644 
23645 	return (pa != NULL);
23646 }
23647 
23648 /*
23649  * Create hardware checksum attribute and fill it with the values passed.
23650  */
23651 boolean_t
23652 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23653     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23654 {
23655 	pattr_t *pa;
23656 	pattrinfo_t pa_info;
23657 
23658 	ASSERT(mmd != NULL);
23659 
23660 	pa_info.type = PATTR_HCKSUM;
23661 	pa_info.len = sizeof (pattr_hcksum_t);
23662 
23663 	/* create and associate the attribute */
23664 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23665 	if (pa != NULL) {
23666 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23667 
23668 		hck->hcksum_start_offset = start_offset;
23669 		hck->hcksum_stuff_offset = stuff_offset;
23670 		hck->hcksum_end_offset = end_offset;
23671 		hck->hcksum_flags = flags;
23672 	}
23673 	return (pa != NULL);
23674 }
23675 
23676 /*
23677  * Create zerocopy attribute and fill it with the specified flags
23678  */
23679 boolean_t
23680 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23681 {
23682 	pattr_t *pa;
23683 	pattrinfo_t pa_info;
23684 
23685 	ASSERT(mmd != NULL);
23686 	pa_info.type = PATTR_ZCOPY;
23687 	pa_info.len = sizeof (pattr_zcopy_t);
23688 
23689 	/* create and associate the attribute */
23690 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23691 	if (pa != NULL) {
23692 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23693 
23694 		zcopy->zcopy_flags = flags;
23695 	}
23696 	return (pa != NULL);
23697 }
23698 
23699 /*
23700  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23701  * block chain. We could rewrite to handle arbitrary message block chains but
23702  * that would make the code complicated and slow. Right now there three
23703  * restrictions:
23704  *
23705  *   1. The first message block must contain the complete IP header and
23706  *	at least 1 byte of payload data.
23707  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23708  *	so that we can use a single Multidata message.
23709  *   3. No frag must be distributed over two or more message blocks so
23710  *	that we don't need more than two packet descriptors per frag.
23711  *
23712  * The above restrictions allow us to support userland applications (which
23713  * will send down a single message block) and NFS over UDP (which will
23714  * send down a chain of at most three message blocks).
23715  *
23716  * We also don't use MDT for payloads with less than or equal to
23717  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23718  */
23719 boolean_t
23720 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23721 {
23722 	int	blocks;
23723 	ssize_t	total, missing, size;
23724 
23725 	ASSERT(mp != NULL);
23726 	ASSERT(hdr_len > 0);
23727 
23728 	size = MBLKL(mp) - hdr_len;
23729 	if (size <= 0)
23730 		return (B_FALSE);
23731 
23732 	/* The first mblk contains the header and some payload. */
23733 	blocks = 1;
23734 	total = size;
23735 	size %= len;
23736 	missing = (size == 0) ? 0 : (len - size);
23737 	mp = mp->b_cont;
23738 
23739 	while (mp != NULL) {
23740 		/*
23741 		 * Give up if we encounter a zero length message block.
23742 		 * In practice, this should rarely happen and therefore
23743 		 * not worth the trouble of freeing and re-linking the
23744 		 * mblk from the chain to handle such case.
23745 		 */
23746 		if ((size = MBLKL(mp)) == 0)
23747 			return (B_FALSE);
23748 
23749 		/* Too many payload buffers for a single Multidata message? */
23750 		if (++blocks > MULTIDATA_MAX_PBUFS)
23751 			return (B_FALSE);
23752 
23753 		total += size;
23754 		/* Is a frag distributed over two or more message blocks? */
23755 		if (missing > size)
23756 			return (B_FALSE);
23757 		size -= missing;
23758 
23759 		size %= len;
23760 		missing = (size == 0) ? 0 : (len - size);
23761 
23762 		mp = mp->b_cont;
23763 	}
23764 
23765 	return (total > ip_wput_frag_mdt_min);
23766 }
23767 
23768 /*
23769  * Outbound IPv4 fragmentation routine using MDT.
23770  */
23771 static void
23772 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23773     uint32_t frag_flag, int offset)
23774 {
23775 	ipha_t		*ipha_orig;
23776 	int		i1, ip_data_end;
23777 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23778 	mblk_t		*hdr_mp, *md_mp = NULL;
23779 	unsigned char	*hdr_ptr, *pld_ptr;
23780 	multidata_t	*mmd;
23781 	ip_pdescinfo_t	pdi;
23782 	ill_t		*ill;
23783 	ip_stack_t	*ipst = ire->ire_ipst;
23784 
23785 	ASSERT(DB_TYPE(mp) == M_DATA);
23786 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23787 
23788 	ill = ire_to_ill(ire);
23789 	ASSERT(ill != NULL);
23790 
23791 	ipha_orig = (ipha_t *)mp->b_rptr;
23792 	mp->b_rptr += sizeof (ipha_t);
23793 
23794 	/* Calculate how many packets we will send out */
23795 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
23796 	pkts = (i1 + len - 1) / len;
23797 	ASSERT(pkts > 1);
23798 
23799 	/* Allocate a message block which will hold all the IP Headers. */
23800 	wroff = ipst->ips_ip_wroff_extra;
23801 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
23802 
23803 	i1 = pkts * hdr_chunk_len;
23804 	/*
23805 	 * Create the header buffer, Multidata and destination address
23806 	 * and SAP attribute that should be associated with it.
23807 	 */
23808 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
23809 	    ((hdr_mp->b_wptr += i1),
23810 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
23811 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
23812 		freemsg(mp);
23813 		if (md_mp == NULL) {
23814 			freemsg(hdr_mp);
23815 		} else {
23816 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
23817 			freemsg(md_mp);
23818 		}
23819 		IP_STAT(ipst, ip_frag_mdt_allocfail);
23820 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
23821 		return;
23822 	}
23823 	IP_STAT(ipst, ip_frag_mdt_allocd);
23824 
23825 	/*
23826 	 * Add a payload buffer to the Multidata; this operation must not
23827 	 * fail, or otherwise our logic in this routine is broken.  There
23828 	 * is no memory allocation done by the routine, so any returned
23829 	 * failure simply tells us that we've done something wrong.
23830 	 *
23831 	 * A failure tells us that either we're adding the same payload
23832 	 * buffer more than once, or we're trying to add more buffers than
23833 	 * allowed.  None of the above cases should happen, and we panic
23834 	 * because either there's horrible heap corruption, and/or
23835 	 * programming mistake.
23836 	 */
23837 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23838 		goto pbuf_panic;
23839 
23840 	hdr_ptr = hdr_mp->b_rptr;
23841 	pld_ptr = mp->b_rptr;
23842 
23843 	/* Establish the ending byte offset, based on the starting offset. */
23844 	offset <<= 3;
23845 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
23846 	    IP_SIMPLE_HDR_LENGTH;
23847 
23848 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
23849 
23850 	while (pld_ptr < mp->b_wptr) {
23851 		ipha_t		*ipha;
23852 		uint16_t	offset_and_flags;
23853 		uint16_t	ip_len;
23854 		int		error;
23855 
23856 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
23857 		ipha = (ipha_t *)(hdr_ptr + wroff);
23858 		ASSERT(OK_32PTR(ipha));
23859 		*ipha = *ipha_orig;
23860 
23861 		if (ip_data_end - offset > len) {
23862 			offset_and_flags = IPH_MF;
23863 		} else {
23864 			/*
23865 			 * Last frag. Set len to the length of this last piece.
23866 			 */
23867 			len = ip_data_end - offset;
23868 			/* A frag of a frag might have IPH_MF non-zero */
23869 			offset_and_flags =
23870 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23871 			    IPH_MF;
23872 		}
23873 		offset_and_flags |= (uint16_t)(offset >> 3);
23874 		offset_and_flags |= (uint16_t)frag_flag;
23875 		/* Store the offset and flags in the IP header. */
23876 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23877 
23878 		/* Store the length in the IP header. */
23879 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
23880 		ipha->ipha_length = htons(ip_len);
23881 
23882 		/*
23883 		 * Set the IP header checksum.  Note that mp is just
23884 		 * the header, so this is easy to pass to ip_csum.
23885 		 */
23886 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23887 
23888 		/*
23889 		 * Record offset and size of header and data of the next packet
23890 		 * in the multidata message.
23891 		 */
23892 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
23893 		PDESC_PLD_INIT(&pdi);
23894 		i1 = MIN(mp->b_wptr - pld_ptr, len);
23895 		ASSERT(i1 > 0);
23896 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
23897 		if (i1 == len) {
23898 			pld_ptr += len;
23899 		} else {
23900 			i1 = len - i1;
23901 			mp = mp->b_cont;
23902 			ASSERT(mp != NULL);
23903 			ASSERT(MBLKL(mp) >= i1);
23904 			/*
23905 			 * Attach the next payload message block to the
23906 			 * multidata message.
23907 			 */
23908 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23909 				goto pbuf_panic;
23910 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
23911 			pld_ptr = mp->b_rptr + i1;
23912 		}
23913 
23914 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
23915 		    KM_NOSLEEP)) == NULL) {
23916 			/*
23917 			 * Any failure other than ENOMEM indicates that we
23918 			 * have passed in invalid pdesc info or parameters
23919 			 * to mmd_addpdesc, which must not happen.
23920 			 *
23921 			 * EINVAL is a result of failure on boundary checks
23922 			 * against the pdesc info contents.  It should not
23923 			 * happen, and we panic because either there's
23924 			 * horrible heap corruption, and/or programming
23925 			 * mistake.
23926 			 */
23927 			if (error != ENOMEM) {
23928 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
23929 				    "pdesc logic error detected for "
23930 				    "mmd %p pinfo %p (%d)\n",
23931 				    (void *)mmd, (void *)&pdi, error);
23932 				/* NOTREACHED */
23933 			}
23934 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
23935 			/* Free unattached payload message blocks as well */
23936 			md_mp->b_cont = mp->b_cont;
23937 			goto free_mmd;
23938 		}
23939 
23940 		/* Advance fragment offset. */
23941 		offset += len;
23942 
23943 		/* Advance to location for next header in the buffer. */
23944 		hdr_ptr += hdr_chunk_len;
23945 
23946 		/* Did we reach the next payload message block? */
23947 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
23948 			mp = mp->b_cont;
23949 			/*
23950 			 * Attach the next message block with payload
23951 			 * data to the multidata message.
23952 			 */
23953 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23954 				goto pbuf_panic;
23955 			pld_ptr = mp->b_rptr;
23956 		}
23957 	}
23958 
23959 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
23960 	ASSERT(mp->b_wptr == pld_ptr);
23961 
23962 	/* Update IP statistics */
23963 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
23964 
23965 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
23966 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
23967 
23968 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
23969 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
23970 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
23971 
23972 	if (pkt_type == OB_PKT) {
23973 		ire->ire_ob_pkt_count += pkts;
23974 		if (ire->ire_ipif != NULL)
23975 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
23976 	} else {
23977 		/* The type is IB_PKT in the forwarding path. */
23978 		ire->ire_ib_pkt_count += pkts;
23979 		ASSERT(!IRE_IS_LOCAL(ire));
23980 		if (ire->ire_type & IRE_BROADCAST) {
23981 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
23982 		} else {
23983 			UPDATE_MIB(ill->ill_ip_mib,
23984 			    ipIfStatsHCOutForwDatagrams, pkts);
23985 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
23986 		}
23987 	}
23988 	ire->ire_last_used_time = lbolt;
23989 	/* Send it down */
23990 	putnext(ire->ire_stq, md_mp);
23991 	return;
23992 
23993 pbuf_panic:
23994 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
23995 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
23996 	    pbuf_idx);
23997 	/* NOTREACHED */
23998 }
23999 
24000 /*
24001  * Outbound IP fragmentation routine.
24002  *
24003  * NOTE : This routine does not ire_refrele the ire that is passed in
24004  * as the argument.
24005  */
24006 static void
24007 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
24008     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst)
24009 {
24010 	int		i1;
24011 	mblk_t		*ll_hdr_mp;
24012 	int 		ll_hdr_len;
24013 	int		hdr_len;
24014 	mblk_t		*hdr_mp;
24015 	ipha_t		*ipha;
24016 	int		ip_data_end;
24017 	int		len;
24018 	mblk_t		*mp = mp_orig, *mp1;
24019 	int		offset;
24020 	queue_t		*q;
24021 	uint32_t	v_hlen_tos_len;
24022 	mblk_t		*first_mp;
24023 	boolean_t	mctl_present;
24024 	ill_t		*ill;
24025 	ill_t		*out_ill;
24026 	mblk_t		*xmit_mp;
24027 	mblk_t		*carve_mp;
24028 	ire_t		*ire1 = NULL;
24029 	ire_t		*save_ire = NULL;
24030 	mblk_t  	*next_mp = NULL;
24031 	boolean_t	last_frag = B_FALSE;
24032 	boolean_t	multirt_send = B_FALSE;
24033 	ire_t		*first_ire = NULL;
24034 	irb_t		*irb = NULL;
24035 	mib2_ipIfStatsEntry_t *mibptr = NULL;
24036 
24037 	ill = ire_to_ill(ire);
24038 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
24039 
24040 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
24041 
24042 	if (max_frag == 0) {
24043 		ip1dbg(("ip_wput_frag: ire frag size is 0"
24044 		    " -  dropping packet\n"));
24045 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24046 		freemsg(mp);
24047 		return;
24048 	}
24049 
24050 	/*
24051 	 * IPsec does not allow hw accelerated packets to be fragmented
24052 	 * This check is made in ip_wput_ipsec_out prior to coming here
24053 	 * via ip_wput_ire_fragmentit.
24054 	 *
24055 	 * If at this point we have an ire whose ARP request has not
24056 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24057 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24058 	 * This packet and all fragmentable packets for this ire will
24059 	 * continue to get dropped while ire_nce->nce_state remains in
24060 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24061 	 * ND_REACHABLE, all subsquent large packets for this ire will
24062 	 * get fragemented and sent out by this function.
24063 	 */
24064 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24065 		/* If nce_state is ND_INITIAL, trigger ARP query */
24066 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
24067 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24068 		    " -  dropping packet\n"));
24069 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24070 		freemsg(mp);
24071 		return;
24072 	}
24073 
24074 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24075 	    "ip_wput_frag_start:");
24076 
24077 	if (mp->b_datap->db_type == M_CTL) {
24078 		first_mp = mp;
24079 		mp_orig = mp = mp->b_cont;
24080 		mctl_present = B_TRUE;
24081 	} else {
24082 		first_mp = mp;
24083 		mctl_present = B_FALSE;
24084 	}
24085 
24086 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24087 	ipha = (ipha_t *)mp->b_rptr;
24088 
24089 	/*
24090 	 * If the Don't Fragment flag is on, generate an ICMP destination
24091 	 * unreachable, fragmentation needed.
24092 	 */
24093 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24094 	if (offset & IPH_DF) {
24095 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24096 		if (is_system_labeled()) {
24097 			max_frag = tsol_pmtu_adjust(mp, ire->ire_max_frag,
24098 			    ire->ire_max_frag - max_frag, AF_INET);
24099 		}
24100 		/*
24101 		 * Need to compute hdr checksum if called from ip_wput_ire.
24102 		 * Note that ip_rput_forward verifies the checksum before
24103 		 * calling this routine so in that case this is a noop.
24104 		 */
24105 		ipha->ipha_hdr_checksum = 0;
24106 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24107 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24108 		    ipst);
24109 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24110 		    "ip_wput_frag_end:(%S)",
24111 		    "don't fragment");
24112 		return;
24113 	}
24114 	/*
24115 	 * Labeled systems adjust max_frag if they add a label
24116 	 * to send the correct path mtu.  We need the real mtu since we
24117 	 * are fragmenting the packet after label adjustment.
24118 	 */
24119 	if (is_system_labeled())
24120 		max_frag = ire->ire_max_frag;
24121 	if (mctl_present)
24122 		freeb(first_mp);
24123 	/*
24124 	 * Establish the starting offset.  May not be zero if we are fragging
24125 	 * a fragment that is being forwarded.
24126 	 */
24127 	offset = offset & IPH_OFFSET;
24128 
24129 	/* TODO why is this test needed? */
24130 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24131 	if (((max_frag - LENGTH) & ~7) < 8) {
24132 		/* TODO: notify ulp somehow */
24133 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24134 		freemsg(mp);
24135 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24136 		    "ip_wput_frag_end:(%S)",
24137 		    "len < 8");
24138 		return;
24139 	}
24140 
24141 	hdr_len = (V_HLEN & 0xF) << 2;
24142 
24143 	ipha->ipha_hdr_checksum = 0;
24144 
24145 	/*
24146 	 * Establish the number of bytes maximum per frag, after putting
24147 	 * in the header.
24148 	 */
24149 	len = (max_frag - hdr_len) & ~7;
24150 
24151 	/* Check if we can use MDT to send out the frags. */
24152 	ASSERT(!IRE_IS_LOCAL(ire));
24153 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24154 	    ipst->ips_ip_multidata_outbound &&
24155 	    !(ire->ire_flags & RTF_MULTIRT) &&
24156 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24157 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24158 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24159 		ASSERT(ill->ill_mdt_capab != NULL);
24160 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24161 			/*
24162 			 * If MDT has been previously turned off in the past,
24163 			 * and we currently can do MDT (due to IPQoS policy
24164 			 * removal, etc.) then enable it for this interface.
24165 			 */
24166 			ill->ill_mdt_capab->ill_mdt_on = 1;
24167 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24168 			    ill->ill_name));
24169 		}
24170 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24171 		    offset);
24172 		return;
24173 	}
24174 
24175 	/* Get a copy of the header for the trailing frags */
24176 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst);
24177 	if (!hdr_mp) {
24178 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24179 		freemsg(mp);
24180 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24181 		    "ip_wput_frag_end:(%S)",
24182 		    "couldn't copy hdr");
24183 		return;
24184 	}
24185 	if (DB_CRED(mp) != NULL)
24186 		mblk_setcred(hdr_mp, DB_CRED(mp));
24187 
24188 	/* Store the starting offset, with the MoreFrags flag. */
24189 	i1 = offset | IPH_MF | frag_flag;
24190 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24191 
24192 	/* Establish the ending byte offset, based on the starting offset. */
24193 	offset <<= 3;
24194 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24195 
24196 	/* Store the length of the first fragment in the IP header. */
24197 	i1 = len + hdr_len;
24198 	ASSERT(i1 <= IP_MAXPACKET);
24199 	ipha->ipha_length = htons((uint16_t)i1);
24200 
24201 	/*
24202 	 * Compute the IP header checksum for the first frag.  We have to
24203 	 * watch out that we stop at the end of the header.
24204 	 */
24205 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24206 
24207 	/*
24208 	 * Now carve off the first frag.  Note that this will include the
24209 	 * original IP header.
24210 	 */
24211 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24212 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24213 		freeb(hdr_mp);
24214 		freemsg(mp_orig);
24215 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24216 		    "ip_wput_frag_end:(%S)",
24217 		    "couldn't carve first");
24218 		return;
24219 	}
24220 
24221 	/*
24222 	 * Multirouting case. Each fragment is replicated
24223 	 * via all non-condemned RTF_MULTIRT routes
24224 	 * currently resolved.
24225 	 * We ensure that first_ire is the first RTF_MULTIRT
24226 	 * ire in the bucket.
24227 	 */
24228 	if (ire->ire_flags & RTF_MULTIRT) {
24229 		irb = ire->ire_bucket;
24230 		ASSERT(irb != NULL);
24231 
24232 		multirt_send = B_TRUE;
24233 
24234 		/* Make sure we do not omit any multiroute ire. */
24235 		IRB_REFHOLD(irb);
24236 		for (first_ire = irb->irb_ire;
24237 		    first_ire != NULL;
24238 		    first_ire = first_ire->ire_next) {
24239 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24240 			    (first_ire->ire_addr == ire->ire_addr) &&
24241 			    !(first_ire->ire_marks &
24242 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
24243 				break;
24244 			}
24245 		}
24246 
24247 		if (first_ire != NULL) {
24248 			if (first_ire != ire) {
24249 				IRE_REFHOLD(first_ire);
24250 				/*
24251 				 * Do not release the ire passed in
24252 				 * as the argument.
24253 				 */
24254 				ire = first_ire;
24255 			} else {
24256 				first_ire = NULL;
24257 			}
24258 		}
24259 		IRB_REFRELE(irb);
24260 
24261 		/*
24262 		 * Save the first ire; we will need to restore it
24263 		 * for the trailing frags.
24264 		 * We REFHOLD save_ire, as each iterated ire will be
24265 		 * REFRELEd.
24266 		 */
24267 		save_ire = ire;
24268 		IRE_REFHOLD(save_ire);
24269 	}
24270 
24271 	/*
24272 	 * First fragment emission loop.
24273 	 * In most cases, the emission loop below is entered only
24274 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24275 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24276 	 * bucket, and send the fragment through all crossed
24277 	 * RTF_MULTIRT routes.
24278 	 */
24279 	do {
24280 		if (ire->ire_flags & RTF_MULTIRT) {
24281 			/*
24282 			 * We are in a multiple send case, need to get
24283 			 * the next ire and make a copy of the packet.
24284 			 * ire1 holds here the next ire to process in the
24285 			 * bucket. If multirouting is expected,
24286 			 * any non-RTF_MULTIRT ire that has the
24287 			 * right destination address is ignored.
24288 			 *
24289 			 * We have to take into account the MTU of
24290 			 * each walked ire. max_frag is set by the
24291 			 * the caller and generally refers to
24292 			 * the primary ire entry. Here we ensure that
24293 			 * no route with a lower MTU will be used, as
24294 			 * fragments are carved once for all ires,
24295 			 * then replicated.
24296 			 */
24297 			ASSERT(irb != NULL);
24298 			IRB_REFHOLD(irb);
24299 			for (ire1 = ire->ire_next;
24300 			    ire1 != NULL;
24301 			    ire1 = ire1->ire_next) {
24302 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24303 					continue;
24304 				if (ire1->ire_addr != ire->ire_addr)
24305 					continue;
24306 				if (ire1->ire_marks &
24307 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
24308 					continue;
24309 				/*
24310 				 * Ensure we do not exceed the MTU
24311 				 * of the next route.
24312 				 */
24313 				if (ire1->ire_max_frag < max_frag) {
24314 					ip_multirt_bad_mtu(ire1, max_frag);
24315 					continue;
24316 				}
24317 
24318 				/* Got one. */
24319 				IRE_REFHOLD(ire1);
24320 				break;
24321 			}
24322 			IRB_REFRELE(irb);
24323 
24324 			if (ire1 != NULL) {
24325 				next_mp = copyb(mp);
24326 				if ((next_mp == NULL) ||
24327 				    ((mp->b_cont != NULL) &&
24328 				    ((next_mp->b_cont =
24329 				    dupmsg(mp->b_cont)) == NULL))) {
24330 					freemsg(next_mp);
24331 					next_mp = NULL;
24332 					ire_refrele(ire1);
24333 					ire1 = NULL;
24334 				}
24335 			}
24336 
24337 			/* Last multiroute ire; don't loop anymore. */
24338 			if (ire1 == NULL) {
24339 				multirt_send = B_FALSE;
24340 			}
24341 		}
24342 
24343 		ll_hdr_len = 0;
24344 		LOCK_IRE_FP_MP(ire);
24345 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24346 		if (ll_hdr_mp != NULL) {
24347 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24348 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24349 		} else {
24350 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24351 		}
24352 
24353 		/* If there is a transmit header, get a copy for this frag. */
24354 		/*
24355 		 * TODO: should check db_ref before calling ip_carve_mp since
24356 		 * it might give us a dup.
24357 		 */
24358 		if (!ll_hdr_mp) {
24359 			/* No xmit header. */
24360 			xmit_mp = mp;
24361 
24362 		/* We have a link-layer header that can fit in our mblk. */
24363 		} else if (mp->b_datap->db_ref == 1 &&
24364 		    ll_hdr_len != 0 &&
24365 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24366 			/* M_DATA fastpath */
24367 			mp->b_rptr -= ll_hdr_len;
24368 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24369 			xmit_mp = mp;
24370 
24371 		/* Corner case if copyb has failed */
24372 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24373 			UNLOCK_IRE_FP_MP(ire);
24374 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24375 			freeb(hdr_mp);
24376 			freemsg(mp);
24377 			freemsg(mp_orig);
24378 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24379 			    "ip_wput_frag_end:(%S)",
24380 			    "discard");
24381 
24382 			if (multirt_send) {
24383 				ASSERT(ire1);
24384 				ASSERT(next_mp);
24385 
24386 				freemsg(next_mp);
24387 				ire_refrele(ire1);
24388 			}
24389 			if (save_ire != NULL)
24390 				IRE_REFRELE(save_ire);
24391 
24392 			if (first_ire != NULL)
24393 				ire_refrele(first_ire);
24394 			return;
24395 
24396 		/*
24397 		 * Case of res_mp OR the fastpath mp can't fit
24398 		 * in the mblk
24399 		 */
24400 		} else {
24401 			xmit_mp->b_cont = mp;
24402 			if (DB_CRED(mp) != NULL)
24403 				mblk_setcred(xmit_mp, DB_CRED(mp));
24404 			/*
24405 			 * Get priority marking, if any.
24406 			 * We propagate the CoS marking from the
24407 			 * original packet that went to QoS processing
24408 			 * in ip_wput_ire to the newly carved mp.
24409 			 */
24410 			if (DB_TYPE(xmit_mp) == M_DATA)
24411 				xmit_mp->b_band = mp->b_band;
24412 		}
24413 		UNLOCK_IRE_FP_MP(ire);
24414 
24415 		q = ire->ire_stq;
24416 		out_ill = (ill_t *)q->q_ptr;
24417 
24418 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24419 
24420 		DTRACE_PROBE4(ip4__physical__out__start,
24421 		    ill_t *, NULL, ill_t *, out_ill,
24422 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24423 
24424 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24425 		    ipst->ips_ipv4firewall_physical_out,
24426 		    NULL, out_ill, ipha, xmit_mp, mp, ipst);
24427 
24428 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24429 
24430 		if (xmit_mp != NULL) {
24431 			putnext(q, xmit_mp);
24432 
24433 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24434 			UPDATE_MIB(out_ill->ill_ip_mib,
24435 			    ipIfStatsHCOutOctets, i1);
24436 
24437 			if (pkt_type != OB_PKT) {
24438 				/*
24439 				 * Update the packet count and MIB stats
24440 				 * of trailing RTF_MULTIRT ires.
24441 				 */
24442 				UPDATE_OB_PKT_COUNT(ire);
24443 				BUMP_MIB(out_ill->ill_ip_mib,
24444 				    ipIfStatsOutFragReqds);
24445 			}
24446 		}
24447 
24448 		if (multirt_send) {
24449 			/*
24450 			 * We are in a multiple send case; look for
24451 			 * the next ire and re-enter the loop.
24452 			 */
24453 			ASSERT(ire1);
24454 			ASSERT(next_mp);
24455 			/* REFRELE the current ire before looping */
24456 			ire_refrele(ire);
24457 			ire = ire1;
24458 			ire1 = NULL;
24459 			mp = next_mp;
24460 			next_mp = NULL;
24461 		}
24462 	} while (multirt_send);
24463 
24464 	ASSERT(ire1 == NULL);
24465 
24466 	/* Restore the original ire; we need it for the trailing frags */
24467 	if (save_ire != NULL) {
24468 		/* REFRELE the last iterated ire */
24469 		ire_refrele(ire);
24470 		/* save_ire has been REFHOLDed */
24471 		ire = save_ire;
24472 		save_ire = NULL;
24473 		q = ire->ire_stq;
24474 	}
24475 
24476 	if (pkt_type == OB_PKT) {
24477 		UPDATE_OB_PKT_COUNT(ire);
24478 	} else {
24479 		out_ill = (ill_t *)q->q_ptr;
24480 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24481 		UPDATE_IB_PKT_COUNT(ire);
24482 	}
24483 
24484 	/* Advance the offset to the second frag starting point. */
24485 	offset += len;
24486 	/*
24487 	 * Update hdr_len from the copied header - there might be less options
24488 	 * in the later fragments.
24489 	 */
24490 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24491 	/* Loop until done. */
24492 	for (;;) {
24493 		uint16_t	offset_and_flags;
24494 		uint16_t	ip_len;
24495 
24496 		if (ip_data_end - offset > len) {
24497 			/*
24498 			 * Carve off the appropriate amount from the original
24499 			 * datagram.
24500 			 */
24501 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24502 				mp = NULL;
24503 				break;
24504 			}
24505 			/*
24506 			 * More frags after this one.  Get another copy
24507 			 * of the header.
24508 			 */
24509 			if (carve_mp->b_datap->db_ref == 1 &&
24510 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24511 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24512 				/* Inline IP header */
24513 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24514 				    hdr_mp->b_rptr;
24515 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24516 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24517 				mp = carve_mp;
24518 			} else {
24519 				if (!(mp = copyb(hdr_mp))) {
24520 					freemsg(carve_mp);
24521 					break;
24522 				}
24523 				/* Get priority marking, if any. */
24524 				mp->b_band = carve_mp->b_band;
24525 				mp->b_cont = carve_mp;
24526 			}
24527 			ipha = (ipha_t *)mp->b_rptr;
24528 			offset_and_flags = IPH_MF;
24529 		} else {
24530 			/*
24531 			 * Last frag.  Consume the header. Set len to
24532 			 * the length of this last piece.
24533 			 */
24534 			len = ip_data_end - offset;
24535 
24536 			/*
24537 			 * Carve off the appropriate amount from the original
24538 			 * datagram.
24539 			 */
24540 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24541 				mp = NULL;
24542 				break;
24543 			}
24544 			if (carve_mp->b_datap->db_ref == 1 &&
24545 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24546 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24547 				/* Inline IP header */
24548 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24549 				    hdr_mp->b_rptr;
24550 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24551 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24552 				mp = carve_mp;
24553 				freeb(hdr_mp);
24554 				hdr_mp = mp;
24555 			} else {
24556 				mp = hdr_mp;
24557 				/* Get priority marking, if any. */
24558 				mp->b_band = carve_mp->b_band;
24559 				mp->b_cont = carve_mp;
24560 			}
24561 			ipha = (ipha_t *)mp->b_rptr;
24562 			/* A frag of a frag might have IPH_MF non-zero */
24563 			offset_and_flags =
24564 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24565 			    IPH_MF;
24566 		}
24567 		offset_and_flags |= (uint16_t)(offset >> 3);
24568 		offset_and_flags |= (uint16_t)frag_flag;
24569 		/* Store the offset and flags in the IP header. */
24570 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24571 
24572 		/* Store the length in the IP header. */
24573 		ip_len = (uint16_t)(len + hdr_len);
24574 		ipha->ipha_length = htons(ip_len);
24575 
24576 		/*
24577 		 * Set the IP header checksum.	Note that mp is just
24578 		 * the header, so this is easy to pass to ip_csum.
24579 		 */
24580 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24581 
24582 		/* Attach a transmit header, if any, and ship it. */
24583 		if (pkt_type == OB_PKT) {
24584 			UPDATE_OB_PKT_COUNT(ire);
24585 		} else {
24586 			out_ill = (ill_t *)q->q_ptr;
24587 			BUMP_MIB(out_ill->ill_ip_mib,
24588 			    ipIfStatsHCOutForwDatagrams);
24589 			UPDATE_IB_PKT_COUNT(ire);
24590 		}
24591 
24592 		if (ire->ire_flags & RTF_MULTIRT) {
24593 			irb = ire->ire_bucket;
24594 			ASSERT(irb != NULL);
24595 
24596 			multirt_send = B_TRUE;
24597 
24598 			/*
24599 			 * Save the original ire; we will need to restore it
24600 			 * for the tailing frags.
24601 			 */
24602 			save_ire = ire;
24603 			IRE_REFHOLD(save_ire);
24604 		}
24605 		/*
24606 		 * Emission loop for this fragment, similar
24607 		 * to what is done for the first fragment.
24608 		 */
24609 		do {
24610 			if (multirt_send) {
24611 				/*
24612 				 * We are in a multiple send case, need to get
24613 				 * the next ire and make a copy of the packet.
24614 				 */
24615 				ASSERT(irb != NULL);
24616 				IRB_REFHOLD(irb);
24617 				for (ire1 = ire->ire_next;
24618 				    ire1 != NULL;
24619 				    ire1 = ire1->ire_next) {
24620 					if (!(ire1->ire_flags & RTF_MULTIRT))
24621 						continue;
24622 					if (ire1->ire_addr != ire->ire_addr)
24623 						continue;
24624 					if (ire1->ire_marks &
24625 					    (IRE_MARK_CONDEMNED|
24626 					    IRE_MARK_HIDDEN)) {
24627 						continue;
24628 					}
24629 					/*
24630 					 * Ensure we do not exceed the MTU
24631 					 * of the next route.
24632 					 */
24633 					if (ire1->ire_max_frag < max_frag) {
24634 						ip_multirt_bad_mtu(ire1,
24635 						    max_frag);
24636 						continue;
24637 					}
24638 
24639 					/* Got one. */
24640 					IRE_REFHOLD(ire1);
24641 					break;
24642 				}
24643 				IRB_REFRELE(irb);
24644 
24645 				if (ire1 != NULL) {
24646 					next_mp = copyb(mp);
24647 					if ((next_mp == NULL) ||
24648 					    ((mp->b_cont != NULL) &&
24649 					    ((next_mp->b_cont =
24650 					    dupmsg(mp->b_cont)) == NULL))) {
24651 						freemsg(next_mp);
24652 						next_mp = NULL;
24653 						ire_refrele(ire1);
24654 						ire1 = NULL;
24655 					}
24656 				}
24657 
24658 				/* Last multiroute ire; don't loop anymore. */
24659 				if (ire1 == NULL) {
24660 					multirt_send = B_FALSE;
24661 				}
24662 			}
24663 
24664 			/* Update transmit header */
24665 			ll_hdr_len = 0;
24666 			LOCK_IRE_FP_MP(ire);
24667 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24668 			if (ll_hdr_mp != NULL) {
24669 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24670 				ll_hdr_len = MBLKL(ll_hdr_mp);
24671 			} else {
24672 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24673 			}
24674 
24675 			if (!ll_hdr_mp) {
24676 				xmit_mp = mp;
24677 
24678 			/*
24679 			 * We have link-layer header that can fit in
24680 			 * our mblk.
24681 			 */
24682 			} else if (mp->b_datap->db_ref == 1 &&
24683 			    ll_hdr_len != 0 &&
24684 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24685 				/* M_DATA fastpath */
24686 				mp->b_rptr -= ll_hdr_len;
24687 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24688 				    ll_hdr_len);
24689 				xmit_mp = mp;
24690 
24691 			/*
24692 			 * Case of res_mp OR the fastpath mp can't fit
24693 			 * in the mblk
24694 			 */
24695 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24696 				xmit_mp->b_cont = mp;
24697 				if (DB_CRED(mp) != NULL)
24698 					mblk_setcred(xmit_mp, DB_CRED(mp));
24699 				/* Get priority marking, if any. */
24700 				if (DB_TYPE(xmit_mp) == M_DATA)
24701 					xmit_mp->b_band = mp->b_band;
24702 
24703 			/* Corner case if copyb failed */
24704 			} else {
24705 				/*
24706 				 * Exit both the replication and
24707 				 * fragmentation loops.
24708 				 */
24709 				UNLOCK_IRE_FP_MP(ire);
24710 				goto drop_pkt;
24711 			}
24712 			UNLOCK_IRE_FP_MP(ire);
24713 
24714 			mp1 = mp;
24715 			out_ill = (ill_t *)q->q_ptr;
24716 
24717 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24718 
24719 			DTRACE_PROBE4(ip4__physical__out__start,
24720 			    ill_t *, NULL, ill_t *, out_ill,
24721 			    ipha_t *, ipha, mblk_t *, xmit_mp);
24722 
24723 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
24724 			    ipst->ips_ipv4firewall_physical_out,
24725 			    NULL, out_ill, ipha, xmit_mp, mp, ipst);
24726 
24727 			DTRACE_PROBE1(ip4__physical__out__end,
24728 			    mblk_t *, xmit_mp);
24729 
24730 			if (mp != mp1 && hdr_mp == mp1)
24731 				hdr_mp = mp;
24732 			if (mp != mp1 && mp_orig == mp1)
24733 				mp_orig = mp;
24734 
24735 			if (xmit_mp != NULL) {
24736 				putnext(q, xmit_mp);
24737 
24738 				BUMP_MIB(out_ill->ill_ip_mib,
24739 				    ipIfStatsHCOutTransmits);
24740 				UPDATE_MIB(out_ill->ill_ip_mib,
24741 				    ipIfStatsHCOutOctets, ip_len);
24742 
24743 				if (pkt_type != OB_PKT) {
24744 					/*
24745 					 * Update the packet count of trailing
24746 					 * RTF_MULTIRT ires.
24747 					 */
24748 					UPDATE_OB_PKT_COUNT(ire);
24749 				}
24750 			}
24751 
24752 			/* All done if we just consumed the hdr_mp. */
24753 			if (mp == hdr_mp) {
24754 				last_frag = B_TRUE;
24755 				BUMP_MIB(out_ill->ill_ip_mib,
24756 				    ipIfStatsOutFragOKs);
24757 			}
24758 
24759 			if (multirt_send) {
24760 				/*
24761 				 * We are in a multiple send case; look for
24762 				 * the next ire and re-enter the loop.
24763 				 */
24764 				ASSERT(ire1);
24765 				ASSERT(next_mp);
24766 				/* REFRELE the current ire before looping */
24767 				ire_refrele(ire);
24768 				ire = ire1;
24769 				ire1 = NULL;
24770 				q = ire->ire_stq;
24771 				mp = next_mp;
24772 				next_mp = NULL;
24773 			}
24774 		} while (multirt_send);
24775 		/*
24776 		 * Restore the original ire; we need it for the
24777 		 * trailing frags
24778 		 */
24779 		if (save_ire != NULL) {
24780 			ASSERT(ire1 == NULL);
24781 			/* REFRELE the last iterated ire */
24782 			ire_refrele(ire);
24783 			/* save_ire has been REFHOLDed */
24784 			ire = save_ire;
24785 			q = ire->ire_stq;
24786 			save_ire = NULL;
24787 		}
24788 
24789 		if (last_frag) {
24790 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24791 			    "ip_wput_frag_end:(%S)",
24792 			    "consumed hdr_mp");
24793 
24794 			if (first_ire != NULL)
24795 				ire_refrele(first_ire);
24796 			return;
24797 		}
24798 		/* Otherwise, advance and loop. */
24799 		offset += len;
24800 	}
24801 
24802 drop_pkt:
24803 	/* Clean up following allocation failure. */
24804 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24805 	freemsg(mp);
24806 	if (mp != hdr_mp)
24807 		freeb(hdr_mp);
24808 	if (mp != mp_orig)
24809 		freemsg(mp_orig);
24810 
24811 	if (save_ire != NULL)
24812 		IRE_REFRELE(save_ire);
24813 	if (first_ire != NULL)
24814 		ire_refrele(first_ire);
24815 
24816 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24817 	    "ip_wput_frag_end:(%S)",
24818 	    "end--alloc failure");
24819 }
24820 
24821 /*
24822  * Copy the header plus those options which have the copy bit set
24823  */
24824 static mblk_t *
24825 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst)
24826 {
24827 	mblk_t	*mp;
24828 	uchar_t	*up;
24829 
24830 	/*
24831 	 * Quick check if we need to look for options without the copy bit
24832 	 * set
24833 	 */
24834 	mp = allocb(ipst->ips_ip_wroff_extra + hdr_len, BPRI_HI);
24835 	if (!mp)
24836 		return (mp);
24837 	mp->b_rptr += ipst->ips_ip_wroff_extra;
24838 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
24839 		bcopy(rptr, mp->b_rptr, hdr_len);
24840 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
24841 		return (mp);
24842 	}
24843 	up  = mp->b_rptr;
24844 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
24845 	up += IP_SIMPLE_HDR_LENGTH;
24846 	rptr += IP_SIMPLE_HDR_LENGTH;
24847 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
24848 	while (hdr_len > 0) {
24849 		uint32_t optval;
24850 		uint32_t optlen;
24851 
24852 		optval = *rptr;
24853 		if (optval == IPOPT_EOL)
24854 			break;
24855 		if (optval == IPOPT_NOP)
24856 			optlen = 1;
24857 		else
24858 			optlen = rptr[1];
24859 		if (optval & IPOPT_COPY) {
24860 			bcopy(rptr, up, optlen);
24861 			up += optlen;
24862 		}
24863 		rptr += optlen;
24864 		hdr_len -= optlen;
24865 	}
24866 	/*
24867 	 * Make sure that we drop an even number of words by filling
24868 	 * with EOL to the next word boundary.
24869 	 */
24870 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
24871 	    hdr_len & 0x3; hdr_len++)
24872 		*up++ = IPOPT_EOL;
24873 	mp->b_wptr = up;
24874 	/* Update header length */
24875 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
24876 	return (mp);
24877 }
24878 
24879 /*
24880  * Delivery to local recipients including fanout to multiple recipients.
24881  * Does not do checksumming of UDP/TCP.
24882  * Note: q should be the read side queue for either the ill or conn.
24883  * Note: rq should be the read side q for the lower (ill) stream.
24884  * We don't send packets to IPPF processing, thus the last argument
24885  * to all the fanout calls are B_FALSE.
24886  */
24887 void
24888 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
24889     int fanout_flags, zoneid_t zoneid)
24890 {
24891 	uint32_t	protocol;
24892 	mblk_t		*first_mp;
24893 	boolean_t	mctl_present;
24894 	int		ire_type;
24895 #define	rptr	((uchar_t *)ipha)
24896 	ip_stack_t	*ipst = ill->ill_ipst;
24897 
24898 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
24899 	    "ip_wput_local_start: q %p", q);
24900 
24901 	if (ire != NULL) {
24902 		ire_type = ire->ire_type;
24903 	} else {
24904 		/*
24905 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
24906 		 * packet is not multicast, we can't tell the ire type.
24907 		 */
24908 		ASSERT(CLASSD(ipha->ipha_dst));
24909 		ire_type = IRE_BROADCAST;
24910 	}
24911 
24912 	first_mp = mp;
24913 	if (first_mp->b_datap->db_type == M_CTL) {
24914 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
24915 		if (!io->ipsec_out_secure) {
24916 			/*
24917 			 * This ipsec_out_t was allocated in ip_wput
24918 			 * for multicast packets to store the ill_index.
24919 			 * As this is being delivered locally, we don't
24920 			 * need this anymore.
24921 			 */
24922 			mp = first_mp->b_cont;
24923 			freeb(first_mp);
24924 			first_mp = mp;
24925 			mctl_present = B_FALSE;
24926 		} else {
24927 			/*
24928 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
24929 			 * security properties for the looped-back packet.
24930 			 */
24931 			mctl_present = B_TRUE;
24932 			mp = first_mp->b_cont;
24933 			ASSERT(mp != NULL);
24934 			ipsec_out_to_in(first_mp);
24935 		}
24936 	} else {
24937 		mctl_present = B_FALSE;
24938 	}
24939 
24940 	DTRACE_PROBE4(ip4__loopback__in__start,
24941 	    ill_t *, ill, ill_t *, NULL,
24942 	    ipha_t *, ipha, mblk_t *, first_mp);
24943 
24944 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
24945 	    ipst->ips_ipv4firewall_loopback_in,
24946 	    ill, NULL, ipha, first_mp, mp, ipst);
24947 
24948 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
24949 
24950 	if (first_mp == NULL)
24951 		return;
24952 
24953 	ipst->ips_loopback_packets++;
24954 
24955 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
24956 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
24957 	if (!IS_SIMPLE_IPH(ipha)) {
24958 		ip_wput_local_options(ipha, ipst);
24959 	}
24960 
24961 	protocol = ipha->ipha_protocol;
24962 	switch (protocol) {
24963 	case IPPROTO_ICMP: {
24964 		ire_t		*ire_zone;
24965 		ilm_t		*ilm;
24966 		mblk_t		*mp1;
24967 		zoneid_t	last_zoneid;
24968 
24969 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(ill)) {
24970 			ASSERT(ire_type == IRE_BROADCAST);
24971 			/*
24972 			 * In the multicast case, applications may have joined
24973 			 * the group from different zones, so we need to deliver
24974 			 * the packet to each of them. Loop through the
24975 			 * multicast memberships structures (ilm) on the receive
24976 			 * ill and send a copy of the packet up each matching
24977 			 * one. However, we don't do this for multicasts sent on
24978 			 * the loopback interface (PHYI_LOOPBACK flag set) as
24979 			 * they must stay in the sender's zone.
24980 			 *
24981 			 * ilm_add_v6() ensures that ilms in the same zone are
24982 			 * contiguous in the ill_ilm list. We use this property
24983 			 * to avoid sending duplicates needed when two
24984 			 * applications in the same zone join the same group on
24985 			 * different logical interfaces: we ignore the ilm if
24986 			 * it's zoneid is the same as the last matching one.
24987 			 * In addition, the sending of the packet for
24988 			 * ire_zoneid is delayed until all of the other ilms
24989 			 * have been exhausted.
24990 			 */
24991 			last_zoneid = -1;
24992 			ILM_WALKER_HOLD(ill);
24993 			for (ilm = ill->ill_ilm; ilm != NULL;
24994 			    ilm = ilm->ilm_next) {
24995 				if ((ilm->ilm_flags & ILM_DELETED) ||
24996 				    ipha->ipha_dst != ilm->ilm_addr ||
24997 				    ilm->ilm_zoneid == last_zoneid ||
24998 				    ilm->ilm_zoneid == zoneid ||
24999 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
25000 					continue;
25001 				mp1 = ip_copymsg(first_mp);
25002 				if (mp1 == NULL)
25003 					continue;
25004 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25005 				    mctl_present, B_FALSE, ill,
25006 				    ilm->ilm_zoneid);
25007 				last_zoneid = ilm->ilm_zoneid;
25008 			}
25009 			ILM_WALKER_RELE(ill);
25010 			/*
25011 			 * Loopback case: the sending endpoint has
25012 			 * IP_MULTICAST_LOOP disabled, therefore we don't
25013 			 * dispatch the multicast packet to the sending zone.
25014 			 */
25015 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
25016 				freemsg(first_mp);
25017 				return;
25018 			}
25019 		} else if (ire_type == IRE_BROADCAST) {
25020 			/*
25021 			 * In the broadcast case, there may be many zones
25022 			 * which need a copy of the packet delivered to them.
25023 			 * There is one IRE_BROADCAST per broadcast address
25024 			 * and per zone; we walk those using a helper function.
25025 			 * In addition, the sending of the packet for zoneid is
25026 			 * delayed until all of the other ires have been
25027 			 * processed.
25028 			 */
25029 			IRB_REFHOLD(ire->ire_bucket);
25030 			ire_zone = NULL;
25031 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25032 			    ire)) != NULL) {
25033 				mp1 = ip_copymsg(first_mp);
25034 				if (mp1 == NULL)
25035 					continue;
25036 
25037 				UPDATE_IB_PKT_COUNT(ire_zone);
25038 				ire_zone->ire_last_used_time = lbolt;
25039 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25040 				    mctl_present, B_FALSE, ill,
25041 				    ire_zone->ire_zoneid);
25042 			}
25043 			IRB_REFRELE(ire->ire_bucket);
25044 		}
25045 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25046 		    0, mctl_present, B_FALSE, ill, zoneid);
25047 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25048 		    "ip_wput_local_end: q %p (%S)",
25049 		    q, "icmp");
25050 		return;
25051 	}
25052 	case IPPROTO_IGMP:
25053 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25054 			/* Bad packet - discarded by igmp_input */
25055 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25056 			    "ip_wput_local_end: q %p (%S)",
25057 			    q, "igmp_input--bad packet");
25058 			if (mctl_present)
25059 				freeb(first_mp);
25060 			return;
25061 		}
25062 		/*
25063 		 * igmp_input() may have returned the pulled up message.
25064 		 * So first_mp and ipha need to be reinitialized.
25065 		 */
25066 		ipha = (ipha_t *)mp->b_rptr;
25067 		if (mctl_present)
25068 			first_mp->b_cont = mp;
25069 		else
25070 			first_mp = mp;
25071 		/* deliver to local raw users */
25072 		break;
25073 	case IPPROTO_ENCAP:
25074 		/*
25075 		 * This case is covered by either ip_fanout_proto, or by
25076 		 * the above security processing for self-tunneled packets.
25077 		 */
25078 		break;
25079 	case IPPROTO_UDP: {
25080 		uint16_t	*up;
25081 		uint32_t	ports;
25082 
25083 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25084 		    UDP_PORTS_OFFSET);
25085 		/* Force a 'valid' checksum. */
25086 		up[3] = 0;
25087 
25088 		ports = *(uint32_t *)up;
25089 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25090 		    (ire_type == IRE_BROADCAST),
25091 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25092 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25093 		    ill, zoneid);
25094 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25095 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25096 		return;
25097 	}
25098 	case IPPROTO_TCP: {
25099 
25100 		/*
25101 		 * For TCP, discard broadcast packets.
25102 		 */
25103 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25104 			freemsg(first_mp);
25105 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25106 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25107 			return;
25108 		}
25109 
25110 		if (mp->b_datap->db_type == M_DATA) {
25111 			/*
25112 			 * M_DATA mblk, so init mblk (chain) for no struio().
25113 			 */
25114 			mblk_t	*mp1 = mp;
25115 
25116 			do {
25117 				mp1->b_datap->db_struioflag = 0;
25118 			} while ((mp1 = mp1->b_cont) != NULL);
25119 		}
25120 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25121 		    <= mp->b_wptr);
25122 		ip_fanout_tcp(q, first_mp, ill, ipha,
25123 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25124 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25125 		    mctl_present, B_FALSE, zoneid);
25126 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25127 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25128 		return;
25129 	}
25130 	case IPPROTO_SCTP:
25131 	{
25132 		uint32_t	ports;
25133 
25134 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25135 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25136 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25137 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25138 		return;
25139 	}
25140 
25141 	default:
25142 		break;
25143 	}
25144 	/*
25145 	 * Find a client for some other protocol.  We give
25146 	 * copies to multiple clients, if more than one is
25147 	 * bound.
25148 	 */
25149 	ip_fanout_proto(q, first_mp, ill, ipha,
25150 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25151 	    mctl_present, B_FALSE, ill, zoneid);
25152 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25153 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25154 #undef	rptr
25155 }
25156 
25157 /*
25158  * Update any source route, record route, or timestamp options.
25159  * Check that we are at end of strict source route.
25160  * The options have been sanity checked by ip_wput_options().
25161  */
25162 static void
25163 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25164 {
25165 	ipoptp_t	opts;
25166 	uchar_t		*opt;
25167 	uint8_t		optval;
25168 	uint8_t		optlen;
25169 	ipaddr_t	dst;
25170 	uint32_t	ts;
25171 	ire_t		*ire;
25172 	timestruc_t	now;
25173 
25174 	ip2dbg(("ip_wput_local_options\n"));
25175 	for (optval = ipoptp_first(&opts, ipha);
25176 	    optval != IPOPT_EOL;
25177 	    optval = ipoptp_next(&opts)) {
25178 		opt = opts.ipoptp_cur;
25179 		optlen = opts.ipoptp_len;
25180 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25181 		switch (optval) {
25182 			uint32_t off;
25183 		case IPOPT_SSRR:
25184 		case IPOPT_LSRR:
25185 			off = opt[IPOPT_OFFSET];
25186 			off--;
25187 			if (optlen < IP_ADDR_LEN ||
25188 			    off > optlen - IP_ADDR_LEN) {
25189 				/* End of source route */
25190 				break;
25191 			}
25192 			/*
25193 			 * This will only happen if two consecutive entries
25194 			 * in the source route contains our address or if
25195 			 * it is a packet with a loose source route which
25196 			 * reaches us before consuming the whole source route
25197 			 */
25198 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25199 			if (optval == IPOPT_SSRR) {
25200 				return;
25201 			}
25202 			/*
25203 			 * Hack: instead of dropping the packet truncate the
25204 			 * source route to what has been used by filling the
25205 			 * rest with IPOPT_NOP.
25206 			 */
25207 			opt[IPOPT_OLEN] = (uint8_t)off;
25208 			while (off < optlen) {
25209 				opt[off++] = IPOPT_NOP;
25210 			}
25211 			break;
25212 		case IPOPT_RR:
25213 			off = opt[IPOPT_OFFSET];
25214 			off--;
25215 			if (optlen < IP_ADDR_LEN ||
25216 			    off > optlen - IP_ADDR_LEN) {
25217 				/* No more room - ignore */
25218 				ip1dbg((
25219 				    "ip_wput_forward_options: end of RR\n"));
25220 				break;
25221 			}
25222 			dst = htonl(INADDR_LOOPBACK);
25223 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25224 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25225 			break;
25226 		case IPOPT_TS:
25227 			/* Insert timestamp if there is romm */
25228 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25229 			case IPOPT_TS_TSONLY:
25230 				off = IPOPT_TS_TIMELEN;
25231 				break;
25232 			case IPOPT_TS_PRESPEC:
25233 			case IPOPT_TS_PRESPEC_RFC791:
25234 				/* Verify that the address matched */
25235 				off = opt[IPOPT_OFFSET] - 1;
25236 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25237 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25238 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25239 				    ipst);
25240 				if (ire == NULL) {
25241 					/* Not for us */
25242 					break;
25243 				}
25244 				ire_refrele(ire);
25245 				/* FALLTHRU */
25246 			case IPOPT_TS_TSANDADDR:
25247 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25248 				break;
25249 			default:
25250 				/*
25251 				 * ip_*put_options should have already
25252 				 * dropped this packet.
25253 				 */
25254 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25255 				    "unknown IT - bug in ip_wput_options?\n");
25256 				return;	/* Keep "lint" happy */
25257 			}
25258 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25259 				/* Increase overflow counter */
25260 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25261 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25262 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25263 				    (off << 4);
25264 				break;
25265 			}
25266 			off = opt[IPOPT_OFFSET] - 1;
25267 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25268 			case IPOPT_TS_PRESPEC:
25269 			case IPOPT_TS_PRESPEC_RFC791:
25270 			case IPOPT_TS_TSANDADDR:
25271 				dst = htonl(INADDR_LOOPBACK);
25272 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25273 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25274 				/* FALLTHRU */
25275 			case IPOPT_TS_TSONLY:
25276 				off = opt[IPOPT_OFFSET] - 1;
25277 				/* Compute # of milliseconds since midnight */
25278 				gethrestime(&now);
25279 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25280 				    now.tv_nsec / (NANOSEC / MILLISEC);
25281 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25282 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25283 				break;
25284 			}
25285 			break;
25286 		}
25287 	}
25288 }
25289 
25290 /*
25291  * Send out a multicast packet on interface ipif.
25292  * The sender does not have an conn.
25293  * Caller verifies that this isn't a PHYI_LOOPBACK.
25294  */
25295 void
25296 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25297 {
25298 	ipha_t	*ipha;
25299 	ire_t	*ire;
25300 	ipaddr_t	dst;
25301 	mblk_t		*first_mp;
25302 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25303 
25304 	/* igmp_sendpkt always allocates a ipsec_out_t */
25305 	ASSERT(mp->b_datap->db_type == M_CTL);
25306 	ASSERT(!ipif->ipif_isv6);
25307 	ASSERT(!IS_LOOPBACK(ipif->ipif_ill));
25308 
25309 	first_mp = mp;
25310 	mp = first_mp->b_cont;
25311 	ASSERT(mp->b_datap->db_type == M_DATA);
25312 	ipha = (ipha_t *)mp->b_rptr;
25313 
25314 	/*
25315 	 * Find an IRE which matches the destination and the outgoing
25316 	 * queue (i.e. the outgoing interface.)
25317 	 */
25318 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25319 		dst = ipif->ipif_pp_dst_addr;
25320 	else
25321 		dst = ipha->ipha_dst;
25322 	/*
25323 	 * The source address has already been initialized by the
25324 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25325 	 * be sufficient rather than MATCH_IRE_IPIF.
25326 	 *
25327 	 * This function is used for sending IGMP packets. We need
25328 	 * to make sure that we send the packet out of the interface
25329 	 * (ipif->ipif_ill) where we joined the group. This is to
25330 	 * prevent from switches doing IGMP snooping to send us multicast
25331 	 * packets for a given group on the interface we have joined.
25332 	 * If we can't find an ire, igmp_sendpkt has already initialized
25333 	 * ipsec_out_attach_if so that this will not be load spread in
25334 	 * ip_newroute_ipif.
25335 	 */
25336 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25337 	    MATCH_IRE_ILL, ipst);
25338 	if (!ire) {
25339 		/*
25340 		 * Mark this packet to make it be delivered to
25341 		 * ip_wput_ire after the new ire has been
25342 		 * created.
25343 		 */
25344 		mp->b_prev = NULL;
25345 		mp->b_next = NULL;
25346 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25347 		    zoneid, &zero_info);
25348 		return;
25349 	}
25350 
25351 	/*
25352 	 * Honor the RTF_SETSRC flag; this is the only case
25353 	 * where we force this addr whatever the current src addr is,
25354 	 * because this address is set by igmp_sendpkt(), and
25355 	 * cannot be specified by any user.
25356 	 */
25357 	if (ire->ire_flags & RTF_SETSRC) {
25358 		ipha->ipha_src = ire->ire_src_addr;
25359 	}
25360 
25361 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25362 }
25363 
25364 /*
25365  * NOTE : This function does not ire_refrele the ire argument passed in.
25366  *
25367  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25368  * failure. The nce_fp_mp can vanish any time in the case of
25369  * IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25370  * the ire_lock to access the nce_fp_mp in this case.
25371  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25372  * prepending a fastpath message IPQoS processing must precede it, we also set
25373  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25374  * (IPQoS might have set the b_band for CoS marking).
25375  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25376  * must follow it so that IPQoS can mark the dl_priority field for CoS
25377  * marking, if needed.
25378  */
25379 static mblk_t *
25380 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
25381 {
25382 	uint_t	hlen;
25383 	ipha_t *ipha;
25384 	mblk_t *mp1;
25385 	boolean_t qos_done = B_FALSE;
25386 	uchar_t	*ll_hdr;
25387 	ip_stack_t	*ipst = ire->ire_ipst;
25388 
25389 #define	rptr	((uchar_t *)ipha)
25390 
25391 	ipha = (ipha_t *)mp->b_rptr;
25392 	hlen = 0;
25393 	LOCK_IRE_FP_MP(ire);
25394 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25395 		ASSERT(DB_TYPE(mp1) == M_DATA);
25396 		/* Initiate IPPF processing */
25397 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25398 			UNLOCK_IRE_FP_MP(ire);
25399 			ip_process(proc, &mp, ill_index);
25400 			if (mp == NULL)
25401 				return (NULL);
25402 
25403 			ipha = (ipha_t *)mp->b_rptr;
25404 			LOCK_IRE_FP_MP(ire);
25405 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25406 				qos_done = B_TRUE;
25407 				goto no_fp_mp;
25408 			}
25409 			ASSERT(DB_TYPE(mp1) == M_DATA);
25410 		}
25411 		hlen = MBLKL(mp1);
25412 		/*
25413 		 * Check if we have enough room to prepend fastpath
25414 		 * header
25415 		 */
25416 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25417 			ll_hdr = rptr - hlen;
25418 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25419 			/*
25420 			 * Set the b_rptr to the start of the link layer
25421 			 * header
25422 			 */
25423 			mp->b_rptr = ll_hdr;
25424 			mp1 = mp;
25425 		} else {
25426 			mp1 = copyb(mp1);
25427 			if (mp1 == NULL)
25428 				goto unlock_err;
25429 			mp1->b_band = mp->b_band;
25430 			mp1->b_cont = mp;
25431 			/*
25432 			 * certain system generated traffic may not
25433 			 * have cred/label in ip header block. This
25434 			 * is true even for a labeled system. But for
25435 			 * labeled traffic, inherit the label in the
25436 			 * new header.
25437 			 */
25438 			if (DB_CRED(mp) != NULL)
25439 				mblk_setcred(mp1, DB_CRED(mp));
25440 			/*
25441 			 * XXX disable ICK_VALID and compute checksum
25442 			 * here; can happen if nce_fp_mp changes and
25443 			 * it can't be copied now due to insufficient
25444 			 * space. (unlikely, fp mp can change, but it
25445 			 * does not increase in length)
25446 			 */
25447 		}
25448 		UNLOCK_IRE_FP_MP(ire);
25449 	} else {
25450 no_fp_mp:
25451 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25452 		if (mp1 == NULL) {
25453 unlock_err:
25454 			UNLOCK_IRE_FP_MP(ire);
25455 			freemsg(mp);
25456 			return (NULL);
25457 		}
25458 		UNLOCK_IRE_FP_MP(ire);
25459 		mp1->b_cont = mp;
25460 		/*
25461 		 * certain system generated traffic may not
25462 		 * have cred/label in ip header block. This
25463 		 * is true even for a labeled system. But for
25464 		 * labeled traffic, inherit the label in the
25465 		 * new header.
25466 		 */
25467 		if (DB_CRED(mp) != NULL)
25468 			mblk_setcred(mp1, DB_CRED(mp));
25469 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25470 			ip_process(proc, &mp1, ill_index);
25471 			if (mp1 == NULL)
25472 				return (NULL);
25473 		}
25474 	}
25475 	return (mp1);
25476 #undef rptr
25477 }
25478 
25479 /*
25480  * Finish the outbound IPsec processing for an IPv6 packet. This function
25481  * is called from ipsec_out_process() if the IPsec packet was processed
25482  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25483  * asynchronously.
25484  */
25485 void
25486 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25487     ire_t *ire_arg)
25488 {
25489 	in6_addr_t *v6dstp;
25490 	ire_t *ire;
25491 	mblk_t *mp;
25492 	ip6_t *ip6h1;
25493 	uint_t	ill_index;
25494 	ipsec_out_t *io;
25495 	boolean_t attach_if, hwaccel;
25496 	uint32_t flags = IP6_NO_IPPOLICY;
25497 	int match_flags;
25498 	zoneid_t zoneid;
25499 	boolean_t ill_need_rele = B_FALSE;
25500 	boolean_t ire_need_rele = B_FALSE;
25501 	ip_stack_t	*ipst;
25502 
25503 	mp = ipsec_mp->b_cont;
25504 	ip6h1 = (ip6_t *)mp->b_rptr;
25505 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25506 	ASSERT(io->ipsec_out_ns != NULL);
25507 	ipst = io->ipsec_out_ns->netstack_ip;
25508 	ill_index = io->ipsec_out_ill_index;
25509 	if (io->ipsec_out_reachable) {
25510 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25511 	}
25512 	attach_if = io->ipsec_out_attach_if;
25513 	hwaccel = io->ipsec_out_accelerated;
25514 	zoneid = io->ipsec_out_zoneid;
25515 	ASSERT(zoneid != ALL_ZONES);
25516 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25517 	/* Multicast addresses should have non-zero ill_index. */
25518 	v6dstp = &ip6h->ip6_dst;
25519 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25520 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25521 	ASSERT(!attach_if || ill_index != 0);
25522 	if (ill_index != 0) {
25523 		if (ill == NULL) {
25524 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
25525 			    B_TRUE, ipst);
25526 
25527 			/* Failure case frees things for us. */
25528 			if (ill == NULL)
25529 				return;
25530 
25531 			ill_need_rele = B_TRUE;
25532 		}
25533 		/*
25534 		 * If this packet needs to go out on a particular interface
25535 		 * honor it.
25536 		 */
25537 		if (attach_if) {
25538 			match_flags = MATCH_IRE_ILL;
25539 
25540 			/*
25541 			 * Check if we need an ire that will not be
25542 			 * looked up by anybody else i.e. HIDDEN.
25543 			 */
25544 			if (ill_is_probeonly(ill)) {
25545 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25546 			}
25547 		}
25548 	}
25549 	ASSERT(mp != NULL);
25550 
25551 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25552 		boolean_t unspec_src;
25553 		ipif_t	*ipif;
25554 
25555 		/*
25556 		 * Use the ill_index to get the right ill.
25557 		 */
25558 		unspec_src = io->ipsec_out_unspec_src;
25559 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25560 		if (ipif == NULL) {
25561 			if (ill_need_rele)
25562 				ill_refrele(ill);
25563 			freemsg(ipsec_mp);
25564 			return;
25565 		}
25566 
25567 		if (ire_arg != NULL) {
25568 			ire = ire_arg;
25569 		} else {
25570 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25571 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25572 			ire_need_rele = B_TRUE;
25573 		}
25574 		if (ire != NULL) {
25575 			ipif_refrele(ipif);
25576 			/*
25577 			 * XXX Do the multicast forwarding now, as the IPsec
25578 			 * processing has been done.
25579 			 */
25580 			goto send;
25581 		}
25582 
25583 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25584 		mp->b_prev = NULL;
25585 		mp->b_next = NULL;
25586 
25587 		/*
25588 		 * If the IPsec packet was processed asynchronously,
25589 		 * drop it now.
25590 		 */
25591 		if (q == NULL) {
25592 			if (ill_need_rele)
25593 				ill_refrele(ill);
25594 			freemsg(ipsec_mp);
25595 			return;
25596 		}
25597 
25598 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
25599 		    unspec_src, zoneid);
25600 		ipif_refrele(ipif);
25601 	} else {
25602 		if (attach_if) {
25603 			ipif_t	*ipif;
25604 
25605 			ipif = ipif_get_next_ipif(NULL, ill);
25606 			if (ipif == NULL) {
25607 				if (ill_need_rele)
25608 					ill_refrele(ill);
25609 				freemsg(ipsec_mp);
25610 				return;
25611 			}
25612 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25613 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25614 			ire_need_rele = B_TRUE;
25615 			ipif_refrele(ipif);
25616 		} else {
25617 			if (ire_arg != NULL) {
25618 				ire = ire_arg;
25619 			} else {
25620 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL,
25621 				    ipst);
25622 				ire_need_rele = B_TRUE;
25623 			}
25624 		}
25625 		if (ire != NULL)
25626 			goto send;
25627 		/*
25628 		 * ire disappeared underneath.
25629 		 *
25630 		 * What we need to do here is the ip_newroute
25631 		 * logic to get the ire without doing the IPsec
25632 		 * processing. Follow the same old path. But this
25633 		 * time, ip_wput or ire_add_then_send will call us
25634 		 * directly as all the IPsec operations are done.
25635 		 */
25636 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25637 		mp->b_prev = NULL;
25638 		mp->b_next = NULL;
25639 
25640 		/*
25641 		 * If the IPsec packet was processed asynchronously,
25642 		 * drop it now.
25643 		 */
25644 		if (q == NULL) {
25645 			if (ill_need_rele)
25646 				ill_refrele(ill);
25647 			freemsg(ipsec_mp);
25648 			return;
25649 		}
25650 
25651 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25652 		    zoneid, ipst);
25653 	}
25654 	if (ill != NULL && ill_need_rele)
25655 		ill_refrele(ill);
25656 	return;
25657 send:
25658 	if (ill != NULL && ill_need_rele)
25659 		ill_refrele(ill);
25660 
25661 	/* Local delivery */
25662 	if (ire->ire_stq == NULL) {
25663 		ill_t	*out_ill;
25664 		ASSERT(q != NULL);
25665 
25666 		/* PFHooks: LOOPBACK_OUT */
25667 		out_ill = ire_to_ill(ire);
25668 
25669 		DTRACE_PROBE4(ip6__loopback__out__start,
25670 		    ill_t *, NULL, ill_t *, out_ill,
25671 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25672 
25673 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
25674 		    ipst->ips_ipv6firewall_loopback_out,
25675 		    NULL, out_ill, ip6h1, ipsec_mp, mp, ipst);
25676 
25677 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25678 
25679 		if (ipsec_mp != NULL)
25680 			ip_wput_local_v6(RD(q), out_ill,
25681 			    ip6h, ipsec_mp, ire, 0);
25682 		if (ire_need_rele)
25683 			ire_refrele(ire);
25684 		return;
25685 	}
25686 	/*
25687 	 * Everything is done. Send it out on the wire.
25688 	 * We force the insertion of a fragment header using the
25689 	 * IPH_FRAG_HDR flag in two cases:
25690 	 * - after reception of an ICMPv6 "packet too big" message
25691 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25692 	 * - for multirouted IPv6 packets, so that the receiver can
25693 	 *   discard duplicates according to their fragment identifier
25694 	 */
25695 	/* XXX fix flow control problems. */
25696 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25697 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25698 		if (hwaccel) {
25699 			/*
25700 			 * hardware acceleration does not handle these
25701 			 * "slow path" cases.
25702 			 */
25703 			/* IPsec KSTATS: should bump bean counter here. */
25704 			if (ire_need_rele)
25705 				ire_refrele(ire);
25706 			freemsg(ipsec_mp);
25707 			return;
25708 		}
25709 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25710 		    (mp->b_cont ? msgdsize(mp) :
25711 		    mp->b_wptr - (uchar_t *)ip6h)) {
25712 			/* IPsec KSTATS: should bump bean counter here. */
25713 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25714 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25715 			    msgdsize(mp)));
25716 			if (ire_need_rele)
25717 				ire_refrele(ire);
25718 			freemsg(ipsec_mp);
25719 			return;
25720 		}
25721 		ASSERT(mp->b_prev == NULL);
25722 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
25723 		    ntohs(ip6h->ip6_plen) +
25724 		    IPV6_HDR_LEN, ire->ire_max_frag));
25725 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
25726 		    ire->ire_max_frag);
25727 	} else {
25728 		UPDATE_OB_PKT_COUNT(ire);
25729 		ire->ire_last_used_time = lbolt;
25730 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
25731 	}
25732 	if (ire_need_rele)
25733 		ire_refrele(ire);
25734 	freeb(ipsec_mp);
25735 }
25736 
25737 void
25738 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
25739 {
25740 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
25741 	da_ipsec_t *hada;	/* data attributes */
25742 	ill_t *ill = (ill_t *)q->q_ptr;
25743 
25744 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
25745 
25746 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
25747 		/* IPsec KSTATS: Bump lose counter here! */
25748 		freemsg(mp);
25749 		return;
25750 	}
25751 
25752 	/*
25753 	 * It's an IPsec packet that must be
25754 	 * accelerated by the Provider, and the
25755 	 * outbound ill is IPsec acceleration capable.
25756 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
25757 	 * to the ill.
25758 	 * IPsec KSTATS: should bump packet counter here.
25759 	 */
25760 
25761 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
25762 	if (hada_mp == NULL) {
25763 		/* IPsec KSTATS: should bump packet counter here. */
25764 		freemsg(mp);
25765 		return;
25766 	}
25767 
25768 	hada_mp->b_datap->db_type = M_CTL;
25769 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
25770 	hada_mp->b_cont = mp;
25771 
25772 	hada = (da_ipsec_t *)hada_mp->b_rptr;
25773 	bzero(hada, sizeof (da_ipsec_t));
25774 	hada->da_type = IPHADA_M_CTL;
25775 
25776 	putnext(q, hada_mp);
25777 }
25778 
25779 /*
25780  * Finish the outbound IPsec processing. This function is called from
25781  * ipsec_out_process() if the IPsec packet was processed
25782  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25783  * asynchronously.
25784  */
25785 void
25786 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
25787     ire_t *ire_arg)
25788 {
25789 	uint32_t v_hlen_tos_len;
25790 	ipaddr_t	dst;
25791 	ipif_t	*ipif = NULL;
25792 	ire_t *ire;
25793 	ire_t *ire1 = NULL;
25794 	mblk_t *next_mp = NULL;
25795 	uint32_t max_frag;
25796 	boolean_t multirt_send = B_FALSE;
25797 	mblk_t *mp;
25798 	ipha_t *ipha1;
25799 	uint_t	ill_index;
25800 	ipsec_out_t *io;
25801 	boolean_t attach_if;
25802 	int match_flags;
25803 	irb_t *irb = NULL;
25804 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
25805 	zoneid_t zoneid;
25806 	ipxmit_state_t	pktxmit_state;
25807 	ip_stack_t	*ipst;
25808 
25809 #ifdef	_BIG_ENDIAN
25810 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
25811 #else
25812 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
25813 #endif
25814 
25815 	mp = ipsec_mp->b_cont;
25816 	ipha1 = (ipha_t *)mp->b_rptr;
25817 	ASSERT(mp != NULL);
25818 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
25819 	dst = ipha->ipha_dst;
25820 
25821 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25822 	ill_index = io->ipsec_out_ill_index;
25823 	attach_if = io->ipsec_out_attach_if;
25824 	zoneid = io->ipsec_out_zoneid;
25825 	ASSERT(zoneid != ALL_ZONES);
25826 	ipst = io->ipsec_out_ns->netstack_ip;
25827 	ASSERT(io->ipsec_out_ns != NULL);
25828 
25829 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25830 	if (ill_index != 0) {
25831 		if (ill == NULL) {
25832 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
25833 			    ill_index, B_FALSE, ipst);
25834 
25835 			/* Failure case frees things for us. */
25836 			if (ill == NULL)
25837 				return;
25838 
25839 			ill_need_rele = B_TRUE;
25840 		}
25841 		/*
25842 		 * If this packet needs to go out on a particular interface
25843 		 * honor it.
25844 		 */
25845 		if (attach_if) {
25846 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25847 
25848 			/*
25849 			 * Check if we need an ire that will not be
25850 			 * looked up by anybody else i.e. HIDDEN.
25851 			 */
25852 			if (ill_is_probeonly(ill)) {
25853 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25854 			}
25855 		}
25856 	}
25857 
25858 	if (CLASSD(dst)) {
25859 		boolean_t conn_dontroute;
25860 		/*
25861 		 * Use the ill_index to get the right ipif.
25862 		 */
25863 		conn_dontroute = io->ipsec_out_dontroute;
25864 		if (ill_index == 0)
25865 			ipif = ipif_lookup_group(dst, zoneid, ipst);
25866 		else
25867 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25868 		if (ipif == NULL) {
25869 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
25870 			    " multicast\n"));
25871 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
25872 			freemsg(ipsec_mp);
25873 			goto done;
25874 		}
25875 		/*
25876 		 * ipha_src has already been intialized with the
25877 		 * value of the ipif in ip_wput. All we need now is
25878 		 * an ire to send this downstream.
25879 		 */
25880 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
25881 		    MBLK_GETLABEL(mp), match_flags, ipst);
25882 		if (ire != NULL) {
25883 			ill_t *ill1;
25884 			/*
25885 			 * Do the multicast forwarding now, as the IPsec
25886 			 * processing has been done.
25887 			 */
25888 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
25889 			    (ill1 = ire_to_ill(ire))) {
25890 				if (ip_mforward(ill1, ipha, mp)) {
25891 					freemsg(ipsec_mp);
25892 					ip1dbg(("ip_wput_ipsec_out: mforward "
25893 					    "failed\n"));
25894 					ire_refrele(ire);
25895 					goto done;
25896 				}
25897 			}
25898 			goto send;
25899 		}
25900 
25901 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
25902 		mp->b_prev = NULL;
25903 		mp->b_next = NULL;
25904 
25905 		/*
25906 		 * If the IPsec packet was processed asynchronously,
25907 		 * drop it now.
25908 		 */
25909 		if (q == NULL) {
25910 			freemsg(ipsec_mp);
25911 			goto done;
25912 		}
25913 
25914 		/*
25915 		 * We may be using a wrong ipif to create the ire.
25916 		 * But it is okay as the source address is assigned
25917 		 * for the packet already. Next outbound packet would
25918 		 * create the IRE with the right IPIF in ip_wput.
25919 		 *
25920 		 * Also handle RTF_MULTIRT routes.
25921 		 */
25922 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
25923 		    zoneid, &zero_info);
25924 	} else {
25925 		if (attach_if) {
25926 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
25927 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25928 		} else {
25929 			if (ire_arg != NULL) {
25930 				ire = ire_arg;
25931 				ire_need_rele = B_FALSE;
25932 			} else {
25933 				ire = ire_cache_lookup(dst, zoneid,
25934 				    MBLK_GETLABEL(mp), ipst);
25935 			}
25936 		}
25937 		if (ire != NULL) {
25938 			goto send;
25939 		}
25940 
25941 		/*
25942 		 * ire disappeared underneath.
25943 		 *
25944 		 * What we need to do here is the ip_newroute
25945 		 * logic to get the ire without doing the IPsec
25946 		 * processing. Follow the same old path. But this
25947 		 * time, ip_wput or ire_add_then_put will call us
25948 		 * directly as all the IPsec operations are done.
25949 		 */
25950 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
25951 		mp->b_prev = NULL;
25952 		mp->b_next = NULL;
25953 
25954 		/*
25955 		 * If the IPsec packet was processed asynchronously,
25956 		 * drop it now.
25957 		 */
25958 		if (q == NULL) {
25959 			freemsg(ipsec_mp);
25960 			goto done;
25961 		}
25962 
25963 		/*
25964 		 * Since we're going through ip_newroute() again, we
25965 		 * need to make sure we don't:
25966 		 *
25967 		 *	1.) Trigger the ASSERT() with the ipha_ident
25968 		 *	    overloading.
25969 		 *	2.) Redo transport-layer checksumming, since we've
25970 		 *	    already done all that to get this far.
25971 		 *
25972 		 * The easiest way not do either of the above is to set
25973 		 * the ipha_ident field to IP_HDR_INCLUDED.
25974 		 */
25975 		ipha->ipha_ident = IP_HDR_INCLUDED;
25976 		ip_newroute(q, ipsec_mp, dst, (CONN_Q(q) ? Q_TO_CONN(q) : NULL),
25977 		    zoneid, ipst);
25978 	}
25979 	goto done;
25980 send:
25981 	if (ire->ire_stq == NULL) {
25982 		ill_t	*out_ill;
25983 		/*
25984 		 * Loopbacks go through ip_wput_local except for one case.
25985 		 * We come here if we generate a icmp_frag_needed message
25986 		 * after IPsec processing is over. When this function calls
25987 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
25988 		 * icmp_frag_needed. The message generated comes back here
25989 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
25990 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
25991 		 * source address as it is usually set in ip_wput_ire. As
25992 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
25993 		 * and we end up here. We can't enter ip_wput_ire once the
25994 		 * IPsec processing is over and hence we need to do it here.
25995 		 */
25996 		ASSERT(q != NULL);
25997 		UPDATE_OB_PKT_COUNT(ire);
25998 		ire->ire_last_used_time = lbolt;
25999 		if (ipha->ipha_src == 0)
26000 			ipha->ipha_src = ire->ire_src_addr;
26001 
26002 		/* PFHooks: LOOPBACK_OUT */
26003 		out_ill = ire_to_ill(ire);
26004 
26005 		DTRACE_PROBE4(ip4__loopback__out__start,
26006 		    ill_t *, NULL, ill_t *, out_ill,
26007 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
26008 
26009 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
26010 		    ipst->ips_ipv4firewall_loopback_out,
26011 		    NULL, out_ill, ipha1, ipsec_mp, mp, ipst);
26012 
26013 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
26014 
26015 		if (ipsec_mp != NULL)
26016 			ip_wput_local(RD(q), out_ill,
26017 			    ipha, ipsec_mp, ire, 0, zoneid);
26018 		if (ire_need_rele)
26019 			ire_refrele(ire);
26020 		goto done;
26021 	}
26022 
26023 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
26024 		/*
26025 		 * We are through with IPsec processing.
26026 		 * Fragment this and send it on the wire.
26027 		 */
26028 		if (io->ipsec_out_accelerated) {
26029 			/*
26030 			 * The packet has been accelerated but must
26031 			 * be fragmented. This should not happen
26032 			 * since AH and ESP must not accelerate
26033 			 * packets that need fragmentation, however
26034 			 * the configuration could have changed
26035 			 * since the AH or ESP processing.
26036 			 * Drop packet.
26037 			 * IPsec KSTATS: bump bean counter here.
26038 			 */
26039 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
26040 			    "fragmented accelerated packet!\n"));
26041 			freemsg(ipsec_mp);
26042 		} else {
26043 			ip_wput_ire_fragmentit(ipsec_mp, ire, zoneid, ipst);
26044 		}
26045 		if (ire_need_rele)
26046 			ire_refrele(ire);
26047 		goto done;
26048 	}
26049 
26050 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
26051 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
26052 	    (void *)ire->ire_ipif, (void *)ipif));
26053 
26054 	/*
26055 	 * Multiroute the secured packet, unless IPsec really
26056 	 * requires the packet to go out only through a particular
26057 	 * interface.
26058 	 */
26059 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
26060 		ire_t *first_ire;
26061 		irb = ire->ire_bucket;
26062 		ASSERT(irb != NULL);
26063 		/*
26064 		 * This ire has been looked up as the one that
26065 		 * goes through the given ipif;
26066 		 * make sure we do not omit any other multiroute ire
26067 		 * that may be present in the bucket before this one.
26068 		 */
26069 		IRB_REFHOLD(irb);
26070 		for (first_ire = irb->irb_ire;
26071 		    first_ire != NULL;
26072 		    first_ire = first_ire->ire_next) {
26073 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
26074 			    (first_ire->ire_addr == ire->ire_addr) &&
26075 			    !(first_ire->ire_marks &
26076 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
26077 				break;
26078 			}
26079 		}
26080 
26081 		if ((first_ire != NULL) && (first_ire != ire)) {
26082 			/*
26083 			 * Don't change the ire if the packet must
26084 			 * be fragmented if sent via this new one.
26085 			 */
26086 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26087 				IRE_REFHOLD(first_ire);
26088 				if (ire_need_rele)
26089 					ire_refrele(ire);
26090 				else
26091 					ire_need_rele = B_TRUE;
26092 				ire = first_ire;
26093 			}
26094 		}
26095 		IRB_REFRELE(irb);
26096 
26097 		multirt_send = B_TRUE;
26098 		max_frag = ire->ire_max_frag;
26099 	} else {
26100 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
26101 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
26102 			    "flag, attach_if %d\n", attach_if));
26103 		}
26104 	}
26105 
26106 	/*
26107 	 * In most cases, the emission loop below is entered only once.
26108 	 * Only in the case where the ire holds the RTF_MULTIRT
26109 	 * flag, we loop to process all RTF_MULTIRT ires in the
26110 	 * bucket, and send the packet through all crossed
26111 	 * RTF_MULTIRT routes.
26112 	 */
26113 	do {
26114 		if (multirt_send) {
26115 			/*
26116 			 * ire1 holds here the next ire to process in the
26117 			 * bucket. If multirouting is expected,
26118 			 * any non-RTF_MULTIRT ire that has the
26119 			 * right destination address is ignored.
26120 			 */
26121 			ASSERT(irb != NULL);
26122 			IRB_REFHOLD(irb);
26123 			for (ire1 = ire->ire_next;
26124 			    ire1 != NULL;
26125 			    ire1 = ire1->ire_next) {
26126 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26127 					continue;
26128 				if (ire1->ire_addr != ire->ire_addr)
26129 					continue;
26130 				if (ire1->ire_marks &
26131 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
26132 					continue;
26133 				/* No loopback here */
26134 				if (ire1->ire_stq == NULL)
26135 					continue;
26136 				/*
26137 				 * Ensure we do not exceed the MTU
26138 				 * of the next route.
26139 				 */
26140 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26141 					ip_multirt_bad_mtu(ire1, max_frag);
26142 					continue;
26143 				}
26144 
26145 				IRE_REFHOLD(ire1);
26146 				break;
26147 			}
26148 			IRB_REFRELE(irb);
26149 			if (ire1 != NULL) {
26150 				/*
26151 				 * We are in a multiple send case, need to
26152 				 * make a copy of the packet.
26153 				 */
26154 				next_mp = copymsg(ipsec_mp);
26155 				if (next_mp == NULL) {
26156 					ire_refrele(ire1);
26157 					ire1 = NULL;
26158 				}
26159 			}
26160 		}
26161 		/*
26162 		 * Everything is done. Send it out on the wire
26163 		 *
26164 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26165 		 * either send it on the wire or, in the case of
26166 		 * HW acceleration, call ipsec_hw_putnext.
26167 		 */
26168 		if (ire->ire_nce &&
26169 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26170 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26171 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26172 			/*
26173 			 * If ire's link-layer is unresolved (this
26174 			 * would only happen if the incomplete ire
26175 			 * was added to cachetable via forwarding path)
26176 			 * don't bother going to ip_xmit_v4. Just drop the
26177 			 * packet.
26178 			 * There is a slight risk here, in that, if we
26179 			 * have the forwarding path create an incomplete
26180 			 * IRE, then until the IRE is completed, any
26181 			 * transmitted IPsec packets will be dropped
26182 			 * instead of being queued waiting for resolution.
26183 			 *
26184 			 * But the likelihood of a forwarding packet and a wput
26185 			 * packet sending to the same dst at the same time
26186 			 * and there not yet be an ARP entry for it is small.
26187 			 * Furthermore, if this actually happens, it might
26188 			 * be likely that wput would generate multiple
26189 			 * packets (and forwarding would also have a train
26190 			 * of packets) for that destination. If this is
26191 			 * the case, some of them would have been dropped
26192 			 * anyway, since ARP only queues a few packets while
26193 			 * waiting for resolution
26194 			 *
26195 			 * NOTE: We should really call ip_xmit_v4,
26196 			 * and let it queue the packet and send the
26197 			 * ARP query and have ARP come back thus:
26198 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26199 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26200 			 * hw accel work. But it's too complex to get
26201 			 * the IPsec hw  acceleration approach to fit
26202 			 * well with ip_xmit_v4 doing ARP without
26203 			 * doing IPsec simplification. For now, we just
26204 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26205 			 * that we can continue with the send on the next
26206 			 * attempt.
26207 			 *
26208 			 * XXX THis should be revisited, when
26209 			 * the IPsec/IP interaction is cleaned up
26210 			 */
26211 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26212 			    " - dropping packet\n"));
26213 			freemsg(ipsec_mp);
26214 			/*
26215 			 * Call ip_xmit_v4() to trigger ARP query
26216 			 * in case the nce_state is ND_INITIAL
26217 			 */
26218 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
26219 			goto drop_pkt;
26220 		}
26221 
26222 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26223 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26224 		    mblk_t *, ipsec_mp);
26225 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26226 		    ipst->ips_ipv4firewall_physical_out,
26227 		    NULL, ire->ire_ipif->ipif_ill, ipha1, ipsec_mp, mp, ipst);
26228 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, ipsec_mp);
26229 		if (ipsec_mp == NULL)
26230 			goto drop_pkt;
26231 
26232 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26233 		pktxmit_state = ip_xmit_v4(mp, ire,
26234 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE);
26235 
26236 		if ((pktxmit_state ==  SEND_FAILED) ||
26237 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26238 
26239 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26240 drop_pkt:
26241 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26242 			    ipIfStatsOutDiscards);
26243 			if (ire_need_rele)
26244 				ire_refrele(ire);
26245 			if (ire1 != NULL) {
26246 				ire_refrele(ire1);
26247 				freemsg(next_mp);
26248 			}
26249 			goto done;
26250 		}
26251 
26252 		freeb(ipsec_mp);
26253 		if (ire_need_rele)
26254 			ire_refrele(ire);
26255 
26256 		if (ire1 != NULL) {
26257 			ire = ire1;
26258 			ire_need_rele = B_TRUE;
26259 			ASSERT(next_mp);
26260 			ipsec_mp = next_mp;
26261 			mp = ipsec_mp->b_cont;
26262 			ire1 = NULL;
26263 			next_mp = NULL;
26264 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26265 		} else {
26266 			multirt_send = B_FALSE;
26267 		}
26268 	} while (multirt_send);
26269 done:
26270 	if (ill != NULL && ill_need_rele)
26271 		ill_refrele(ill);
26272 	if (ipif != NULL)
26273 		ipif_refrele(ipif);
26274 }
26275 
26276 /*
26277  * Get the ill corresponding to the specified ire, and compare its
26278  * capabilities with the protocol and algorithms specified by the
26279  * the SA obtained from ipsec_out. If they match, annotate the
26280  * ipsec_out structure to indicate that the packet needs acceleration.
26281  *
26282  *
26283  * A packet is eligible for outbound hardware acceleration if the
26284  * following conditions are satisfied:
26285  *
26286  * 1. the packet will not be fragmented
26287  * 2. the provider supports the algorithm
26288  * 3. there is no pending control message being exchanged
26289  * 4. snoop is not attached
26290  * 5. the destination address is not a broadcast or multicast address.
26291  *
26292  * Rationale:
26293  *	- Hardware drivers do not support fragmentation with
26294  *	  the current interface.
26295  *	- snoop, multicast, and broadcast may result in exposure of
26296  *	  a cleartext datagram.
26297  * We check all five of these conditions here.
26298  *
26299  * XXX would like to nuke "ire_t *" parameter here; problem is that
26300  * IRE is only way to figure out if a v4 address is a broadcast and
26301  * thus ineligible for acceleration...
26302  */
26303 static void
26304 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26305 {
26306 	ipsec_out_t *io;
26307 	mblk_t *data_mp;
26308 	uint_t plen, overhead;
26309 	ip_stack_t	*ipst;
26310 
26311 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26312 		return;
26313 
26314 	if (ill == NULL)
26315 		return;
26316 	ipst = ill->ill_ipst;
26317 	/*
26318 	 * Destination address is a broadcast or multicast.  Punt.
26319 	 */
26320 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26321 	    IRE_LOCAL)))
26322 		return;
26323 
26324 	data_mp = ipsec_mp->b_cont;
26325 
26326 	if (ill->ill_isv6) {
26327 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26328 
26329 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26330 			return;
26331 
26332 		plen = ip6h->ip6_plen;
26333 	} else {
26334 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26335 
26336 		if (CLASSD(ipha->ipha_dst))
26337 			return;
26338 
26339 		plen = ipha->ipha_length;
26340 	}
26341 	/*
26342 	 * Is there a pending DLPI control message being exchanged
26343 	 * between IP/IPsec and the DLS Provider? If there is, it
26344 	 * could be a SADB update, and the state of the DLS Provider
26345 	 * SADB might not be in sync with the SADB maintained by
26346 	 * IPsec. To avoid dropping packets or using the wrong keying
26347 	 * material, we do not accelerate this packet.
26348 	 */
26349 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26350 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26351 		    "ill_dlpi_pending! don't accelerate packet\n"));
26352 		return;
26353 	}
26354 
26355 	/*
26356 	 * Is the Provider in promiscous mode? If it does, we don't
26357 	 * accelerate the packet since it will bounce back up to the
26358 	 * listeners in the clear.
26359 	 */
26360 	if (ill->ill_promisc_on_phys) {
26361 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26362 		    "ill in promiscous mode, don't accelerate packet\n"));
26363 		return;
26364 	}
26365 
26366 	/*
26367 	 * Will the packet require fragmentation?
26368 	 */
26369 
26370 	/*
26371 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26372 	 * as is used elsewhere.
26373 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26374 	 *	+ 2-byte trailer
26375 	 */
26376 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26377 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26378 
26379 	if ((plen + overhead) > ill->ill_max_mtu)
26380 		return;
26381 
26382 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26383 
26384 	/*
26385 	 * Can the ill accelerate this IPsec protocol and algorithm
26386 	 * specified by the SA?
26387 	 */
26388 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26389 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26390 		return;
26391 	}
26392 
26393 	/*
26394 	 * Tell AH or ESP that the outbound ill is capable of
26395 	 * accelerating this packet.
26396 	 */
26397 	io->ipsec_out_is_capab_ill = B_TRUE;
26398 }
26399 
26400 /*
26401  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26402  *
26403  * If this function returns B_TRUE, the requested SA's have been filled
26404  * into the ipsec_out_*_sa pointers.
26405  *
26406  * If the function returns B_FALSE, the packet has been "consumed", most
26407  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26408  *
26409  * The SA references created by the protocol-specific "select"
26410  * function will be released when the ipsec_mp is freed, thanks to the
26411  * ipsec_out_free destructor -- see spd.c.
26412  */
26413 static boolean_t
26414 ipsec_out_select_sa(mblk_t *ipsec_mp)
26415 {
26416 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26417 	ipsec_out_t *io;
26418 	ipsec_policy_t *pp;
26419 	ipsec_action_t *ap;
26420 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26421 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26422 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26423 
26424 	if (!io->ipsec_out_secure) {
26425 		/*
26426 		 * We came here by mistake.
26427 		 * Don't bother with ipsec processing
26428 		 * We should "discourage" this path in the future.
26429 		 */
26430 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26431 		return (B_FALSE);
26432 	}
26433 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26434 	ASSERT((io->ipsec_out_policy != NULL) ||
26435 	    (io->ipsec_out_act != NULL));
26436 
26437 	ASSERT(io->ipsec_out_failed == B_FALSE);
26438 
26439 	/*
26440 	 * IPsec processing has started.
26441 	 */
26442 	io->ipsec_out_proc_begin = B_TRUE;
26443 	ap = io->ipsec_out_act;
26444 	if (ap == NULL) {
26445 		pp = io->ipsec_out_policy;
26446 		ASSERT(pp != NULL);
26447 		ap = pp->ipsp_act;
26448 		ASSERT(ap != NULL);
26449 	}
26450 
26451 	/*
26452 	 * We have an action.  now, let's select SA's.
26453 	 * (In the future, we can cache this in the conn_t..)
26454 	 */
26455 	if (ap->ipa_want_esp) {
26456 		if (io->ipsec_out_esp_sa == NULL) {
26457 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26458 			    IPPROTO_ESP);
26459 		}
26460 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26461 	}
26462 
26463 	if (ap->ipa_want_ah) {
26464 		if (io->ipsec_out_ah_sa == NULL) {
26465 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26466 			    IPPROTO_AH);
26467 		}
26468 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26469 		/*
26470 		 * The ESP and AH processing order needs to be preserved
26471 		 * when both protocols are required (ESP should be applied
26472 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26473 		 * when both ESP and AH are required, and an AH ACQUIRE
26474 		 * is needed.
26475 		 */
26476 		if (ap->ipa_want_esp && need_ah_acquire)
26477 			need_esp_acquire = B_TRUE;
26478 	}
26479 
26480 	/*
26481 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26482 	 * Release SAs that got referenced, but will not be used until we
26483 	 * acquire _all_ of the SAs we need.
26484 	 */
26485 	if (need_ah_acquire || need_esp_acquire) {
26486 		if (io->ipsec_out_ah_sa != NULL) {
26487 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26488 			io->ipsec_out_ah_sa = NULL;
26489 		}
26490 		if (io->ipsec_out_esp_sa != NULL) {
26491 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26492 			io->ipsec_out_esp_sa = NULL;
26493 		}
26494 
26495 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26496 		return (B_FALSE);
26497 	}
26498 
26499 	return (B_TRUE);
26500 }
26501 
26502 /*
26503  * Process an IPSEC_OUT message and see what you can
26504  * do with it.
26505  * IPQoS Notes:
26506  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26507  * IPsec.
26508  * XXX would like to nuke ire_t.
26509  * XXX ill_index better be "real"
26510  */
26511 void
26512 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26513 {
26514 	ipsec_out_t *io;
26515 	ipsec_policy_t *pp;
26516 	ipsec_action_t *ap;
26517 	ipha_t *ipha;
26518 	ip6_t *ip6h;
26519 	mblk_t *mp;
26520 	ill_t *ill;
26521 	zoneid_t zoneid;
26522 	ipsec_status_t ipsec_rc;
26523 	boolean_t ill_need_rele = B_FALSE;
26524 	ip_stack_t	*ipst;
26525 	ipsec_stack_t	*ipss;
26526 
26527 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26528 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26529 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26530 	ipst = io->ipsec_out_ns->netstack_ip;
26531 	mp = ipsec_mp->b_cont;
26532 
26533 	/*
26534 	 * Initiate IPPF processing. We do it here to account for packets
26535 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26536 	 * We can check for ipsec_out_proc_begin even for such packets, as
26537 	 * they will always be false (asserted below).
26538 	 */
26539 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26540 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26541 		    io->ipsec_out_ill_index : ill_index);
26542 		if (mp == NULL) {
26543 			ip2dbg(("ipsec_out_process: packet dropped "\
26544 			    "during IPPF processing\n"));
26545 			freeb(ipsec_mp);
26546 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26547 			return;
26548 		}
26549 	}
26550 
26551 	if (!io->ipsec_out_secure) {
26552 		/*
26553 		 * We came here by mistake.
26554 		 * Don't bother with ipsec processing
26555 		 * Should "discourage" this path in the future.
26556 		 */
26557 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26558 		goto done;
26559 	}
26560 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26561 	ASSERT((io->ipsec_out_policy != NULL) ||
26562 	    (io->ipsec_out_act != NULL));
26563 	ASSERT(io->ipsec_out_failed == B_FALSE);
26564 
26565 	ipss = ipst->ips_netstack->netstack_ipsec;
26566 	if (!ipsec_loaded(ipss)) {
26567 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26568 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26569 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26570 		} else {
26571 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26572 		}
26573 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26574 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26575 		    &ipss->ipsec_dropper);
26576 		return;
26577 	}
26578 
26579 	/*
26580 	 * IPsec processing has started.
26581 	 */
26582 	io->ipsec_out_proc_begin = B_TRUE;
26583 	ap = io->ipsec_out_act;
26584 	if (ap == NULL) {
26585 		pp = io->ipsec_out_policy;
26586 		ASSERT(pp != NULL);
26587 		ap = pp->ipsp_act;
26588 		ASSERT(ap != NULL);
26589 	}
26590 
26591 	/*
26592 	 * Save the outbound ill index. When the packet comes back
26593 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26594 	 * before sending it the accelerated packet.
26595 	 */
26596 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26597 		int ifindex;
26598 		ill = ire_to_ill(ire);
26599 		ifindex = ill->ill_phyint->phyint_ifindex;
26600 		io->ipsec_out_capab_ill_index = ifindex;
26601 	}
26602 
26603 	/*
26604 	 * The order of processing is first insert a IP header if needed.
26605 	 * Then insert the ESP header and then the AH header.
26606 	 */
26607 	if ((io->ipsec_out_se_done == B_FALSE) &&
26608 	    (ap->ipa_want_se)) {
26609 		/*
26610 		 * First get the outer IP header before sending
26611 		 * it to ESP.
26612 		 */
26613 		ipha_t *oipha, *iipha;
26614 		mblk_t *outer_mp, *inner_mp;
26615 
26616 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26617 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26618 			    "ipsec_out_process: "
26619 			    "Self-Encapsulation failed: Out of memory\n");
26620 			freemsg(ipsec_mp);
26621 			if (ill != NULL) {
26622 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26623 			} else {
26624 				BUMP_MIB(&ipst->ips_ip_mib,
26625 				    ipIfStatsOutDiscards);
26626 			}
26627 			return;
26628 		}
26629 		inner_mp = ipsec_mp->b_cont;
26630 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26631 		oipha = (ipha_t *)outer_mp->b_rptr;
26632 		iipha = (ipha_t *)inner_mp->b_rptr;
26633 		*oipha = *iipha;
26634 		outer_mp->b_wptr += sizeof (ipha_t);
26635 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26636 		    sizeof (ipha_t));
26637 		oipha->ipha_protocol = IPPROTO_ENCAP;
26638 		oipha->ipha_version_and_hdr_length =
26639 		    IP_SIMPLE_HDR_VERSION;
26640 		oipha->ipha_hdr_checksum = 0;
26641 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26642 		outer_mp->b_cont = inner_mp;
26643 		ipsec_mp->b_cont = outer_mp;
26644 
26645 		io->ipsec_out_se_done = B_TRUE;
26646 		io->ipsec_out_tunnel = B_TRUE;
26647 	}
26648 
26649 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26650 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26651 	    !ipsec_out_select_sa(ipsec_mp))
26652 		return;
26653 
26654 	/*
26655 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26656 	 * to do the heavy lifting.
26657 	 */
26658 	zoneid = io->ipsec_out_zoneid;
26659 	ASSERT(zoneid != ALL_ZONES);
26660 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26661 		ASSERT(io->ipsec_out_esp_sa != NULL);
26662 		io->ipsec_out_esp_done = B_TRUE;
26663 		/*
26664 		 * Note that since hw accel can only apply one transform,
26665 		 * not two, we skip hw accel for ESP if we also have AH
26666 		 * This is an design limitation of the interface
26667 		 * which should be revisited.
26668 		 */
26669 		ASSERT(ire != NULL);
26670 		if (io->ipsec_out_ah_sa == NULL) {
26671 			ill = (ill_t *)ire->ire_stq->q_ptr;
26672 			ipsec_out_is_accelerated(ipsec_mp,
26673 			    io->ipsec_out_esp_sa, ill, ire);
26674 		}
26675 
26676 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26677 		switch (ipsec_rc) {
26678 		case IPSEC_STATUS_SUCCESS:
26679 			break;
26680 		case IPSEC_STATUS_FAILED:
26681 			if (ill != NULL) {
26682 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26683 			} else {
26684 				BUMP_MIB(&ipst->ips_ip_mib,
26685 				    ipIfStatsOutDiscards);
26686 			}
26687 			/* FALLTHRU */
26688 		case IPSEC_STATUS_PENDING:
26689 			return;
26690 		}
26691 	}
26692 
26693 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
26694 		ASSERT(io->ipsec_out_ah_sa != NULL);
26695 		io->ipsec_out_ah_done = B_TRUE;
26696 		if (ire == NULL) {
26697 			int idx = io->ipsec_out_capab_ill_index;
26698 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
26699 			    NULL, NULL, NULL, NULL, ipst);
26700 			ill_need_rele = B_TRUE;
26701 		} else {
26702 			ill = (ill_t *)ire->ire_stq->q_ptr;
26703 		}
26704 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
26705 		    ire);
26706 
26707 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
26708 		switch (ipsec_rc) {
26709 		case IPSEC_STATUS_SUCCESS:
26710 			break;
26711 		case IPSEC_STATUS_FAILED:
26712 			if (ill != NULL) {
26713 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26714 			} else {
26715 				BUMP_MIB(&ipst->ips_ip_mib,
26716 				    ipIfStatsOutDiscards);
26717 			}
26718 			/* FALLTHRU */
26719 		case IPSEC_STATUS_PENDING:
26720 			if (ill != NULL && ill_need_rele)
26721 				ill_refrele(ill);
26722 			return;
26723 		}
26724 	}
26725 	/*
26726 	 * We are done with IPsec processing. Send it over
26727 	 * the wire.
26728 	 */
26729 done:
26730 	mp = ipsec_mp->b_cont;
26731 	ipha = (ipha_t *)mp->b_rptr;
26732 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26733 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
26734 	} else {
26735 		ip6h = (ip6_t *)ipha;
26736 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
26737 	}
26738 	if (ill != NULL && ill_need_rele)
26739 		ill_refrele(ill);
26740 }
26741 
26742 /* ARGSUSED */
26743 void
26744 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
26745 {
26746 	opt_restart_t	*or;
26747 	int	err;
26748 	conn_t	*connp;
26749 
26750 	ASSERT(CONN_Q(q));
26751 	connp = Q_TO_CONN(q);
26752 
26753 	ASSERT(first_mp->b_datap->db_type == M_CTL);
26754 	or = (opt_restart_t *)first_mp->b_rptr;
26755 	/*
26756 	 * We don't need to pass any credentials here since this is just
26757 	 * a restart. The credentials are passed in when svr4_optcom_req
26758 	 * is called the first time (from ip_wput_nondata).
26759 	 */
26760 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
26761 		err = svr4_optcom_req(q, first_mp, NULL,
26762 		    &ip_opt_obj, B_FALSE);
26763 	} else {
26764 		ASSERT(or->or_type == T_OPTMGMT_REQ);
26765 		err = tpi_optcom_req(q, first_mp, NULL,
26766 		    &ip_opt_obj, B_FALSE);
26767 	}
26768 	if (err != EINPROGRESS) {
26769 		/* operation is done */
26770 		CONN_OPER_PENDING_DONE(connp);
26771 	}
26772 }
26773 
26774 /*
26775  * ioctls that go through a down/up sequence may need to wait for the down
26776  * to complete. This involves waiting for the ire and ipif refcnts to go down
26777  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
26778  */
26779 /* ARGSUSED */
26780 void
26781 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26782 {
26783 	struct iocblk *iocp;
26784 	mblk_t *mp1;
26785 	ip_ioctl_cmd_t *ipip;
26786 	int err;
26787 	sin_t	*sin;
26788 	struct lifreq *lifr;
26789 	struct ifreq *ifr;
26790 
26791 	iocp = (struct iocblk *)mp->b_rptr;
26792 	ASSERT(ipsq != NULL);
26793 	/* Existence of mp1 verified in ip_wput_nondata */
26794 	mp1 = mp->b_cont->b_cont;
26795 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26796 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
26797 		/*
26798 		 * Special case where ipsq_current_ipif is not set:
26799 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
26800 		 * ill could also have become part of a ipmp group in the
26801 		 * process, we are here as were not able to complete the
26802 		 * operation in ipif_set_values because we could not become
26803 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
26804 		 * will not be set so we need to set it.
26805 		 */
26806 		ill_t *ill = q->q_ptr;
26807 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
26808 	}
26809 	ASSERT(ipsq->ipsq_current_ipif != NULL);
26810 
26811 	if (ipip->ipi_cmd_type == IF_CMD) {
26812 		/* This a old style SIOC[GS]IF* command */
26813 		ifr = (struct ifreq *)mp1->b_rptr;
26814 		sin = (sin_t *)&ifr->ifr_addr;
26815 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
26816 		/* This a new style SIOC[GS]LIF* command */
26817 		lifr = (struct lifreq *)mp1->b_rptr;
26818 		sin = (sin_t *)&lifr->lifr_addr;
26819 	} else {
26820 		sin = NULL;
26821 	}
26822 
26823 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_current_ipif, sin, q, mp,
26824 	    ipip, mp1->b_rptr);
26825 
26826 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26827 }
26828 
26829 /*
26830  * ioctl processing
26831  *
26832  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
26833  * the ioctl command in the ioctl tables, determines the copyin data size
26834  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
26835  *
26836  * ioctl processing then continues when the M_IOCDATA makes its way down to
26837  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
26838  * associated 'conn' is refheld till the end of the ioctl and the general
26839  * ioctl processing function ip_process_ioctl() is called to extract the
26840  * arguments and process the ioctl.  To simplify extraction, ioctl commands
26841  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
26842  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
26843  * is used to extract the ioctl's arguments.
26844  *
26845  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
26846  * so goes thru the serialization primitive ipsq_try_enter. Then the
26847  * appropriate function to handle the ioctl is called based on the entry in
26848  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
26849  * which also refreleases the 'conn' that was refheld at the start of the
26850  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
26851  *
26852  * Many exclusive ioctls go thru an internal down up sequence as part of
26853  * the operation. For example an attempt to change the IP address of an
26854  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
26855  * does all the cleanup such as deleting all ires that use this address.
26856  * Then we need to wait till all references to the interface go away.
26857  */
26858 void
26859 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
26860 {
26861 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
26862 	ip_ioctl_cmd_t *ipip = arg;
26863 	ip_extract_func_t *extract_funcp;
26864 	cmd_info_t ci;
26865 	int err;
26866 	boolean_t entered_ipsq = B_FALSE;
26867 
26868 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
26869 
26870 	if (ipip == NULL)
26871 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26872 
26873 	/*
26874 	 * SIOCLIFADDIF needs to go thru a special path since the
26875 	 * ill may not exist yet. This happens in the case of lo0
26876 	 * which is created using this ioctl.
26877 	 */
26878 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
26879 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
26880 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26881 		return;
26882 	}
26883 
26884 	ci.ci_ipif = NULL;
26885 	if (ipip->ipi_cmd_type == MISC_CMD) {
26886 		/*
26887 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
26888 		 */
26889 		if (ipip->ipi_cmd == IF_UNITSEL) {
26890 			/* ioctl comes down the ill */
26891 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
26892 			ipif_refhold(ci.ci_ipif);
26893 		}
26894 		err = 0;
26895 		ci.ci_sin = NULL;
26896 		ci.ci_sin6 = NULL;
26897 		ci.ci_lifr = NULL;
26898 	} else {
26899 		switch (ipip->ipi_cmd_type) {
26900 		case IF_CMD:
26901 		case LIF_CMD:
26902 			extract_funcp = ip_extract_lifreq;
26903 			break;
26904 
26905 		case ARP_CMD:
26906 		case XARP_CMD:
26907 			extract_funcp = ip_extract_arpreq;
26908 			break;
26909 
26910 		case TUN_CMD:
26911 			extract_funcp = ip_extract_tunreq;
26912 			break;
26913 
26914 		case MSFILT_CMD:
26915 			extract_funcp = ip_extract_msfilter;
26916 			break;
26917 
26918 		default:
26919 			ASSERT(0);
26920 		}
26921 
26922 		err = (*extract_funcp)(q, mp, ipip, &ci, ip_process_ioctl);
26923 		if (err != 0) {
26924 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26925 			return;
26926 		}
26927 
26928 		/*
26929 		 * All of the extraction functions return a refheld ipif.
26930 		 */
26931 		ASSERT(ci.ci_ipif != NULL);
26932 	}
26933 
26934 	/*
26935 	 * If ipsq is non-null, we are already being called exclusively
26936 	 */
26937 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
26938 	if (!(ipip->ipi_flags & IPI_WR)) {
26939 		/*
26940 		 * A return value of EINPROGRESS means the ioctl is
26941 		 * either queued and waiting for some reason or has
26942 		 * already completed.
26943 		 */
26944 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
26945 		    ci.ci_lifr);
26946 		if (ci.ci_ipif != NULL)
26947 			ipif_refrele(ci.ci_ipif);
26948 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26949 		return;
26950 	}
26951 
26952 	ASSERT(ci.ci_ipif != NULL);
26953 
26954 	if (ipsq == NULL) {
26955 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
26956 		    ip_process_ioctl, NEW_OP, B_TRUE);
26957 		entered_ipsq = B_TRUE;
26958 	}
26959 	/*
26960 	 * Release the ipif so that ipif_down and friends that wait for
26961 	 * references to go away are not misled about the current ipif_refcnt
26962 	 * values. We are writer so we can access the ipif even after releasing
26963 	 * the ipif.
26964 	 */
26965 	ipif_refrele(ci.ci_ipif);
26966 	if (ipsq == NULL)
26967 		return;
26968 
26969 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
26970 
26971 	/*
26972 	 * For most set ioctls that come here, this serves as a single point
26973 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
26974 	 * be any new references to the ipif. This helps functions that go
26975 	 * through this path and end up trying to wait for the refcnts
26976 	 * associated with the ipif to go down to zero. Some exceptions are
26977 	 * Failover, Failback, and Groupname commands that operate on more than
26978 	 * just the ci.ci_ipif. These commands internally determine the
26979 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
26980 	 * flags on that set. Another exception is the Removeif command that
26981 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
26982 	 * ipif to operate on.
26983 	 */
26984 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
26985 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
26986 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
26987 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
26988 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
26989 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
26990 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
26991 
26992 	/*
26993 	 * A return value of EINPROGRESS means the ioctl is
26994 	 * either queued and waiting for some reason or has
26995 	 * already completed.
26996 	 */
26997 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
26998 
26999 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27000 
27001 	if (entered_ipsq)
27002 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
27003 }
27004 
27005 /*
27006  * Complete the ioctl. Typically ioctls use the mi package and need to
27007  * do mi_copyout/mi_copy_done.
27008  */
27009 void
27010 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
27011 {
27012 	conn_t	*connp = NULL;
27013 
27014 	if (err == EINPROGRESS)
27015 		return;
27016 
27017 	if (CONN_Q(q)) {
27018 		connp = Q_TO_CONN(q);
27019 		ASSERT(connp->conn_ref >= 2);
27020 	}
27021 
27022 	switch (mode) {
27023 	case COPYOUT:
27024 		if (err == 0)
27025 			mi_copyout(q, mp);
27026 		else
27027 			mi_copy_done(q, mp, err);
27028 		break;
27029 
27030 	case NO_COPYOUT:
27031 		mi_copy_done(q, mp, err);
27032 		break;
27033 
27034 	default:
27035 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
27036 		break;
27037 	}
27038 
27039 	/*
27040 	 * The refhold placed at the start of the ioctl is released here.
27041 	 */
27042 	if (connp != NULL)
27043 		CONN_OPER_PENDING_DONE(connp);
27044 
27045 	if (ipsq != NULL)
27046 		ipsq_current_finish(ipsq);
27047 }
27048 
27049 /*
27050  * This is called from ip_wput_nondata to resume a deferred TCP bind.
27051  */
27052 /* ARGSUSED */
27053 void
27054 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
27055 {
27056 	conn_t *connp = arg;
27057 	tcp_t	*tcp;
27058 
27059 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
27060 	tcp = connp->conn_tcp;
27061 
27062 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
27063 		freemsg(mp);
27064 	else
27065 		tcp_rput_other(tcp, mp);
27066 	CONN_OPER_PENDING_DONE(connp);
27067 }
27068 
27069 /* Called from ip_wput for all non data messages */
27070 /* ARGSUSED */
27071 void
27072 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27073 {
27074 	mblk_t		*mp1;
27075 	ire_t		*ire, *fake_ire;
27076 	ill_t		*ill;
27077 	struct iocblk	*iocp;
27078 	ip_ioctl_cmd_t	*ipip;
27079 	cred_t		*cr;
27080 	conn_t		*connp;
27081 	int		err;
27082 	nce_t		*nce;
27083 	ipif_t		*ipif;
27084 	ip_stack_t	*ipst;
27085 	char		*proto_str;
27086 
27087 	if (CONN_Q(q)) {
27088 		connp = Q_TO_CONN(q);
27089 		ipst = connp->conn_netstack->netstack_ip;
27090 	} else {
27091 		connp = NULL;
27092 		ipst = ILLQ_TO_IPST(q);
27093 	}
27094 
27095 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
27096 
27097 	switch (DB_TYPE(mp)) {
27098 	case M_IOCTL:
27099 		/*
27100 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
27101 		 * will arrange to copy in associated control structures.
27102 		 */
27103 		ip_sioctl_copyin_setup(q, mp);
27104 		return;
27105 	case M_IOCDATA:
27106 		/*
27107 		 * Ensure that this is associated with one of our trans-
27108 		 * parent ioctls.  If it's not ours, discard it if we're
27109 		 * running as a driver, or pass it on if we're a module.
27110 		 */
27111 		iocp = (struct iocblk *)mp->b_rptr;
27112 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27113 		if (ipip == NULL) {
27114 			if (q->q_next == NULL) {
27115 				goto nak;
27116 			} else {
27117 				putnext(q, mp);
27118 			}
27119 			return;
27120 		}
27121 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
27122 			/*
27123 			 * the ioctl is one we recognise, but is not
27124 			 * consumed by IP as a module, pass M_IOCDATA
27125 			 * for processing downstream, but only for
27126 			 * common Streams ioctls.
27127 			 */
27128 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27129 				putnext(q, mp);
27130 				return;
27131 			} else {
27132 				goto nak;
27133 			}
27134 		}
27135 
27136 		/* IOCTL continuation following copyin or copyout. */
27137 		if (mi_copy_state(q, mp, NULL) == -1) {
27138 			/*
27139 			 * The copy operation failed.  mi_copy_state already
27140 			 * cleaned up, so we're out of here.
27141 			 */
27142 			return;
27143 		}
27144 		/*
27145 		 * If we just completed a copy in, we become writer and
27146 		 * continue processing in ip_sioctl_copyin_done.  If it
27147 		 * was a copy out, we call mi_copyout again.  If there is
27148 		 * nothing more to copy out, it will complete the IOCTL.
27149 		 */
27150 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27151 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27152 				mi_copy_done(q, mp, EPROTO);
27153 				return;
27154 			}
27155 			/*
27156 			 * Check for cases that need more copying.  A return
27157 			 * value of 0 means a second copyin has been started,
27158 			 * so we return; a return value of 1 means no more
27159 			 * copying is needed, so we continue.
27160 			 */
27161 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
27162 			    MI_COPY_COUNT(mp) == 1) {
27163 				if (ip_copyin_msfilter(q, mp) == 0)
27164 					return;
27165 			}
27166 			/*
27167 			 * Refhold the conn, till the ioctl completes. This is
27168 			 * needed in case the ioctl ends up in the pending mp
27169 			 * list. Every mp in the ill_pending_mp list and
27170 			 * the ipsq_pending_mp must have a refhold on the conn
27171 			 * to resume processing. The refhold is released when
27172 			 * the ioctl completes. (normally or abnormally)
27173 			 * In all cases ip_ioctl_finish is called to finish
27174 			 * the ioctl.
27175 			 */
27176 			if (connp != NULL) {
27177 				/* This is not a reentry */
27178 				ASSERT(ipsq == NULL);
27179 				CONN_INC_REF(connp);
27180 			} else {
27181 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27182 					mi_copy_done(q, mp, EINVAL);
27183 					return;
27184 				}
27185 			}
27186 
27187 			ip_process_ioctl(ipsq, q, mp, ipip);
27188 
27189 		} else {
27190 			mi_copyout(q, mp);
27191 		}
27192 		return;
27193 nak:
27194 		iocp->ioc_error = EINVAL;
27195 		mp->b_datap->db_type = M_IOCNAK;
27196 		iocp->ioc_count = 0;
27197 		qreply(q, mp);
27198 		return;
27199 
27200 	case M_IOCNAK:
27201 		/*
27202 		 * The only way we could get here is if a resolver didn't like
27203 		 * an IOCTL we sent it.	 This shouldn't happen.
27204 		 */
27205 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27206 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27207 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27208 		freemsg(mp);
27209 		return;
27210 	case M_IOCACK:
27211 		/* /dev/ip shouldn't see this */
27212 		if (CONN_Q(q))
27213 			goto nak;
27214 
27215 		/* Finish socket ioctls passed through to ARP. */
27216 		ip_sioctl_iocack(q, mp);
27217 		return;
27218 	case M_FLUSH:
27219 		if (*mp->b_rptr & FLUSHW)
27220 			flushq(q, FLUSHALL);
27221 		if (q->q_next) {
27222 			putnext(q, mp);
27223 			return;
27224 		}
27225 		if (*mp->b_rptr & FLUSHR) {
27226 			*mp->b_rptr &= ~FLUSHW;
27227 			qreply(q, mp);
27228 			return;
27229 		}
27230 		freemsg(mp);
27231 		return;
27232 	case IRE_DB_REQ_TYPE:
27233 		if (connp == NULL) {
27234 			proto_str = "IRE_DB_REQ_TYPE";
27235 			goto protonak;
27236 		}
27237 		/* An Upper Level Protocol wants a copy of an IRE. */
27238 		ip_ire_req(q, mp);
27239 		return;
27240 	case M_CTL:
27241 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27242 			break;
27243 
27244 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27245 		    TUN_HELLO) {
27246 			ASSERT(connp != NULL);
27247 			connp->conn_flags |= IPCL_IPTUN;
27248 			freeb(mp);
27249 			return;
27250 		}
27251 
27252 		/* M_CTL messages are used by ARP to tell us things. */
27253 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27254 			break;
27255 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27256 		case AR_ENTRY_SQUERY:
27257 			ip_wput_ctl(q, mp);
27258 			return;
27259 		case AR_CLIENT_NOTIFY:
27260 			ip_arp_news(q, mp);
27261 			return;
27262 		case AR_DLPIOP_DONE:
27263 			ASSERT(q->q_next != NULL);
27264 			ill = (ill_t *)q->q_ptr;
27265 			/* qwriter_ip releases the refhold */
27266 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27267 			ill_refhold(ill);
27268 			qwriter_ip(ill, q, mp, ip_arp_done, CUR_OP, B_FALSE);
27269 			return;
27270 		case AR_ARP_CLOSING:
27271 			/*
27272 			 * ARP (above us) is closing. If no ARP bringup is
27273 			 * currently pending, ack the message so that ARP
27274 			 * can complete its close. Also mark ill_arp_closing
27275 			 * so that new ARP bringups will fail. If any
27276 			 * ARP bringup is currently in progress, we will
27277 			 * ack this when the current ARP bringup completes.
27278 			 */
27279 			ASSERT(q->q_next != NULL);
27280 			ill = (ill_t *)q->q_ptr;
27281 			mutex_enter(&ill->ill_lock);
27282 			ill->ill_arp_closing = 1;
27283 			if (!ill->ill_arp_bringup_pending) {
27284 				mutex_exit(&ill->ill_lock);
27285 				qreply(q, mp);
27286 			} else {
27287 				mutex_exit(&ill->ill_lock);
27288 				freemsg(mp);
27289 			}
27290 			return;
27291 		case AR_ARP_EXTEND:
27292 			/*
27293 			 * The ARP module above us is capable of duplicate
27294 			 * address detection.  Old ATM drivers will not send
27295 			 * this message.
27296 			 */
27297 			ASSERT(q->q_next != NULL);
27298 			ill = (ill_t *)q->q_ptr;
27299 			ill->ill_arp_extend = B_TRUE;
27300 			freemsg(mp);
27301 			return;
27302 		default:
27303 			break;
27304 		}
27305 		break;
27306 	case M_PROTO:
27307 	case M_PCPROTO:
27308 		/*
27309 		 * The only PROTO messages we expect are ULP binds and
27310 		 * copies of option negotiation acknowledgements.
27311 		 */
27312 		switch (((union T_primitives *)mp->b_rptr)->type) {
27313 		case O_T_BIND_REQ:
27314 		case T_BIND_REQ: {
27315 			/* Request can get queued in bind */
27316 			if (connp == NULL) {
27317 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27318 				goto protonak;
27319 			}
27320 			/*
27321 			 * The transports except SCTP call ip_bind_{v4,v6}()
27322 			 * directly instead of a a putnext. SCTP doesn't
27323 			 * generate any T_BIND_REQ since it has its own
27324 			 * fanout data structures. However, ESP and AH
27325 			 * come in for regular binds; all other cases are
27326 			 * bind retries.
27327 			 */
27328 			ASSERT(!IPCL_IS_SCTP(connp));
27329 
27330 			/* Don't increment refcnt if this is a re-entry */
27331 			if (ipsq == NULL)
27332 				CONN_INC_REF(connp);
27333 
27334 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27335 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27336 			if (mp == NULL)
27337 				return;
27338 			if (IPCL_IS_TCP(connp)) {
27339 				/*
27340 				 * In the case of TCP endpoint we
27341 				 * come here only for bind retries
27342 				 */
27343 				ASSERT(ipsq != NULL);
27344 				CONN_INC_REF(connp);
27345 				squeue_fill(connp->conn_sqp, mp,
27346 				    ip_resume_tcp_bind, connp,
27347 				    SQTAG_BIND_RETRY);
27348 			} else if (IPCL_IS_UDP(connp)) {
27349 				/*
27350 				 * In the case of UDP endpoint we
27351 				 * come here only for bind retries
27352 				 */
27353 				ASSERT(ipsq != NULL);
27354 				udp_resume_bind(connp, mp);
27355 			} else if (IPCL_IS_RAWIP(connp)) {
27356 				/*
27357 				 * In the case of RAWIP endpoint we
27358 				 * come here only for bind retries
27359 				 */
27360 				ASSERT(ipsq != NULL);
27361 				rawip_resume_bind(connp, mp);
27362 			} else {
27363 				/* The case of AH and ESP */
27364 				qreply(q, mp);
27365 				CONN_OPER_PENDING_DONE(connp);
27366 			}
27367 			return;
27368 		}
27369 		case T_SVR4_OPTMGMT_REQ:
27370 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27371 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27372 
27373 			if (connp == NULL) {
27374 				proto_str = "T_SVR4_OPTMGMT_REQ";
27375 				goto protonak;
27376 			}
27377 
27378 			if (!snmpcom_req(q, mp, ip_snmp_set,
27379 			    ip_snmp_get, cr)) {
27380 				/*
27381 				 * Call svr4_optcom_req so that it can
27382 				 * generate the ack. We don't come here
27383 				 * if this operation is being restarted.
27384 				 * ip_restart_optmgmt will drop the conn ref.
27385 				 * In the case of ipsec option after the ipsec
27386 				 * load is complete conn_restart_ipsec_waiter
27387 				 * drops the conn ref.
27388 				 */
27389 				ASSERT(ipsq == NULL);
27390 				CONN_INC_REF(connp);
27391 				if (ip_check_for_ipsec_opt(q, mp))
27392 					return;
27393 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj,
27394 				    B_FALSE);
27395 				if (err != EINPROGRESS) {
27396 					/* Operation is done */
27397 					CONN_OPER_PENDING_DONE(connp);
27398 				}
27399 			}
27400 			return;
27401 		case T_OPTMGMT_REQ:
27402 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27403 			/*
27404 			 * Note: No snmpcom_req support through new
27405 			 * T_OPTMGMT_REQ.
27406 			 * Call tpi_optcom_req so that it can
27407 			 * generate the ack.
27408 			 */
27409 			if (connp == NULL) {
27410 				proto_str = "T_OPTMGMT_REQ";
27411 				goto protonak;
27412 			}
27413 
27414 			ASSERT(ipsq == NULL);
27415 			/*
27416 			 * We don't come here for restart. ip_restart_optmgmt
27417 			 * will drop the conn ref. In the case of ipsec option
27418 			 * after the ipsec load is complete
27419 			 * conn_restart_ipsec_waiter drops the conn ref.
27420 			 */
27421 			CONN_INC_REF(connp);
27422 			if (ip_check_for_ipsec_opt(q, mp))
27423 				return;
27424 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj, B_FALSE);
27425 			if (err != EINPROGRESS) {
27426 				/* Operation is done */
27427 				CONN_OPER_PENDING_DONE(connp);
27428 			}
27429 			return;
27430 		case T_UNBIND_REQ:
27431 			if (connp == NULL) {
27432 				proto_str = "T_UNBIND_REQ";
27433 				goto protonak;
27434 			}
27435 			mp = ip_unbind(q, mp);
27436 			qreply(q, mp);
27437 			return;
27438 		default:
27439 			/*
27440 			 * Have to drop any DLPI messages coming down from
27441 			 * arp (such as an info_req which would cause ip
27442 			 * to receive an extra info_ack if it was passed
27443 			 * through.
27444 			 */
27445 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27446 			    (int)*(uint_t *)mp->b_rptr));
27447 			freemsg(mp);
27448 			return;
27449 		}
27450 		/* NOTREACHED */
27451 	case IRE_DB_TYPE: {
27452 		nce_t		*nce;
27453 		ill_t		*ill;
27454 		in6_addr_t	gw_addr_v6;
27455 
27456 
27457 		/*
27458 		 * This is a response back from a resolver.  It
27459 		 * consists of a message chain containing:
27460 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27461 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27462 		 * The LL_HDR_MBLK is the DLPI header to use to get
27463 		 * the attached packet, and subsequent ones for the
27464 		 * same destination, transmitted.
27465 		 */
27466 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27467 			break;
27468 		/*
27469 		 * First, check to make sure the resolution succeeded.
27470 		 * If it failed, the second mblk will be empty.
27471 		 * If it is, free the chain, dropping the packet.
27472 		 * (We must ire_delete the ire; that frees the ire mblk)
27473 		 * We're doing this now to support PVCs for ATM; it's
27474 		 * a partial xresolv implementation. When we fully implement
27475 		 * xresolv interfaces, instead of freeing everything here
27476 		 * we'll initiate neighbor discovery.
27477 		 *
27478 		 * For v4 (ARP and other external resolvers) the resolver
27479 		 * frees the message, so no check is needed. This check
27480 		 * is required, though, for a full xresolve implementation.
27481 		 * Including this code here now both shows how external
27482 		 * resolvers can NACK a resolution request using an
27483 		 * existing design that has no specific provisions for NACKs,
27484 		 * and also takes into account that the current non-ARP
27485 		 * external resolver has been coded to use this method of
27486 		 * NACKing for all IPv6 (xresolv) cases,
27487 		 * whether our xresolv implementation is complete or not.
27488 		 *
27489 		 */
27490 		ire = (ire_t *)mp->b_rptr;
27491 		ill = ire_to_ill(ire);
27492 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27493 		if (mp1->b_rptr == mp1->b_wptr) {
27494 			if (ire->ire_ipversion == IPV6_VERSION) {
27495 				/*
27496 				 * XRESOLV interface.
27497 				 */
27498 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27499 				mutex_enter(&ire->ire_lock);
27500 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27501 				mutex_exit(&ire->ire_lock);
27502 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27503 					nce = ndp_lookup_v6(ill,
27504 					    &ire->ire_addr_v6, B_FALSE);
27505 				} else {
27506 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
27507 					    B_FALSE);
27508 				}
27509 				if (nce != NULL) {
27510 					nce_resolv_failed(nce);
27511 					ndp_delete(nce);
27512 					NCE_REFRELE(nce);
27513 				}
27514 			}
27515 			mp->b_cont = NULL;
27516 			freemsg(mp1);		/* frees the pkt as well */
27517 			ASSERT(ire->ire_nce == NULL);
27518 			ire_delete((ire_t *)mp->b_rptr);
27519 			return;
27520 		}
27521 
27522 		/*
27523 		 * Split them into IRE_MBLK and pkt and feed it into
27524 		 * ire_add_then_send. Then in ire_add_then_send
27525 		 * the IRE will be added, and then the packet will be
27526 		 * run back through ip_wput. This time it will make
27527 		 * it to the wire.
27528 		 */
27529 		mp->b_cont = NULL;
27530 		mp = mp1->b_cont;		/* now, mp points to pkt */
27531 		mp1->b_cont = NULL;
27532 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27533 		if (ire->ire_ipversion == IPV6_VERSION) {
27534 			/*
27535 			 * XRESOLV interface. Find the nce and put a copy
27536 			 * of the dl_unitdata_req in nce_res_mp
27537 			 */
27538 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27539 			mutex_enter(&ire->ire_lock);
27540 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27541 			mutex_exit(&ire->ire_lock);
27542 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27543 				nce = ndp_lookup_v6(ill, &ire->ire_addr_v6,
27544 				    B_FALSE);
27545 			} else {
27546 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
27547 			}
27548 			if (nce != NULL) {
27549 				/*
27550 				 * We have to protect nce_res_mp here
27551 				 * from being accessed by other threads
27552 				 * while we change the mblk pointer.
27553 				 * Other functions will also lock the nce when
27554 				 * accessing nce_res_mp.
27555 				 *
27556 				 * The reason we change the mblk pointer
27557 				 * here rather than copying the resolved address
27558 				 * into the template is that, unlike with
27559 				 * ethernet, we have no guarantee that the
27560 				 * resolved address length will be
27561 				 * smaller than or equal to the lla length
27562 				 * with which the template was allocated,
27563 				 * (for ethernet, they're equal)
27564 				 * so we have to use the actual resolved
27565 				 * address mblk - which holds the real
27566 				 * dl_unitdata_req with the resolved address.
27567 				 *
27568 				 * Doing this is the same behavior as was
27569 				 * previously used in the v4 ARP case.
27570 				 */
27571 				mutex_enter(&nce->nce_lock);
27572 				if (nce->nce_res_mp != NULL)
27573 					freemsg(nce->nce_res_mp);
27574 				nce->nce_res_mp = mp1;
27575 				mutex_exit(&nce->nce_lock);
27576 				/*
27577 				 * We do a fastpath probe here because
27578 				 * we have resolved the address without
27579 				 * using Neighbor Discovery.
27580 				 * In the non-XRESOLV v6 case, the fastpath
27581 				 * probe is done right after neighbor
27582 				 * discovery completes.
27583 				 */
27584 				if (nce->nce_res_mp != NULL) {
27585 					int res;
27586 					nce_fastpath_list_add(nce);
27587 					res = ill_fastpath_probe(ill,
27588 					    nce->nce_res_mp);
27589 					if (res != 0 && res != EAGAIN)
27590 						nce_fastpath_list_delete(nce);
27591 				}
27592 
27593 				ire_add_then_send(q, ire, mp);
27594 				/*
27595 				 * Now we have to clean out any packets
27596 				 * that may have been queued on the nce
27597 				 * while it was waiting for address resolution
27598 				 * to complete.
27599 				 */
27600 				mutex_enter(&nce->nce_lock);
27601 				mp1 = nce->nce_qd_mp;
27602 				nce->nce_qd_mp = NULL;
27603 				mutex_exit(&nce->nce_lock);
27604 				while (mp1 != NULL) {
27605 					mblk_t *nxt_mp;
27606 					queue_t *fwdq = NULL;
27607 					ill_t   *inbound_ill;
27608 					uint_t ifindex;
27609 
27610 					nxt_mp = mp1->b_next;
27611 					mp1->b_next = NULL;
27612 					/*
27613 					 * Retrieve ifindex stored in
27614 					 * ip_rput_data_v6()
27615 					 */
27616 					ifindex =
27617 					    (uint_t)(uintptr_t)mp1->b_prev;
27618 					inbound_ill =
27619 					    ill_lookup_on_ifindex(ifindex,
27620 					    B_TRUE, NULL, NULL, NULL,
27621 					    NULL, ipst);
27622 					mp1->b_prev = NULL;
27623 					if (inbound_ill != NULL)
27624 						fwdq = inbound_ill->ill_rq;
27625 
27626 					if (fwdq != NULL) {
27627 						put(fwdq, mp1);
27628 						ill_refrele(inbound_ill);
27629 					} else
27630 						put(WR(ill->ill_rq), mp1);
27631 					mp1 = nxt_mp;
27632 				}
27633 				NCE_REFRELE(nce);
27634 			} else {	/* nce is NULL; clean up */
27635 				ire_delete(ire);
27636 				freemsg(mp);
27637 				freemsg(mp1);
27638 				return;
27639 			}
27640 		} else {
27641 			nce_t *arpce;
27642 			/*
27643 			 * Link layer resolution succeeded. Recompute the
27644 			 * ire_nce.
27645 			 */
27646 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27647 			if ((arpce = ndp_lookup_v4(ill,
27648 			    (ire->ire_gateway_addr != INADDR_ANY ?
27649 			    &ire->ire_gateway_addr : &ire->ire_addr),
27650 			    B_FALSE)) == NULL) {
27651 				freeb(ire->ire_mp);
27652 				freeb(mp1);
27653 				freemsg(mp);
27654 				return;
27655 			}
27656 			mutex_enter(&arpce->nce_lock);
27657 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27658 			if (arpce->nce_state == ND_REACHABLE) {
27659 				/*
27660 				 * Someone resolved this before us;
27661 				 * cleanup the res_mp. Since ire has
27662 				 * not been added yet, the call to ire_add_v4
27663 				 * from ire_add_then_send (when a dup is
27664 				 * detected) will clean up the ire.
27665 				 */
27666 				freeb(mp1);
27667 			} else {
27668 				ASSERT(arpce->nce_res_mp == NULL);
27669 				arpce->nce_res_mp = mp1;
27670 				arpce->nce_state = ND_REACHABLE;
27671 			}
27672 			mutex_exit(&arpce->nce_lock);
27673 			if (ire->ire_marks & IRE_MARK_NOADD) {
27674 				/*
27675 				 * this ire will not be added to the ire
27676 				 * cache table, so we can set the ire_nce
27677 				 * here, as there are no atomicity constraints.
27678 				 */
27679 				ire->ire_nce = arpce;
27680 				/*
27681 				 * We are associating this nce with the ire
27682 				 * so change the nce ref taken in
27683 				 * ndp_lookup_v4() from
27684 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
27685 				 */
27686 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
27687 			} else {
27688 				NCE_REFRELE(arpce);
27689 			}
27690 			ire_add_then_send(q, ire, mp);
27691 		}
27692 		return;	/* All is well, the packet has been sent. */
27693 	}
27694 	case IRE_ARPRESOLVE_TYPE: {
27695 
27696 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
27697 			break;
27698 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27699 		mp->b_cont = NULL;
27700 		/*
27701 		 * First, check to make sure the resolution succeeded.
27702 		 * If it failed, the second mblk will be empty.
27703 		 */
27704 		if (mp1->b_rptr == mp1->b_wptr) {
27705 			/* cleanup  the incomplete ire, free queued packets */
27706 			freemsg(mp); /* fake ire */
27707 			freeb(mp1);  /* dl_unitdata response */
27708 			return;
27709 		}
27710 
27711 		/*
27712 		 * update any incomplete nce_t found. we lookup the ctable
27713 		 * and find the nce from the ire->ire_nce because we need
27714 		 * to pass the ire to ip_xmit_v4 later, and can find both
27715 		 * ire and nce in one lookup from the ctable.
27716 		 */
27717 		fake_ire = (ire_t *)mp->b_rptr;
27718 		/*
27719 		 * By the time we come back here from ARP
27720 		 * the logical outgoing interface  of the incomplete ire
27721 		 * we added in ire_forward could have disappeared,
27722 		 * causing the incomplete ire to also have
27723 		 * dissapeared. So we need to retreive the
27724 		 * proper ipif for the ire  before looking
27725 		 * in ctable;  do the ctablelookup based on ire_ipif_seqid
27726 		 */
27727 		ill = q->q_ptr;
27728 
27729 		/* Get the outgoing ipif */
27730 		mutex_enter(&ill->ill_lock);
27731 		if (ill->ill_state_flags & ILL_CONDEMNED) {
27732 			mutex_exit(&ill->ill_lock);
27733 			freemsg(mp); /* fake ire */
27734 			freeb(mp1);  /* dl_unitdata response */
27735 			return;
27736 		}
27737 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27738 
27739 		if (ipif == NULL) {
27740 			mutex_exit(&ill->ill_lock);
27741 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27742 			freemsg(mp);
27743 			freeb(mp1);
27744 			return;
27745 		}
27746 		ipif_refhold_locked(ipif);
27747 		mutex_exit(&ill->ill_lock);
27748 		ire = ire_ctable_lookup(fake_ire->ire_addr,
27749 		    fake_ire->ire_gateway_addr, IRE_CACHE,
27750 		    ipif, fake_ire->ire_zoneid, NULL,
27751 		    (MATCH_IRE_GW|MATCH_IRE_IPIF|MATCH_IRE_ZONEONLY), ipst);
27752 		ipif_refrele(ipif);
27753 		if (ire == NULL) {
27754 			/*
27755 			 * no ire was found; check if there is an nce
27756 			 * for this lookup; if it has no ire's pointing at it
27757 			 * cleanup.
27758 			 */
27759 			if ((nce = ndp_lookup_v4(ill,
27760 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
27761 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
27762 			    B_FALSE)) != NULL) {
27763 				/*
27764 				 * cleanup:
27765 				 * We check for refcnt 2 (one for the nce
27766 				 * hash list + 1 for the ref taken by
27767 				 * ndp_lookup_v4) to check that there are
27768 				 * no ire's pointing at the nce.
27769 				 */
27770 				if (nce->nce_refcnt == 2)
27771 					ndp_delete(nce);
27772 				NCE_REFRELE(nce);
27773 			}
27774 			freeb(mp1);  /* dl_unitdata response */
27775 			freemsg(mp); /* fake ire */
27776 			return;
27777 		}
27778 		nce = ire->ire_nce;
27779 		DTRACE_PROBE2(ire__arpresolve__type,
27780 		    ire_t *, ire, nce_t *, nce);
27781 		ASSERT(nce->nce_state != ND_INITIAL);
27782 		mutex_enter(&nce->nce_lock);
27783 		nce->nce_last = TICK_TO_MSEC(lbolt64);
27784 		if (nce->nce_state == ND_REACHABLE) {
27785 			/*
27786 			 * Someone resolved this before us;
27787 			 * our response is not needed any more.
27788 			 */
27789 			mutex_exit(&nce->nce_lock);
27790 			freeb(mp1);  /* dl_unitdata response */
27791 		} else {
27792 			ASSERT(nce->nce_res_mp == NULL);
27793 			nce->nce_res_mp = mp1;
27794 			nce->nce_state = ND_REACHABLE;
27795 			mutex_exit(&nce->nce_lock);
27796 			nce_fastpath(nce);
27797 		}
27798 		/*
27799 		 * The cached nce_t has been updated to be reachable;
27800 		 * Clear the IRE_MARK_UNCACHED flag and free the fake_ire.
27801 		 */
27802 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
27803 		freemsg(mp);
27804 		/*
27805 		 * send out queued packets.
27806 		 */
27807 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
27808 
27809 		IRE_REFRELE(ire);
27810 		return;
27811 	}
27812 	default:
27813 		break;
27814 	}
27815 	if (q->q_next) {
27816 		putnext(q, mp);
27817 	} else
27818 		freemsg(mp);
27819 	return;
27820 
27821 protonak:
27822 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
27823 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
27824 		qreply(q, mp);
27825 }
27826 
27827 /*
27828  * Process IP options in an outbound packet.  Modify the destination if there
27829  * is a source route option.
27830  * Returns non-zero if something fails in which case an ICMP error has been
27831  * sent and mp freed.
27832  */
27833 static int
27834 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
27835     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
27836 {
27837 	ipoptp_t	opts;
27838 	uchar_t		*opt;
27839 	uint8_t		optval;
27840 	uint8_t		optlen;
27841 	ipaddr_t	dst;
27842 	intptr_t	code = 0;
27843 	mblk_t		*mp;
27844 	ire_t		*ire = NULL;
27845 
27846 	ip2dbg(("ip_wput_options\n"));
27847 	mp = ipsec_mp;
27848 	if (mctl_present) {
27849 		mp = ipsec_mp->b_cont;
27850 	}
27851 
27852 	dst = ipha->ipha_dst;
27853 	for (optval = ipoptp_first(&opts, ipha);
27854 	    optval != IPOPT_EOL;
27855 	    optval = ipoptp_next(&opts)) {
27856 		opt = opts.ipoptp_cur;
27857 		optlen = opts.ipoptp_len;
27858 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
27859 		    optval, optlen));
27860 		switch (optval) {
27861 			uint32_t off;
27862 		case IPOPT_SSRR:
27863 		case IPOPT_LSRR:
27864 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27865 				ip1dbg((
27866 				    "ip_wput_options: bad option offset\n"));
27867 				code = (char *)&opt[IPOPT_OLEN] -
27868 				    (char *)ipha;
27869 				goto param_prob;
27870 			}
27871 			off = opt[IPOPT_OFFSET];
27872 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
27873 			    ntohl(dst)));
27874 			/*
27875 			 * For strict: verify that dst is directly
27876 			 * reachable.
27877 			 */
27878 			if (optval == IPOPT_SSRR) {
27879 				ire = ire_ftable_lookup(dst, 0, 0,
27880 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
27881 				    MBLK_GETLABEL(mp),
27882 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
27883 				if (ire == NULL) {
27884 					ip1dbg(("ip_wput_options: SSRR not"
27885 					    " directly reachable: 0x%x\n",
27886 					    ntohl(dst)));
27887 					goto bad_src_route;
27888 				}
27889 				ire_refrele(ire);
27890 			}
27891 			break;
27892 		case IPOPT_RR:
27893 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27894 				ip1dbg((
27895 				    "ip_wput_options: bad option offset\n"));
27896 				code = (char *)&opt[IPOPT_OLEN] -
27897 				    (char *)ipha;
27898 				goto param_prob;
27899 			}
27900 			break;
27901 		case IPOPT_TS:
27902 			/*
27903 			 * Verify that length >=5 and that there is either
27904 			 * room for another timestamp or that the overflow
27905 			 * counter is not maxed out.
27906 			 */
27907 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
27908 			if (optlen < IPOPT_MINLEN_IT) {
27909 				goto param_prob;
27910 			}
27911 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27912 				ip1dbg((
27913 				    "ip_wput_options: bad option offset\n"));
27914 				code = (char *)&opt[IPOPT_OFFSET] -
27915 				    (char *)ipha;
27916 				goto param_prob;
27917 			}
27918 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
27919 			case IPOPT_TS_TSONLY:
27920 				off = IPOPT_TS_TIMELEN;
27921 				break;
27922 			case IPOPT_TS_TSANDADDR:
27923 			case IPOPT_TS_PRESPEC:
27924 			case IPOPT_TS_PRESPEC_RFC791:
27925 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
27926 				break;
27927 			default:
27928 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
27929 				    (char *)ipha;
27930 				goto param_prob;
27931 			}
27932 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
27933 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
27934 				/*
27935 				 * No room and the overflow counter is 15
27936 				 * already.
27937 				 */
27938 				goto param_prob;
27939 			}
27940 			break;
27941 		}
27942 	}
27943 
27944 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
27945 		return (0);
27946 
27947 	ip1dbg(("ip_wput_options: error processing IP options."));
27948 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
27949 
27950 param_prob:
27951 	/*
27952 	 * Since ip_wput() isn't close to finished, we fill
27953 	 * in enough of the header for credible error reporting.
27954 	 */
27955 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
27956 		/* Failed */
27957 		freemsg(ipsec_mp);
27958 		return (-1);
27959 	}
27960 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
27961 	return (-1);
27962 
27963 bad_src_route:
27964 	/*
27965 	 * Since ip_wput() isn't close to finished, we fill
27966 	 * in enough of the header for credible error reporting.
27967 	 */
27968 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
27969 		/* Failed */
27970 		freemsg(ipsec_mp);
27971 		return (-1);
27972 	}
27973 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
27974 	return (-1);
27975 }
27976 
27977 /*
27978  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
27979  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
27980  * thru /etc/system.
27981  */
27982 #define	CONN_MAXDRAINCNT	64
27983 
27984 static void
27985 conn_drain_init(ip_stack_t *ipst)
27986 {
27987 	int i;
27988 
27989 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
27990 
27991 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
27992 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
27993 		/*
27994 		 * Default value of the number of drainers is the
27995 		 * number of cpus, subject to maximum of 8 drainers.
27996 		 */
27997 		if (boot_max_ncpus != -1)
27998 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
27999 		else
28000 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
28001 	}
28002 
28003 	ipst->ips_conn_drain_list = kmem_zalloc(ipst->ips_conn_drain_list_cnt *
28004 	    sizeof (idl_t), KM_SLEEP);
28005 
28006 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28007 		mutex_init(&ipst->ips_conn_drain_list[i].idl_lock, NULL,
28008 		    MUTEX_DEFAULT, NULL);
28009 	}
28010 }
28011 
28012 static void
28013 conn_drain_fini(ip_stack_t *ipst)
28014 {
28015 	int i;
28016 
28017 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++)
28018 		mutex_destroy(&ipst->ips_conn_drain_list[i].idl_lock);
28019 	kmem_free(ipst->ips_conn_drain_list,
28020 	    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
28021 	ipst->ips_conn_drain_list = NULL;
28022 }
28023 
28024 /*
28025  * Note: For an overview of how flowcontrol is handled in IP please see the
28026  * IP Flowcontrol notes at the top of this file.
28027  *
28028  * Flow control has blocked us from proceeding. Insert the given conn in one
28029  * of the conn drain lists. These conn wq's will be qenabled later on when
28030  * STREAMS flow control does a backenable. conn_walk_drain will enable
28031  * the first conn in each of these drain lists. Each of these qenabled conns
28032  * in turn enables the next in the list, after it runs, or when it closes,
28033  * thus sustaining the drain process.
28034  *
28035  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
28036  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
28037  * running at any time, on a given conn, since there can be only 1 service proc
28038  * running on a queue at any time.
28039  */
28040 void
28041 conn_drain_insert(conn_t *connp)
28042 {
28043 	idl_t	*idl;
28044 	uint_t	index;
28045 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28046 
28047 	mutex_enter(&connp->conn_lock);
28048 	if (connp->conn_state_flags & CONN_CLOSING) {
28049 		/*
28050 		 * The conn is closing as a result of which CONN_CLOSING
28051 		 * is set. Return.
28052 		 */
28053 		mutex_exit(&connp->conn_lock);
28054 		return;
28055 	} else if (connp->conn_idl == NULL) {
28056 		/*
28057 		 * Assign the next drain list round robin. We dont' use
28058 		 * a lock, and thus it may not be strictly round robin.
28059 		 * Atomicity of load/stores is enough to make sure that
28060 		 * conn_drain_list_index is always within bounds.
28061 		 */
28062 		index = ipst->ips_conn_drain_list_index;
28063 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
28064 		connp->conn_idl = &ipst->ips_conn_drain_list[index];
28065 		index++;
28066 		if (index == ipst->ips_conn_drain_list_cnt)
28067 			index = 0;
28068 		ipst->ips_conn_drain_list_index = index;
28069 	}
28070 	mutex_exit(&connp->conn_lock);
28071 
28072 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28073 	if ((connp->conn_drain_prev != NULL) ||
28074 	    (connp->conn_state_flags & CONN_CLOSING)) {
28075 		/*
28076 		 * The conn is already in the drain list, OR
28077 		 * the conn is closing. We need to check again for
28078 		 * the closing case again since close can happen
28079 		 * after we drop the conn_lock, and before we
28080 		 * acquire the CONN_DRAIN_LIST_LOCK.
28081 		 */
28082 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28083 		return;
28084 	} else {
28085 		idl = connp->conn_idl;
28086 	}
28087 
28088 	/*
28089 	 * The conn is not in the drain list. Insert it at the
28090 	 * tail of the drain list. The drain list is circular
28091 	 * and doubly linked. idl_conn points to the 1st element
28092 	 * in the list.
28093 	 */
28094 	if (idl->idl_conn == NULL) {
28095 		idl->idl_conn = connp;
28096 		connp->conn_drain_next = connp;
28097 		connp->conn_drain_prev = connp;
28098 	} else {
28099 		conn_t *head = idl->idl_conn;
28100 
28101 		connp->conn_drain_next = head;
28102 		connp->conn_drain_prev = head->conn_drain_prev;
28103 		head->conn_drain_prev->conn_drain_next = connp;
28104 		head->conn_drain_prev = connp;
28105 	}
28106 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28107 }
28108 
28109 /*
28110  * This conn is closing, and we are called from ip_close. OR
28111  * This conn has been serviced by ip_wsrv, and we need to do the tail
28112  * processing.
28113  * If this conn is part of the drain list, we may need to sustain the drain
28114  * process by qenabling the next conn in the drain list. We may also need to
28115  * remove this conn from the list, if it is done.
28116  */
28117 static void
28118 conn_drain_tail(conn_t *connp, boolean_t closing)
28119 {
28120 	idl_t *idl;
28121 
28122 	/*
28123 	 * connp->conn_idl is stable at this point, and no lock is needed
28124 	 * to check it. If we are called from ip_close, close has already
28125 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28126 	 * called us only because conn_idl is non-null. If we are called thru
28127 	 * service, conn_idl could be null, but it cannot change because
28128 	 * service is single-threaded per queue, and there cannot be another
28129 	 * instance of service trying to call conn_drain_insert on this conn
28130 	 * now.
28131 	 */
28132 	ASSERT(!closing || (connp->conn_idl != NULL));
28133 
28134 	/*
28135 	 * If connp->conn_idl is null, the conn has not been inserted into any
28136 	 * drain list even once since creation of the conn. Just return.
28137 	 */
28138 	if (connp->conn_idl == NULL)
28139 		return;
28140 
28141 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28142 
28143 	if (connp->conn_drain_prev == NULL) {
28144 		/* This conn is currently not in the drain list.  */
28145 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28146 		return;
28147 	}
28148 	idl = connp->conn_idl;
28149 	if (idl->idl_conn_draining == connp) {
28150 		/*
28151 		 * This conn is the current drainer. If this is the last conn
28152 		 * in the drain list, we need to do more checks, in the 'if'
28153 		 * below. Otherwwise we need to just qenable the next conn,
28154 		 * to sustain the draining, and is handled in the 'else'
28155 		 * below.
28156 		 */
28157 		if (connp->conn_drain_next == idl->idl_conn) {
28158 			/*
28159 			 * This conn is the last in this list. This round
28160 			 * of draining is complete. If idl_repeat is set,
28161 			 * it means another flow enabling has happened from
28162 			 * the driver/streams and we need to another round
28163 			 * of draining.
28164 			 * If there are more than 2 conns in the drain list,
28165 			 * do a left rotate by 1, so that all conns except the
28166 			 * conn at the head move towards the head by 1, and the
28167 			 * the conn at the head goes to the tail. This attempts
28168 			 * a more even share for all queues that are being
28169 			 * drained.
28170 			 */
28171 			if ((connp->conn_drain_next != connp) &&
28172 			    (idl->idl_conn->conn_drain_next != connp)) {
28173 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28174 			}
28175 			if (idl->idl_repeat) {
28176 				qenable(idl->idl_conn->conn_wq);
28177 				idl->idl_conn_draining = idl->idl_conn;
28178 				idl->idl_repeat = 0;
28179 			} else {
28180 				idl->idl_conn_draining = NULL;
28181 			}
28182 		} else {
28183 			/*
28184 			 * If the next queue that we are now qenable'ing,
28185 			 * is closing, it will remove itself from this list
28186 			 * and qenable the subsequent queue in ip_close().
28187 			 * Serialization is acheived thru idl_lock.
28188 			 */
28189 			qenable(connp->conn_drain_next->conn_wq);
28190 			idl->idl_conn_draining = connp->conn_drain_next;
28191 		}
28192 	}
28193 	if (!connp->conn_did_putbq || closing) {
28194 		/*
28195 		 * Remove ourself from the drain list, if we did not do
28196 		 * a putbq, or if the conn is closing.
28197 		 * Note: It is possible that q->q_first is non-null. It means
28198 		 * that these messages landed after we did a enableok() in
28199 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28200 		 * service them.
28201 		 */
28202 		if (connp->conn_drain_next == connp) {
28203 			/* Singleton in the list */
28204 			ASSERT(connp->conn_drain_prev == connp);
28205 			idl->idl_conn = NULL;
28206 			idl->idl_conn_draining = NULL;
28207 		} else {
28208 			connp->conn_drain_prev->conn_drain_next =
28209 			    connp->conn_drain_next;
28210 			connp->conn_drain_next->conn_drain_prev =
28211 			    connp->conn_drain_prev;
28212 			if (idl->idl_conn == connp)
28213 				idl->idl_conn = connp->conn_drain_next;
28214 			ASSERT(idl->idl_conn_draining != connp);
28215 
28216 		}
28217 		connp->conn_drain_next = NULL;
28218 		connp->conn_drain_prev = NULL;
28219 	}
28220 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28221 }
28222 
28223 /*
28224  * Write service routine. Shared perimeter entry point.
28225  * ip_wsrv can be called in any of the following ways.
28226  * 1. The device queue's messages has fallen below the low water mark
28227  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28228  *    the drain lists and backenable the first conn in each list.
28229  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28230  *    qenabled non-tcp upper layers. We start dequeing messages and call
28231  *    ip_wput for each message.
28232  */
28233 
28234 void
28235 ip_wsrv(queue_t *q)
28236 {
28237 	conn_t	*connp;
28238 	ill_t	*ill;
28239 	mblk_t	*mp;
28240 
28241 	if (q->q_next) {
28242 		ill = (ill_t *)q->q_ptr;
28243 		if (ill->ill_state_flags == 0) {
28244 			/*
28245 			 * The device flow control has opened up.
28246 			 * Walk through conn drain lists and qenable the
28247 			 * first conn in each list. This makes sense only
28248 			 * if the stream is fully plumbed and setup.
28249 			 * Hence the if check above.
28250 			 */
28251 			ip1dbg(("ip_wsrv: walking\n"));
28252 			conn_walk_drain(ill->ill_ipst);
28253 		}
28254 		return;
28255 	}
28256 
28257 	connp = Q_TO_CONN(q);
28258 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28259 
28260 	/*
28261 	 * 1. Set conn_draining flag to signal that service is active.
28262 	 *
28263 	 * 2. ip_output determines whether it has been called from service,
28264 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28265 	 *    has been called from service.
28266 	 *
28267 	 * 3. Message ordering is preserved by the following logic.
28268 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28269 	 *    the message at the tail, if conn_draining is set (i.e. service
28270 	 *    is running) or if q->q_first is non-null.
28271 	 *
28272 	 *    ii. If ip_output is called from service, and if ip_output cannot
28273 	 *    putnext due to flow control, it does a putbq.
28274 	 *
28275 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28276 	 *    (causing an infinite loop).
28277 	 */
28278 	ASSERT(!connp->conn_did_putbq);
28279 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28280 		connp->conn_draining = 1;
28281 		noenable(q);
28282 		while ((mp = getq(q)) != NULL) {
28283 			ASSERT(CONN_Q(q));
28284 
28285 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28286 			if (connp->conn_did_putbq) {
28287 				/* ip_wput did a putbq */
28288 				break;
28289 			}
28290 		}
28291 		/*
28292 		 * At this point, a thread coming down from top, calling
28293 		 * ip_wput, may end up queueing the message. We have not yet
28294 		 * enabled the queue, so ip_wsrv won't be called again.
28295 		 * To avoid this race, check q->q_first again (in the loop)
28296 		 * If the other thread queued the message before we call
28297 		 * enableok(), we will catch it in the q->q_first check.
28298 		 * If the other thread queues the message after we call
28299 		 * enableok(), ip_wsrv will be called again by STREAMS.
28300 		 */
28301 		connp->conn_draining = 0;
28302 		enableok(q);
28303 	}
28304 
28305 	/* Enable the next conn for draining */
28306 	conn_drain_tail(connp, B_FALSE);
28307 
28308 	connp->conn_did_putbq = 0;
28309 }
28310 
28311 /*
28312  * Walk the list of all conn's calling the function provided with the
28313  * specified argument for each.	 Note that this only walks conn's that
28314  * have been bound.
28315  * Applies to both IPv4 and IPv6.
28316  */
28317 static void
28318 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid, ip_stack_t *ipst)
28319 {
28320 	conn_walk_fanout_table(ipst->ips_ipcl_udp_fanout,
28321 	    ipst->ips_ipcl_udp_fanout_size,
28322 	    func, arg, zoneid);
28323 	conn_walk_fanout_table(ipst->ips_ipcl_conn_fanout,
28324 	    ipst->ips_ipcl_conn_fanout_size,
28325 	    func, arg, zoneid);
28326 	conn_walk_fanout_table(ipst->ips_ipcl_bind_fanout,
28327 	    ipst->ips_ipcl_bind_fanout_size,
28328 	    func, arg, zoneid);
28329 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout,
28330 	    IPPROTO_MAX, func, arg, zoneid);
28331 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout_v6,
28332 	    IPPROTO_MAX, func, arg, zoneid);
28333 }
28334 
28335 /*
28336  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28337  * of conns that need to be drained, check if drain is already in progress.
28338  * If so set the idl_repeat bit, indicating that the last conn in the list
28339  * needs to reinitiate the drain once again, for the list. If drain is not
28340  * in progress for the list, initiate the draining, by qenabling the 1st
28341  * conn in the list. The drain is self-sustaining, each qenabled conn will
28342  * in turn qenable the next conn, when it is done/blocked/closing.
28343  */
28344 static void
28345 conn_walk_drain(ip_stack_t *ipst)
28346 {
28347 	int i;
28348 	idl_t *idl;
28349 
28350 	IP_STAT(ipst, ip_conn_walk_drain);
28351 
28352 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28353 		idl = &ipst->ips_conn_drain_list[i];
28354 		mutex_enter(&idl->idl_lock);
28355 		if (idl->idl_conn == NULL) {
28356 			mutex_exit(&idl->idl_lock);
28357 			continue;
28358 		}
28359 		/*
28360 		 * If this list is not being drained currently by
28361 		 * an ip_wsrv thread, start the process.
28362 		 */
28363 		if (idl->idl_conn_draining == NULL) {
28364 			ASSERT(idl->idl_repeat == 0);
28365 			qenable(idl->idl_conn->conn_wq);
28366 			idl->idl_conn_draining = idl->idl_conn;
28367 		} else {
28368 			idl->idl_repeat = 1;
28369 		}
28370 		mutex_exit(&idl->idl_lock);
28371 	}
28372 }
28373 
28374 /*
28375  * Walk an conn hash table of `count' buckets, calling func for each entry.
28376  */
28377 static void
28378 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
28379     zoneid_t zoneid)
28380 {
28381 	conn_t	*connp;
28382 
28383 	while (count-- > 0) {
28384 		mutex_enter(&connfp->connf_lock);
28385 		for (connp = connfp->connf_head; connp != NULL;
28386 		    connp = connp->conn_next) {
28387 			if (zoneid == GLOBAL_ZONEID ||
28388 			    zoneid == connp->conn_zoneid) {
28389 				CONN_INC_REF(connp);
28390 				mutex_exit(&connfp->connf_lock);
28391 				(*func)(connp, arg);
28392 				mutex_enter(&connfp->connf_lock);
28393 				CONN_DEC_REF(connp);
28394 			}
28395 		}
28396 		mutex_exit(&connfp->connf_lock);
28397 		connfp++;
28398 	}
28399 }
28400 
28401 /* conn_walk_fanout routine invoked for ip_conn_report for each conn. */
28402 static void
28403 conn_report1(conn_t *connp, void *mp)
28404 {
28405 	char	buf1[INET6_ADDRSTRLEN];
28406 	char	buf2[INET6_ADDRSTRLEN];
28407 	uint_t	print_len, buf_len;
28408 
28409 	ASSERT(connp != NULL);
28410 
28411 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
28412 	if (buf_len <= 0)
28413 		return;
28414 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1));
28415 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2));
28416 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
28417 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
28418 	    "%5d %s/%05d %s/%05d\n",
28419 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
28420 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
28421 	    buf1, connp->conn_lport,
28422 	    buf2, connp->conn_fport);
28423 	if (print_len < buf_len) {
28424 		((mblk_t *)mp)->b_wptr += print_len;
28425 	} else {
28426 		((mblk_t *)mp)->b_wptr += buf_len;
28427 	}
28428 }
28429 
28430 /*
28431  * Named Dispatch routine to produce a formatted report on all conns
28432  * that are listed in one of the fanout tables.
28433  * This report is accessed by using the ndd utility to "get" ND variable
28434  * "ip_conn_status".
28435  */
28436 /* ARGSUSED */
28437 static int
28438 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
28439 {
28440 	conn_t *connp = Q_TO_CONN(q);
28441 
28442 	(void) mi_mpprintf(mp,
28443 	    "CONN      " MI_COL_HDRPAD_STR
28444 	    "rfq      " MI_COL_HDRPAD_STR
28445 	    "stq      " MI_COL_HDRPAD_STR
28446 	    " zone local                 remote");
28447 
28448 	/*
28449 	 * Because of the ndd constraint, at most we can have 64K buffer
28450 	 * to put in all conn info.  So to be more efficient, just
28451 	 * allocate a 64K buffer here, assuming we need that large buffer.
28452 	 * This should be OK as only privileged processes can do ndd /dev/ip.
28453 	 */
28454 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
28455 		/* The following may work even if we cannot get a large buf. */
28456 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
28457 		return (0);
28458 	}
28459 
28460 	conn_walk_fanout(conn_report1, mp->b_cont, connp->conn_zoneid,
28461 	    connp->conn_netstack->netstack_ip);
28462 	return (0);
28463 }
28464 
28465 /*
28466  * Determine if the ill and multicast aspects of that packets
28467  * "matches" the conn.
28468  */
28469 boolean_t
28470 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28471     zoneid_t zoneid)
28472 {
28473 	ill_t *in_ill;
28474 	boolean_t found;
28475 	ipif_t *ipif;
28476 	ire_t *ire;
28477 	ipaddr_t dst, src;
28478 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28479 
28480 	dst = ipha->ipha_dst;
28481 	src = ipha->ipha_src;
28482 
28483 	/*
28484 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28485 	 * unicast, broadcast and multicast reception to
28486 	 * conn_incoming_ill. conn_wantpacket itself is called
28487 	 * only for BROADCAST and multicast.
28488 	 *
28489 	 * 1) ip_rput supresses duplicate broadcasts if the ill
28490 	 *    is part of a group. Hence, we should be receiving
28491 	 *    just one copy of broadcast for the whole group.
28492 	 *    Thus, if it is part of the group the packet could
28493 	 *    come on any ill of the group and hence we need a
28494 	 *    match on the group. Otherwise, match on ill should
28495 	 *    be sufficient.
28496 	 *
28497 	 * 2) ip_rput does not suppress duplicate multicast packets.
28498 	 *    If there are two interfaces in a ill group and we have
28499 	 *    2 applications (conns) joined a multicast group G on
28500 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
28501 	 *    will give us two packets because we join G on both the
28502 	 *    interfaces rather than nominating just one interface
28503 	 *    for receiving multicast like broadcast above. So,
28504 	 *    we have to call ilg_lookup_ill to filter out duplicate
28505 	 *    copies, if ill is part of a group.
28506 	 */
28507 	in_ill = connp->conn_incoming_ill;
28508 	if (in_ill != NULL) {
28509 		if (in_ill->ill_group == NULL) {
28510 			if (in_ill != ill)
28511 				return (B_FALSE);
28512 		} else if (in_ill->ill_group != ill->ill_group) {
28513 			return (B_FALSE);
28514 		}
28515 	}
28516 
28517 	if (!CLASSD(dst)) {
28518 		if (IPCL_ZONE_MATCH(connp, zoneid))
28519 			return (B_TRUE);
28520 		/*
28521 		 * The conn is in a different zone; we need to check that this
28522 		 * broadcast address is configured in the application's zone and
28523 		 * on one ill in the group.
28524 		 */
28525 		ipif = ipif_get_next_ipif(NULL, ill);
28526 		if (ipif == NULL)
28527 			return (B_FALSE);
28528 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28529 		    connp->conn_zoneid, NULL,
28530 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
28531 		ipif_refrele(ipif);
28532 		if (ire != NULL) {
28533 			ire_refrele(ire);
28534 			return (B_TRUE);
28535 		} else {
28536 			return (B_FALSE);
28537 		}
28538 	}
28539 
28540 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28541 	    connp->conn_zoneid == zoneid) {
28542 		/*
28543 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28544 		 * disabled, therefore we don't dispatch the multicast packet to
28545 		 * the sending zone.
28546 		 */
28547 		return (B_FALSE);
28548 	}
28549 
28550 	if (IS_LOOPBACK(ill) && connp->conn_zoneid != zoneid) {
28551 		/*
28552 		 * Multicast packet on the loopback interface: we only match
28553 		 * conns who joined the group in the specified zone.
28554 		 */
28555 		return (B_FALSE);
28556 	}
28557 
28558 	if (connp->conn_multi_router) {
28559 		/* multicast packet and multicast router socket: send up */
28560 		return (B_TRUE);
28561 	}
28562 
28563 	mutex_enter(&connp->conn_lock);
28564 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28565 	mutex_exit(&connp->conn_lock);
28566 	return (found);
28567 }
28568 
28569 /*
28570  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28571  */
28572 /* ARGSUSED */
28573 static void
28574 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28575 {
28576 	ill_t *ill = (ill_t *)q->q_ptr;
28577 	mblk_t	*mp1, *mp2;
28578 	ipif_t  *ipif;
28579 	int err = 0;
28580 	conn_t *connp = NULL;
28581 	ipsq_t	*ipsq;
28582 	arc_t	*arc;
28583 
28584 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28585 
28586 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28587 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28588 
28589 	ASSERT(IAM_WRITER_ILL(ill));
28590 	mp2 = mp->b_cont;
28591 	mp->b_cont = NULL;
28592 
28593 	/*
28594 	 * We have now received the arp bringup completion message
28595 	 * from ARP. Mark the arp bringup as done. Also if the arp
28596 	 * stream has already started closing, send up the AR_ARP_CLOSING
28597 	 * ack now since ARP is waiting in close for this ack.
28598 	 */
28599 	mutex_enter(&ill->ill_lock);
28600 	ill->ill_arp_bringup_pending = 0;
28601 	if (ill->ill_arp_closing) {
28602 		mutex_exit(&ill->ill_lock);
28603 		/* Let's reuse the mp for sending the ack */
28604 		arc = (arc_t *)mp->b_rptr;
28605 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28606 		arc->arc_cmd = AR_ARP_CLOSING;
28607 		qreply(q, mp);
28608 	} else {
28609 		mutex_exit(&ill->ill_lock);
28610 		freeb(mp);
28611 	}
28612 
28613 	ipsq = ill->ill_phyint->phyint_ipsq;
28614 	ipif = ipsq->ipsq_pending_ipif;
28615 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28616 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
28617 	if (mp1 == NULL) {
28618 		/* bringup was aborted by the user */
28619 		freemsg(mp2);
28620 		return;
28621 	}
28622 
28623 	/*
28624 	 * If an IOCTL is waiting on this (ipsq_current_ioctl != 0), then we
28625 	 * must have an associated conn_t.  Otherwise, we're bringing this
28626 	 * interface back up as part of handling an asynchronous event (e.g.,
28627 	 * physical address change).
28628 	 */
28629 	if (ipsq->ipsq_current_ioctl != 0) {
28630 		ASSERT(connp != NULL);
28631 		q = CONNP_TO_WQ(connp);
28632 	} else {
28633 		ASSERT(connp == NULL);
28634 		q = ill->ill_rq;
28635 	}
28636 
28637 	/*
28638 	 * If the DL_BIND_REQ fails, it is noted
28639 	 * in arc_name_offset.
28640 	 */
28641 	err = *((int *)mp2->b_rptr);
28642 	if (err == 0) {
28643 		if (ipif->ipif_isv6) {
28644 			if ((err = ipif_up_done_v6(ipif)) != 0)
28645 				ip0dbg(("ip_arp_done: init failed\n"));
28646 		} else {
28647 			if ((err = ipif_up_done(ipif)) != 0)
28648 				ip0dbg(("ip_arp_done: init failed\n"));
28649 		}
28650 	} else {
28651 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28652 	}
28653 
28654 	freemsg(mp2);
28655 
28656 	if ((err == 0) && (ill->ill_up_ipifs)) {
28657 		err = ill_up_ipifs(ill, q, mp1);
28658 		if (err == EINPROGRESS)
28659 			return;
28660 	}
28661 
28662 	if (ill->ill_up_ipifs)
28663 		ill_group_cleanup(ill);
28664 
28665 	/*
28666 	 * The operation must complete without EINPROGRESS since
28667 	 * ipsq_pending_mp_get() has removed the mblk from ipsq_pending_mp.
28668 	 * Otherwise, the operation will be stuck forever in the ipsq.
28669 	 */
28670 	ASSERT(err != EINPROGRESS);
28671 	if (ipsq->ipsq_current_ioctl != 0)
28672 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
28673 	else
28674 		ipsq_current_finish(ipsq);
28675 }
28676 
28677 /* Allocate the private structure */
28678 static int
28679 ip_priv_alloc(void **bufp)
28680 {
28681 	void	*buf;
28682 
28683 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
28684 		return (ENOMEM);
28685 
28686 	*bufp = buf;
28687 	return (0);
28688 }
28689 
28690 /* Function to delete the private structure */
28691 void
28692 ip_priv_free(void *buf)
28693 {
28694 	ASSERT(buf != NULL);
28695 	kmem_free(buf, sizeof (ip_priv_t));
28696 }
28697 
28698 /*
28699  * The entry point for IPPF processing.
28700  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
28701  * routine just returns.
28702  *
28703  * When called, ip_process generates an ipp_packet_t structure
28704  * which holds the state information for this packet and invokes the
28705  * the classifier (via ipp_packet_process). The classification, depending on
28706  * configured filters, results in a list of actions for this packet. Invoking
28707  * an action may cause the packet to be dropped, in which case the resulting
28708  * mblk (*mpp) is NULL. proc indicates the callout position for
28709  * this packet and ill_index is the interface this packet on or will leave
28710  * on (inbound and outbound resp.).
28711  */
28712 void
28713 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
28714 {
28715 	mblk_t		*mp;
28716 	ip_priv_t	*priv;
28717 	ipp_action_id_t	aid;
28718 	int		rc = 0;
28719 	ipp_packet_t	*pp;
28720 #define	IP_CLASS	"ip"
28721 
28722 	/* If the classifier is not loaded, return  */
28723 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
28724 		return;
28725 	}
28726 
28727 	mp = *mpp;
28728 	ASSERT(mp != NULL);
28729 
28730 	/* Allocate the packet structure */
28731 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
28732 	if (rc != 0) {
28733 		*mpp = NULL;
28734 		freemsg(mp);
28735 		return;
28736 	}
28737 
28738 	/* Allocate the private structure */
28739 	rc = ip_priv_alloc((void **)&priv);
28740 	if (rc != 0) {
28741 		*mpp = NULL;
28742 		freemsg(mp);
28743 		ipp_packet_free(pp);
28744 		return;
28745 	}
28746 	priv->proc = proc;
28747 	priv->ill_index = ill_index;
28748 	ipp_packet_set_private(pp, priv, ip_priv_free);
28749 	ipp_packet_set_data(pp, mp);
28750 
28751 	/* Invoke the classifier */
28752 	rc = ipp_packet_process(&pp);
28753 	if (pp != NULL) {
28754 		mp = ipp_packet_get_data(pp);
28755 		ipp_packet_free(pp);
28756 		if (rc != 0) {
28757 			freemsg(mp);
28758 			*mpp = NULL;
28759 		}
28760 	} else {
28761 		*mpp = NULL;
28762 	}
28763 #undef	IP_CLASS
28764 }
28765 
28766 /*
28767  * Propagate a multicast group membership operation (add/drop) on
28768  * all the interfaces crossed by the related multirt routes.
28769  * The call is considered successful if the operation succeeds
28770  * on at least one interface.
28771  */
28772 static int
28773 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
28774     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
28775     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
28776     mblk_t *first_mp)
28777 {
28778 	ire_t		*ire_gw;
28779 	irb_t		*irb;
28780 	int		error = 0;
28781 	opt_restart_t	*or;
28782 	ip_stack_t	*ipst = ire->ire_ipst;
28783 
28784 	irb = ire->ire_bucket;
28785 	ASSERT(irb != NULL);
28786 
28787 	ASSERT(DB_TYPE(first_mp) == M_CTL);
28788 
28789 	or = (opt_restart_t *)first_mp->b_rptr;
28790 	IRB_REFHOLD(irb);
28791 	for (; ire != NULL; ire = ire->ire_next) {
28792 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
28793 			continue;
28794 		if (ire->ire_addr != group)
28795 			continue;
28796 
28797 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
28798 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
28799 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
28800 		/* No resolver exists for the gateway; skip this ire. */
28801 		if (ire_gw == NULL)
28802 			continue;
28803 
28804 		/*
28805 		 * This function can return EINPROGRESS. If so the operation
28806 		 * will be restarted from ip_restart_optmgmt which will
28807 		 * call ip_opt_set and option processing will restart for
28808 		 * this option. So we may end up calling 'fn' more than once.
28809 		 * This requires that 'fn' is idempotent except for the
28810 		 * return value. The operation is considered a success if
28811 		 * it succeeds at least once on any one interface.
28812 		 */
28813 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
28814 		    NULL, fmode, src, first_mp);
28815 		if (error == 0)
28816 			or->or_private = CGTP_MCAST_SUCCESS;
28817 
28818 		if (ip_debug > 0) {
28819 			ulong_t	off;
28820 			char	*ksym;
28821 			ksym = kobj_getsymname((uintptr_t)fn, &off);
28822 			ip2dbg(("ip_multirt_apply_membership: "
28823 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
28824 			    "error %d [success %u]\n",
28825 			    ksym ? ksym : "?",
28826 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
28827 			    error, or->or_private));
28828 		}
28829 
28830 		ire_refrele(ire_gw);
28831 		if (error == EINPROGRESS) {
28832 			IRB_REFRELE(irb);
28833 			return (error);
28834 		}
28835 	}
28836 	IRB_REFRELE(irb);
28837 	/*
28838 	 * Consider the call as successful if we succeeded on at least
28839 	 * one interface. Otherwise, return the last encountered error.
28840 	 */
28841 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
28842 }
28843 
28844 
28845 /*
28846  * Issue a warning regarding a route crossing an interface with an
28847  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
28848  * amount of time is logged.
28849  */
28850 static void
28851 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
28852 {
28853 	hrtime_t	current = gethrtime();
28854 	char		buf[INET_ADDRSTRLEN];
28855 	ip_stack_t	*ipst = ire->ire_ipst;
28856 
28857 	/* Convert interval in ms to hrtime in ns */
28858 	if (ipst->ips_multirt_bad_mtu_last_time +
28859 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
28860 	    current) {
28861 		cmn_err(CE_WARN, "ip: ignoring multiroute "
28862 		    "to %s, incorrect MTU %u (expected %u)\n",
28863 		    ip_dot_addr(ire->ire_addr, buf),
28864 		    ire->ire_max_frag, max_frag);
28865 
28866 		ipst->ips_multirt_bad_mtu_last_time = current;
28867 	}
28868 }
28869 
28870 
28871 /*
28872  * Get the CGTP (multirouting) filtering status.
28873  * If 0, the CGTP hooks are transparent.
28874  */
28875 /* ARGSUSED */
28876 static int
28877 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
28878 {
28879 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28880 
28881 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
28882 	return (0);
28883 }
28884 
28885 
28886 /*
28887  * Set the CGTP (multirouting) filtering status.
28888  * If the status is changed from active to transparent
28889  * or from transparent to active, forward the new status
28890  * to the filtering module (if loaded).
28891  */
28892 /* ARGSUSED */
28893 static int
28894 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
28895     cred_t *ioc_cr)
28896 {
28897 	long		new_value;
28898 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28899 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
28900 
28901 	if (secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
28902 		return (EPERM);
28903 
28904 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
28905 	    new_value < 0 || new_value > 1) {
28906 		return (EINVAL);
28907 	}
28908 
28909 	if ((!*ip_cgtp_filter_value) && new_value) {
28910 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
28911 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28912 		    " (module not loaded)" : "");
28913 	}
28914 	if (*ip_cgtp_filter_value && (!new_value)) {
28915 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
28916 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28917 		    " (module not loaded)" : "");
28918 	}
28919 
28920 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
28921 		int	res;
28922 		netstackid_t stackid;
28923 
28924 		stackid = ipst->ips_netstack->netstack_stackid;
28925 		res = ipst->ips_ip_cgtp_filter_ops->cfo_change_state(stackid,
28926 		    new_value);
28927 		if (res)
28928 			return (res);
28929 	}
28930 
28931 	*ip_cgtp_filter_value = (boolean_t)new_value;
28932 
28933 	return (0);
28934 }
28935 
28936 
28937 /*
28938  * Return the expected CGTP hooks version number.
28939  */
28940 int
28941 ip_cgtp_filter_supported(void)
28942 {
28943 	return (ip_cgtp_filter_rev);
28944 }
28945 
28946 
28947 /*
28948  * CGTP hooks can be registered by invoking this function.
28949  * Checks that the version number matches.
28950  */
28951 int
28952 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
28953 {
28954 	netstack_t *ns;
28955 	ip_stack_t *ipst;
28956 
28957 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
28958 		return (ENOTSUP);
28959 
28960 	ns = netstack_find_by_stackid(stackid);
28961 	if (ns == NULL)
28962 		return (EINVAL);
28963 	ipst = ns->netstack_ip;
28964 	ASSERT(ipst != NULL);
28965 
28966 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
28967 		netstack_rele(ns);
28968 		return (EALREADY);
28969 	}
28970 
28971 	ipst->ips_ip_cgtp_filter_ops = ops;
28972 	netstack_rele(ns);
28973 	return (0);
28974 }
28975 
28976 /*
28977  * CGTP hooks can be unregistered by invoking this function.
28978  * Returns ENXIO if there was no registration.
28979  * Returns EBUSY if the ndd variable has not been turned off.
28980  */
28981 int
28982 ip_cgtp_filter_unregister(netstackid_t stackid)
28983 {
28984 	netstack_t *ns;
28985 	ip_stack_t *ipst;
28986 
28987 	ns = netstack_find_by_stackid(stackid);
28988 	if (ns == NULL)
28989 		return (EINVAL);
28990 	ipst = ns->netstack_ip;
28991 	ASSERT(ipst != NULL);
28992 
28993 	if (ipst->ips_ip_cgtp_filter) {
28994 		netstack_rele(ns);
28995 		return (EBUSY);
28996 	}
28997 
28998 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
28999 		netstack_rele(ns);
29000 		return (ENXIO);
29001 	}
29002 	ipst->ips_ip_cgtp_filter_ops = NULL;
29003 	netstack_rele(ns);
29004 	return (0);
29005 }
29006 
29007 /*
29008  * Check whether there is a CGTP filter registration.
29009  * Returns non-zero if there is a registration, otherwise returns zero.
29010  * Note: returns zero if bad stackid.
29011  */
29012 int
29013 ip_cgtp_filter_is_registered(netstackid_t stackid)
29014 {
29015 	netstack_t *ns;
29016 	ip_stack_t *ipst;
29017 	int ret;
29018 
29019 	ns = netstack_find_by_stackid(stackid);
29020 	if (ns == NULL)
29021 		return (0);
29022 	ipst = ns->netstack_ip;
29023 	ASSERT(ipst != NULL);
29024 
29025 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
29026 		ret = 1;
29027 	else
29028 		ret = 0;
29029 
29030 	netstack_rele(ns);
29031 	return (ret);
29032 }
29033 
29034 static squeue_func_t
29035 ip_squeue_switch(int val)
29036 {
29037 	squeue_func_t rval = squeue_fill;
29038 
29039 	switch (val) {
29040 	case IP_SQUEUE_ENTER_NODRAIN:
29041 		rval = squeue_enter_nodrain;
29042 		break;
29043 	case IP_SQUEUE_ENTER:
29044 		rval = squeue_enter;
29045 		break;
29046 	default:
29047 		break;
29048 	}
29049 	return (rval);
29050 }
29051 
29052 /* ARGSUSED */
29053 static int
29054 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
29055     caddr_t addr, cred_t *cr)
29056 {
29057 	int *v = (int *)addr;
29058 	long new_value;
29059 
29060 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29061 		return (EPERM);
29062 
29063 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29064 		return (EINVAL);
29065 
29066 	ip_input_proc = ip_squeue_switch(new_value);
29067 	*v = new_value;
29068 	return (0);
29069 }
29070 
29071 /*
29072  * Handle ndd set of variables which require PRIV_SYS_NET_CONFIG such as
29073  * ip_debug.
29074  */
29075 /* ARGSUSED */
29076 static int
29077 ip_int_set(queue_t *q, mblk_t *mp, char *value,
29078     caddr_t addr, cred_t *cr)
29079 {
29080 	int *v = (int *)addr;
29081 	long new_value;
29082 
29083 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29084 		return (EPERM);
29085 
29086 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29087 		return (EINVAL);
29088 
29089 	*v = new_value;
29090 	return (0);
29091 }
29092 
29093 /*
29094  * Handle changes to ipmp_hook_emulation ndd variable.
29095  * Need to update phyint_hook_ifindex.
29096  * Also generate a nic plumb event should a new ifidex be assigned to a group.
29097  */
29098 static void
29099 ipmp_hook_emulation_changed(ip_stack_t *ipst)
29100 {
29101 	phyint_t *phyi;
29102 	phyint_t *phyi_tmp;
29103 	char *groupname;
29104 	int namelen;
29105 	ill_t	*ill;
29106 	boolean_t new_group;
29107 
29108 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29109 	/*
29110 	 * Group indicies are stored in the phyint - a common structure
29111 	 * to both IPv4 and IPv6.
29112 	 */
29113 	phyi = avl_first(&ipst->ips_phyint_g_list->phyint_list_avl_by_index);
29114 	for (; phyi != NULL;
29115 	    phyi = avl_walk(&ipst->ips_phyint_g_list->phyint_list_avl_by_index,
29116 	    phyi, AVL_AFTER)) {
29117 		/* Ignore the ones that do not have a group */
29118 		if (phyi->phyint_groupname_len == 0)
29119 			continue;
29120 
29121 		/*
29122 		 * Look for other phyint in group.
29123 		 * Clear name/namelen so the lookup doesn't find ourselves.
29124 		 */
29125 		namelen = phyi->phyint_groupname_len;
29126 		groupname = phyi->phyint_groupname;
29127 		phyi->phyint_groupname_len = 0;
29128 		phyi->phyint_groupname = NULL;
29129 
29130 		phyi_tmp = phyint_lookup_group(groupname, B_FALSE, ipst);
29131 		/* Restore */
29132 		phyi->phyint_groupname_len = namelen;
29133 		phyi->phyint_groupname = groupname;
29134 
29135 		new_group = B_FALSE;
29136 		if (ipst->ips_ipmp_hook_emulation) {
29137 			/*
29138 			 * If the group already exists and has already
29139 			 * been assigned a group ifindex, we use the existing
29140 			 * group_ifindex, otherwise we pick a new group_ifindex
29141 			 * here.
29142 			 */
29143 			if (phyi_tmp != NULL &&
29144 			    phyi_tmp->phyint_group_ifindex != 0) {
29145 				phyi->phyint_group_ifindex =
29146 				    phyi_tmp->phyint_group_ifindex;
29147 			} else {
29148 				/* XXX We need a recovery strategy here. */
29149 				if (!ip_assign_ifindex(
29150 				    &phyi->phyint_group_ifindex, ipst))
29151 					cmn_err(CE_PANIC,
29152 					    "ip_assign_ifindex() failed");
29153 				new_group = B_TRUE;
29154 			}
29155 		} else {
29156 			phyi->phyint_group_ifindex = 0;
29157 		}
29158 		if (ipst->ips_ipmp_hook_emulation)
29159 			phyi->phyint_hook_ifindex = phyi->phyint_group_ifindex;
29160 		else
29161 			phyi->phyint_hook_ifindex = phyi->phyint_ifindex;
29162 
29163 		/*
29164 		 * For IP Filter to find out the relationship between
29165 		 * names and interface indicies, we need to generate
29166 		 * a NE_PLUMB event when a new group can appear.
29167 		 * We always generate events when a new interface appears
29168 		 * (even when ipmp_hook_emulation is set) so there
29169 		 * is no need to generate NE_PLUMB events when
29170 		 * ipmp_hook_emulation is turned off.
29171 		 * And since it isn't critical for IP Filter to get
29172 		 * the NE_UNPLUMB events we skip those here.
29173 		 */
29174 		if (new_group) {
29175 			/*
29176 			 * First phyint in group - generate group PLUMB event.
29177 			 * Since we are not running inside the ipsq we do
29178 			 * the dispatch immediately.
29179 			 */
29180 			if (phyi->phyint_illv4 != NULL)
29181 				ill = phyi->phyint_illv4;
29182 			else
29183 				ill = phyi->phyint_illv6;
29184 
29185 			if (ill != NULL) {
29186 				mutex_enter(&ill->ill_lock);
29187 				ill_nic_info_plumb(ill, B_TRUE);
29188 				ill_nic_info_dispatch(ill);
29189 				mutex_exit(&ill->ill_lock);
29190 			}
29191 		}
29192 	}
29193 	rw_exit(&ipst->ips_ill_g_lock);
29194 }
29195 
29196 /* ARGSUSED */
29197 static int
29198 ipmp_hook_emulation_set(queue_t *q, mblk_t *mp, char *value,
29199     caddr_t addr, cred_t *cr)
29200 {
29201 	int *v = (int *)addr;
29202 	long new_value;
29203 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29204 
29205 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29206 		return (EINVAL);
29207 
29208 	if (*v != new_value) {
29209 		*v = new_value;
29210 		ipmp_hook_emulation_changed(ipst);
29211 	}
29212 	return (0);
29213 }
29214 
29215 static void *
29216 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
29217 {
29218 	kstat_t *ksp;
29219 
29220 	ip_stat_t template = {
29221 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
29222 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
29223 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
29224 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
29225 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
29226 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
29227 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
29228 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
29229 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
29230 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
29231 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
29232 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
29233 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
29234 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
29235 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
29236 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
29237 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
29238 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
29239 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
29240 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
29241 		{ "ip_opt",			KSTAT_DATA_UINT64 },
29242 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
29243 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
29244 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29245 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29246 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29247 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29248 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29249 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29250 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29251 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29252 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29253 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29254 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29255 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29256 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29257 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29258 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29259 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29260 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29261 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29262 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29263 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29264 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29265 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29266 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29267 	};
29268 
29269 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29270 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29271 	    KSTAT_FLAG_VIRTUAL, stackid);
29272 
29273 	if (ksp == NULL)
29274 		return (NULL);
29275 
29276 	bcopy(&template, ip_statisticsp, sizeof (template));
29277 	ksp->ks_data = (void *)ip_statisticsp;
29278 	ksp->ks_private = (void *)(uintptr_t)stackid;
29279 
29280 	kstat_install(ksp);
29281 	return (ksp);
29282 }
29283 
29284 static void
29285 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29286 {
29287 	if (ksp != NULL) {
29288 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29289 		kstat_delete_netstack(ksp, stackid);
29290 	}
29291 }
29292 
29293 static void *
29294 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29295 {
29296 	kstat_t	*ksp;
29297 
29298 	ip_named_kstat_t template = {
29299 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29300 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29301 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29302 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29303 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29304 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29305 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29306 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29307 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29308 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29309 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29310 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29311 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29312 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29313 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29314 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29315 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29316 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29317 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29318 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29319 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29320 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29321 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29322 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29323 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29324 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29325 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29326 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29327 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29328 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29329 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29330 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29331 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29332 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29333 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29334 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29335 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29336 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29337 	};
29338 
29339 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29340 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
29341 	if (ksp == NULL || ksp->ks_data == NULL)
29342 		return (NULL);
29343 
29344 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29345 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29346 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29347 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29348 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29349 
29350 	template.netToMediaEntrySize.value.i32 =
29351 	    sizeof (mib2_ipNetToMediaEntry_t);
29352 
29353 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29354 
29355 	bcopy(&template, ksp->ks_data, sizeof (template));
29356 	ksp->ks_update = ip_kstat_update;
29357 	ksp->ks_private = (void *)(uintptr_t)stackid;
29358 
29359 	kstat_install(ksp);
29360 	return (ksp);
29361 }
29362 
29363 static void
29364 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29365 {
29366 	if (ksp != NULL) {
29367 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29368 		kstat_delete_netstack(ksp, stackid);
29369 	}
29370 }
29371 
29372 static int
29373 ip_kstat_update(kstat_t *kp, int rw)
29374 {
29375 	ip_named_kstat_t *ipkp;
29376 	mib2_ipIfStatsEntry_t ipmib;
29377 	ill_walk_context_t ctx;
29378 	ill_t *ill;
29379 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29380 	netstack_t	*ns;
29381 	ip_stack_t	*ipst;
29382 
29383 	if (kp == NULL || kp->ks_data == NULL)
29384 		return (EIO);
29385 
29386 	if (rw == KSTAT_WRITE)
29387 		return (EACCES);
29388 
29389 	ns = netstack_find_by_stackid(stackid);
29390 	if (ns == NULL)
29391 		return (-1);
29392 	ipst = ns->netstack_ip;
29393 	if (ipst == NULL) {
29394 		netstack_rele(ns);
29395 		return (-1);
29396 	}
29397 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29398 
29399 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29400 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29401 	ill = ILL_START_WALK_V4(&ctx, ipst);
29402 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29403 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29404 	rw_exit(&ipst->ips_ill_g_lock);
29405 
29406 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29407 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29408 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29409 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29410 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29411 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29412 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29413 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29414 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29415 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29416 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29417 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29418 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29419 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29420 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29421 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29422 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29423 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29424 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29425 
29426 	ipkp->routingDiscards.value.ui32 =	0;
29427 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29428 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29429 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29430 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29431 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29432 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29433 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29434 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29435 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29436 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29437 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29438 
29439 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29440 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29441 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29442 
29443 	netstack_rele(ns);
29444 
29445 	return (0);
29446 }
29447 
29448 static void *
29449 icmp_kstat_init(netstackid_t stackid)
29450 {
29451 	kstat_t	*ksp;
29452 
29453 	icmp_named_kstat_t template = {
29454 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29455 		{ "inErrors",		KSTAT_DATA_UINT32 },
29456 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29457 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29458 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29459 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29460 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29461 		{ "inEchos",		KSTAT_DATA_UINT32 },
29462 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29463 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29464 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29465 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29466 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29467 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29468 		{ "outErrors",		KSTAT_DATA_UINT32 },
29469 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29470 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29471 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29472 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29473 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29474 		{ "outEchos",		KSTAT_DATA_UINT32 },
29475 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29476 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29477 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29478 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29479 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29480 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29481 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29482 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29483 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29484 		{ "outDrops",		KSTAT_DATA_UINT32 },
29485 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29486 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29487 	};
29488 
29489 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29490 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
29491 	if (ksp == NULL || ksp->ks_data == NULL)
29492 		return (NULL);
29493 
29494 	bcopy(&template, ksp->ks_data, sizeof (template));
29495 
29496 	ksp->ks_update = icmp_kstat_update;
29497 	ksp->ks_private = (void *)(uintptr_t)stackid;
29498 
29499 	kstat_install(ksp);
29500 	return (ksp);
29501 }
29502 
29503 static void
29504 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29505 {
29506 	if (ksp != NULL) {
29507 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29508 		kstat_delete_netstack(ksp, stackid);
29509 	}
29510 }
29511 
29512 static int
29513 icmp_kstat_update(kstat_t *kp, int rw)
29514 {
29515 	icmp_named_kstat_t *icmpkp;
29516 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29517 	netstack_t	*ns;
29518 	ip_stack_t	*ipst;
29519 
29520 	if ((kp == NULL) || (kp->ks_data == NULL))
29521 		return (EIO);
29522 
29523 	if (rw == KSTAT_WRITE)
29524 		return (EACCES);
29525 
29526 	ns = netstack_find_by_stackid(stackid);
29527 	if (ns == NULL)
29528 		return (-1);
29529 	ipst = ns->netstack_ip;
29530 	if (ipst == NULL) {
29531 		netstack_rele(ns);
29532 		return (-1);
29533 	}
29534 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29535 
29536 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29537 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29538 	icmpkp->inDestUnreachs.value.ui32 =
29539 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29540 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29541 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29542 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29543 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29544 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29545 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29546 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29547 	icmpkp->inTimestampReps.value.ui32 =
29548 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29549 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29550 	icmpkp->inAddrMaskReps.value.ui32 =
29551 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29552 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29553 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29554 	icmpkp->outDestUnreachs.value.ui32 =
29555 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29556 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29557 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29558 	icmpkp->outSrcQuenchs.value.ui32 =
29559 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29560 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29561 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29562 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29563 	icmpkp->outTimestamps.value.ui32 =
29564 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29565 	icmpkp->outTimestampReps.value.ui32 =
29566 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29567 	icmpkp->outAddrMasks.value.ui32 =
29568 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29569 	icmpkp->outAddrMaskReps.value.ui32 =
29570 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29571 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29572 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29573 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29574 	icmpkp->outFragNeeded.value.ui32 =
29575 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29576 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29577 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29578 	icmpkp->inBadRedirects.value.ui32 =
29579 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29580 
29581 	netstack_rele(ns);
29582 	return (0);
29583 }
29584 
29585 /*
29586  * This is the fanout function for raw socket opened for SCTP.  Note
29587  * that it is called after SCTP checks that there is no socket which
29588  * wants a packet.  Then before SCTP handles this out of the blue packet,
29589  * this function is called to see if there is any raw socket for SCTP.
29590  * If there is and it is bound to the correct address, the packet will
29591  * be sent to that socket.  Note that only one raw socket can be bound to
29592  * a port.  This is assured in ipcl_sctp_hash_insert();
29593  */
29594 void
29595 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29596     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29597     zoneid_t zoneid)
29598 {
29599 	conn_t		*connp;
29600 	queue_t		*rq;
29601 	mblk_t		*first_mp;
29602 	boolean_t	secure;
29603 	ip6_t		*ip6h;
29604 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29605 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29606 
29607 	first_mp = mp;
29608 	if (mctl_present) {
29609 		mp = first_mp->b_cont;
29610 		secure = ipsec_in_is_secure(first_mp);
29611 		ASSERT(mp != NULL);
29612 	} else {
29613 		secure = B_FALSE;
29614 	}
29615 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29616 
29617 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29618 	if (connp == NULL) {
29619 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29620 		return;
29621 	}
29622 	rq = connp->conn_rq;
29623 	if (!canputnext(rq)) {
29624 		CONN_DEC_REF(connp);
29625 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29626 		freemsg(first_mp);
29627 		return;
29628 	}
29629 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29630 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29631 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29632 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29633 		if (first_mp == NULL) {
29634 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29635 			CONN_DEC_REF(connp);
29636 			return;
29637 		}
29638 	}
29639 	/*
29640 	 * We probably should not send M_CTL message up to
29641 	 * raw socket.
29642 	 */
29643 	if (mctl_present)
29644 		freeb(first_mp);
29645 
29646 	/* Initiate IPPF processing here if needed. */
29647 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
29648 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
29649 		ip_process(IPP_LOCAL_IN, &mp,
29650 		    recv_ill->ill_phyint->phyint_ifindex);
29651 		if (mp == NULL) {
29652 			CONN_DEC_REF(connp);
29653 			return;
29654 		}
29655 	}
29656 
29657 	if (connp->conn_recvif || connp->conn_recvslla ||
29658 	    ((connp->conn_ip_recvpktinfo ||
29659 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29660 	    (flags & IP_FF_IPINFO))) {
29661 		int in_flags = 0;
29662 
29663 		/*
29664 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29665 		 * IPF_RECVIF.
29666 		 */
29667 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29668 			in_flags = IPF_RECVIF;
29669 		}
29670 		if (connp->conn_recvslla) {
29671 			in_flags |= IPF_RECVSLLA;
29672 		}
29673 		if (isv4) {
29674 			mp = ip_add_info(mp, recv_ill, in_flags,
29675 			    IPCL_ZONEID(connp), ipst);
29676 		} else {
29677 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
29678 			if (mp == NULL) {
29679 				BUMP_MIB(recv_ill->ill_ip_mib,
29680 				    ipIfStatsInDiscards);
29681 				CONN_DEC_REF(connp);
29682 				return;
29683 			}
29684 		}
29685 	}
29686 
29687 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
29688 	/*
29689 	 * We are sending the IPSEC_IN message also up. Refer
29690 	 * to comments above this function.
29691 	 * This is the SOCK_RAW, IPPROTO_SCTP case.
29692 	 */
29693 	(connp->conn_recv)(connp, mp, NULL);
29694 	CONN_DEC_REF(connp);
29695 }
29696 
29697 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
29698 {									\
29699 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
29700 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
29701 }
29702 /*
29703  * This function should be called only if all packet processing
29704  * including fragmentation is complete. Callers of this function
29705  * must set mp->b_prev to one of these values:
29706  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
29707  * prior to handing over the mp as first argument to this function.
29708  *
29709  * If the ire passed by caller is incomplete, this function
29710  * queues the packet and if necessary, sends ARP request and bails.
29711  * If the ire passed is fully resolved, we simply prepend
29712  * the link-layer header to the packet, do ipsec hw acceleration
29713  * work if necessary, and send the packet out on the wire.
29714  *
29715  * NOTE: IPsec will only call this function with fully resolved
29716  * ires if hw acceleration is involved.
29717  * TODO list :
29718  * 	a Handle M_MULTIDATA so that
29719  *	  tcp_multisend->tcp_multisend_data can
29720  *	  call ip_xmit_v4 directly
29721  *	b Handle post-ARP work for fragments so that
29722  *	  ip_wput_frag can call this function.
29723  */
29724 ipxmit_state_t
29725 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io, boolean_t flow_ctl_enabled)
29726 {
29727 	nce_t		*arpce;
29728 	queue_t		*q;
29729 	int		ill_index;
29730 	mblk_t		*nxt_mp, *first_mp;
29731 	boolean_t	xmit_drop = B_FALSE;
29732 	ip_proc_t	proc;
29733 	ill_t		*out_ill;
29734 	int		pkt_len;
29735 
29736 	arpce = ire->ire_nce;
29737 	ASSERT(arpce != NULL);
29738 
29739 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
29740 
29741 	mutex_enter(&arpce->nce_lock);
29742 	switch (arpce->nce_state) {
29743 	case ND_REACHABLE:
29744 		/* If there are other queued packets, queue this packet */
29745 		if (arpce->nce_qd_mp != NULL) {
29746 			if (mp != NULL)
29747 				nce_queue_mp_common(arpce, mp, B_FALSE);
29748 			mp = arpce->nce_qd_mp;
29749 		}
29750 		arpce->nce_qd_mp = NULL;
29751 		mutex_exit(&arpce->nce_lock);
29752 
29753 		/*
29754 		 * Flush the queue.  In the common case, where the
29755 		 * ARP is already resolved,  it will go through the
29756 		 * while loop only once.
29757 		 */
29758 		while (mp != NULL) {
29759 
29760 			nxt_mp = mp->b_next;
29761 			mp->b_next = NULL;
29762 			ASSERT(mp->b_datap->db_type != M_CTL);
29763 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
29764 			/*
29765 			 * This info is needed for IPQOS to do COS marking
29766 			 * in ip_wput_attach_llhdr->ip_process.
29767 			 */
29768 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
29769 			mp->b_prev = NULL;
29770 
29771 			/* set up ill index for outbound qos processing */
29772 			out_ill = ire_to_ill(ire);
29773 			ill_index = out_ill->ill_phyint->phyint_ifindex;
29774 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
29775 			    ill_index);
29776 			if (first_mp == NULL) {
29777 				xmit_drop = B_TRUE;
29778 				BUMP_MIB(out_ill->ill_ip_mib,
29779 				    ipIfStatsOutDiscards);
29780 				goto next_mp;
29781 			}
29782 			/* non-ipsec hw accel case */
29783 			if (io == NULL || !io->ipsec_out_accelerated) {
29784 				/* send it */
29785 				q = ire->ire_stq;
29786 				if (proc == IPP_FWD_OUT) {
29787 					UPDATE_IB_PKT_COUNT(ire);
29788 				} else {
29789 					UPDATE_OB_PKT_COUNT(ire);
29790 				}
29791 				ire->ire_last_used_time = lbolt;
29792 
29793 				if (flow_ctl_enabled || canputnext(q)) {
29794 					if (proc == IPP_FWD_OUT) {
29795 
29796 					BUMP_MIB(out_ill->ill_ip_mib,
29797 					    ipIfStatsHCOutForwDatagrams);
29798 
29799 					}
29800 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
29801 					    pkt_len);
29802 
29803 					putnext(q, first_mp);
29804 				} else {
29805 					BUMP_MIB(out_ill->ill_ip_mib,
29806 					    ipIfStatsOutDiscards);
29807 					xmit_drop = B_TRUE;
29808 					freemsg(first_mp);
29809 				}
29810 			} else {
29811 				/*
29812 				 * Safety Pup says: make sure this
29813 				 *  is going to the right interface!
29814 				 */
29815 				ill_t *ill1 =
29816 				    (ill_t *)ire->ire_stq->q_ptr;
29817 				int ifindex =
29818 				    ill1->ill_phyint->phyint_ifindex;
29819 				if (ifindex !=
29820 				    io->ipsec_out_capab_ill_index) {
29821 					xmit_drop = B_TRUE;
29822 					freemsg(mp);
29823 				} else {
29824 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
29825 					    pkt_len);
29826 					ipsec_hw_putnext(ire->ire_stq, mp);
29827 				}
29828 			}
29829 next_mp:
29830 			mp = nxt_mp;
29831 		} /* while (mp != NULL) */
29832 		if (xmit_drop)
29833 			return (SEND_FAILED);
29834 		else
29835 			return (SEND_PASSED);
29836 
29837 	case ND_INITIAL:
29838 	case ND_INCOMPLETE:
29839 
29840 		/*
29841 		 * While we do send off packets to dests that
29842 		 * use fully-resolved CGTP routes, we do not
29843 		 * handle unresolved CGTP routes.
29844 		 */
29845 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
29846 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
29847 
29848 		if (mp != NULL) {
29849 			/* queue the packet */
29850 			nce_queue_mp_common(arpce, mp, B_FALSE);
29851 		}
29852 
29853 		if (arpce->nce_state == ND_INCOMPLETE) {
29854 			mutex_exit(&arpce->nce_lock);
29855 			DTRACE_PROBE3(ip__xmit__incomplete,
29856 			    (ire_t *), ire, (mblk_t *), mp,
29857 			    (ipsec_out_t *), io);
29858 			return (LOOKUP_IN_PROGRESS);
29859 		}
29860 
29861 		arpce->nce_state = ND_INCOMPLETE;
29862 		mutex_exit(&arpce->nce_lock);
29863 		/*
29864 		 * Note that ire_add() (called from ire_forward())
29865 		 * holds a ref on the ire until ARP is completed.
29866 		 */
29867 
29868 		ire_arpresolve(ire, ire_to_ill(ire));
29869 		return (LOOKUP_IN_PROGRESS);
29870 	default:
29871 		ASSERT(0);
29872 		mutex_exit(&arpce->nce_lock);
29873 		return (LLHDR_RESLV_FAILED);
29874 	}
29875 }
29876 
29877 #undef	UPDATE_IP_MIB_OB_COUNTERS
29878 
29879 /*
29880  * Return B_TRUE if the buffers differ in length or content.
29881  * This is used for comparing extension header buffers.
29882  * Note that an extension header would be declared different
29883  * even if all that changed was the next header value in that header i.e.
29884  * what really changed is the next extension header.
29885  */
29886 boolean_t
29887 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
29888     uint_t blen)
29889 {
29890 	if (!b_valid)
29891 		blen = 0;
29892 
29893 	if (alen != blen)
29894 		return (B_TRUE);
29895 	if (alen == 0)
29896 		return (B_FALSE);	/* Both zero length */
29897 	return (bcmp(abuf, bbuf, alen));
29898 }
29899 
29900 /*
29901  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
29902  * Return B_FALSE if memory allocation fails - don't change any state!
29903  */
29904 boolean_t
29905 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29906     const void *src, uint_t srclen)
29907 {
29908 	void *dst;
29909 
29910 	if (!src_valid)
29911 		srclen = 0;
29912 
29913 	ASSERT(*dstlenp == 0);
29914 	if (src != NULL && srclen != 0) {
29915 		dst = mi_alloc(srclen, BPRI_MED);
29916 		if (dst == NULL)
29917 			return (B_FALSE);
29918 	} else {
29919 		dst = NULL;
29920 	}
29921 	if (*dstp != NULL)
29922 		mi_free(*dstp);
29923 	*dstp = dst;
29924 	*dstlenp = dst == NULL ? 0 : srclen;
29925 	return (B_TRUE);
29926 }
29927 
29928 /*
29929  * Replace what is in *dst, *dstlen with the source.
29930  * Assumes ip_allocbuf has already been called.
29931  */
29932 void
29933 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29934     const void *src, uint_t srclen)
29935 {
29936 	if (!src_valid)
29937 		srclen = 0;
29938 
29939 	ASSERT(*dstlenp == srclen);
29940 	if (src != NULL && srclen != 0)
29941 		bcopy(src, *dstp, srclen);
29942 }
29943 
29944 /*
29945  * Free the storage pointed to by the members of an ip6_pkt_t.
29946  */
29947 void
29948 ip6_pkt_free(ip6_pkt_t *ipp)
29949 {
29950 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
29951 
29952 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
29953 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
29954 		ipp->ipp_hopopts = NULL;
29955 		ipp->ipp_hopoptslen = 0;
29956 	}
29957 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
29958 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
29959 		ipp->ipp_rtdstopts = NULL;
29960 		ipp->ipp_rtdstoptslen = 0;
29961 	}
29962 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
29963 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
29964 		ipp->ipp_dstopts = NULL;
29965 		ipp->ipp_dstoptslen = 0;
29966 	}
29967 	if (ipp->ipp_fields & IPPF_RTHDR) {
29968 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
29969 		ipp->ipp_rthdr = NULL;
29970 		ipp->ipp_rthdrlen = 0;
29971 	}
29972 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
29973 	    IPPF_RTHDR);
29974 }
29975