xref: /illumos-gate/usr/src/uts/common/inet/ip/ip.c (revision fa94a07fd0519b8abfd871ad8fe60e6bebe1e2bb)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 /* Copyright (c) 1990 Mentat Inc. */
27 
28 #pragma ident	"%Z%%M%	%I%	%E% SMI"
29 
30 #include <sys/types.h>
31 #include <sys/stream.h>
32 #include <sys/dlpi.h>
33 #include <sys/stropts.h>
34 #include <sys/sysmacros.h>
35 #include <sys/strsubr.h>
36 #include <sys/strlog.h>
37 #include <sys/strsun.h>
38 #include <sys/zone.h>
39 #define	_SUN_TPI_VERSION 2
40 #include <sys/tihdr.h>
41 #include <sys/xti_inet.h>
42 #include <sys/ddi.h>
43 #include <sys/sunddi.h>
44 #include <sys/cmn_err.h>
45 #include <sys/debug.h>
46 #include <sys/kobj.h>
47 #include <sys/modctl.h>
48 #include <sys/atomic.h>
49 #include <sys/policy.h>
50 #include <sys/priv.h>
51 
52 #include <sys/systm.h>
53 #include <sys/param.h>
54 #include <sys/kmem.h>
55 #include <sys/sdt.h>
56 #include <sys/socket.h>
57 #include <sys/vtrace.h>
58 #include <sys/isa_defs.h>
59 #include <net/if.h>
60 #include <net/if_arp.h>
61 #include <net/route.h>
62 #include <sys/sockio.h>
63 #include <netinet/in.h>
64 #include <net/if_dl.h>
65 
66 #include <inet/common.h>
67 #include <inet/mi.h>
68 #include <inet/mib2.h>
69 #include <inet/nd.h>
70 #include <inet/arp.h>
71 #include <inet/snmpcom.h>
72 #include <inet/optcom.h>
73 #include <inet/kstatcom.h>
74 
75 #include <netinet/igmp_var.h>
76 #include <netinet/ip6.h>
77 #include <netinet/icmp6.h>
78 #include <netinet/sctp.h>
79 
80 #include <inet/ip.h>
81 #include <inet/ip_impl.h>
82 #include <inet/ip6.h>
83 #include <inet/ip6_asp.h>
84 #include <inet/tcp.h>
85 #include <inet/tcp_impl.h>
86 #include <inet/ip_multi.h>
87 #include <inet/ip_if.h>
88 #include <inet/ip_ire.h>
89 #include <inet/ip_ftable.h>
90 #include <inet/ip_rts.h>
91 #include <inet/ip_ndp.h>
92 #include <inet/ip_listutils.h>
93 #include <netinet/igmp.h>
94 #include <netinet/ip_mroute.h>
95 #include <inet/ipp_common.h>
96 
97 #include <net/pfkeyv2.h>
98 #include <inet/ipsec_info.h>
99 #include <inet/sadb.h>
100 #include <inet/ipsec_impl.h>
101 #include <sys/iphada.h>
102 #include <inet/tun.h>
103 #include <inet/ipdrop.h>
104 #include <inet/ip_netinfo.h>
105 
106 #include <sys/ethernet.h>
107 #include <net/if_types.h>
108 #include <sys/cpuvar.h>
109 
110 #include <ipp/ipp.h>
111 #include <ipp/ipp_impl.h>
112 #include <ipp/ipgpc/ipgpc.h>
113 
114 #include <sys/multidata.h>
115 #include <sys/pattr.h>
116 
117 #include <inet/ipclassifier.h>
118 #include <inet/sctp_ip.h>
119 #include <inet/sctp/sctp_impl.h>
120 #include <inet/udp_impl.h>
121 #include <inet/rawip_impl.h>
122 #include <inet/rts_impl.h>
123 #include <sys/sunddi.h>
124 
125 #include <sys/tsol/label.h>
126 #include <sys/tsol/tnet.h>
127 
128 #include <rpc/pmap_prot.h>
129 
130 /*
131  * Values for squeue switch:
132  * IP_SQUEUE_ENTER_NODRAIN: squeue_enter_nodrain
133  * IP_SQUEUE_ENTER: squeue_enter
134  * IP_SQUEUE_FILL: squeue_fill
135  */
136 int ip_squeue_enter = 2;	/* Setable in /etc/system */
137 
138 squeue_func_t ip_input_proc;
139 #define	SET_BPREV_FLAG(x)	((mblk_t *)(uintptr_t)(x))
140 
141 /*
142  * Setable in /etc/system
143  */
144 int ip_poll_normal_ms = 100;
145 int ip_poll_normal_ticks = 0;
146 int ip_modclose_ackwait_ms = 3000;
147 
148 /*
149  * It would be nice to have these present only in DEBUG systems, but the
150  * current design of the global symbol checking logic requires them to be
151  * unconditionally present.
152  */
153 uint_t ip_thread_data;			/* TSD key for debug support */
154 krwlock_t ip_thread_rwlock;
155 list_t	ip_thread_list;
156 
157 /*
158  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
159  */
160 
161 struct listptr_s {
162 	mblk_t	*lp_head;	/* pointer to the head of the list */
163 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
164 };
165 
166 typedef struct listptr_s listptr_t;
167 
168 /*
169  * This is used by ip_snmp_get_mib2_ip_route_media and
170  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
171  */
172 typedef struct iproutedata_s {
173 	uint_t		ird_idx;
174 	listptr_t	ird_route;	/* ipRouteEntryTable */
175 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
176 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
177 } iproutedata_t;
178 
179 /*
180  * Cluster specific hooks. These should be NULL when booted as a non-cluster
181  */
182 
183 /*
184  * Hook functions to enable cluster networking
185  * On non-clustered systems these vectors must always be NULL.
186  *
187  * Hook function to Check ip specified ip address is a shared ip address
188  * in the cluster
189  *
190  */
191 int (*cl_inet_isclusterwide)(uint8_t protocol,
192     sa_family_t addr_family, uint8_t *laddrp) = NULL;
193 
194 /*
195  * Hook function to generate cluster wide ip fragment identifier
196  */
197 uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
198     uint8_t *laddrp, uint8_t *faddrp) = NULL;
199 
200 /*
201  * Synchronization notes:
202  *
203  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
204  * MT level protection given by STREAMS. IP uses a combination of its own
205  * internal serialization mechanism and standard Solaris locking techniques.
206  * The internal serialization is per phyint (no IPMP) or per IPMP group.
207  * This is used to serialize plumbing operations, IPMP operations, certain
208  * multicast operations, most set ioctls, igmp/mld timers etc.
209  *
210  * Plumbing is a long sequence of operations involving message
211  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
212  * involved in plumbing operations. A natural model is to serialize these
213  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
214  * parallel without any interference. But various set ioctls on hme0 are best
215  * serialized. However if the system uses IPMP, the operations are easier if
216  * they are serialized on a per IPMP group basis since IPMP operations
217  * happen across ill's of a group. Thus the lowest common denominator is to
218  * serialize most set ioctls, multicast join/leave operations, IPMP operations
219  * igmp/mld timer operations, and processing of DLPI control messages received
220  * from drivers on a per IPMP group basis. If the system does not employ
221  * IPMP the serialization is on a per phyint basis. This serialization is
222  * provided by the ipsq_t and primitives operating on this. Details can
223  * be found in ip_if.c above the core primitives operating on ipsq_t.
224  *
225  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
226  * Simiarly lookup of an ire by a thread also returns a refheld ire.
227  * In addition ipif's and ill's referenced by the ire are also indirectly
228  * refheld. Thus no ipif or ill can vanish nor can critical parameters like
229  * the ipif's address or netmask change as long as an ipif is refheld
230  * directly or indirectly. For example an SIOCLIFADDR ioctl that changes the
231  * address of an ipif has to go through the ipsq_t. This ensures that only
232  * 1 such exclusive operation proceeds at any time on the ipif. It then
233  * deletes all ires associated with this ipif, and waits for all refcnts
234  * associated with this ipif to come down to zero. The address is changed
235  * only after the ipif has been quiesced. Then the ipif is brought up again.
236  * More details are described above the comment in ip_sioctl_flags.
237  *
238  * Packet processing is based mostly on IREs and are fully multi-threaded
239  * using standard Solaris MT techniques.
240  *
241  * There are explicit locks in IP to handle:
242  * - The ip_g_head list maintained by mi_open_link() and friends.
243  *
244  * - The reassembly data structures (one lock per hash bucket)
245  *
246  * - conn_lock is meant to protect conn_t fields. The fields actually
247  *   protected by conn_lock are documented in the conn_t definition.
248  *
249  * - ire_lock to protect some of the fields of the ire, IRE tables
250  *   (one lock per hash bucket). Refer to ip_ire.c for details.
251  *
252  * - ndp_g_lock and nce_lock for protecting NCEs.
253  *
254  * - ill_lock protects fields of the ill and ipif. Details in ip.h
255  *
256  * - ill_g_lock: This is a global reader/writer lock. Protects the following
257  *	* The AVL tree based global multi list of all ills.
258  *	* The linked list of all ipifs of an ill
259  *	* The <ill-ipsq> mapping
260  *	* The ipsq->ipsq_phyint_list threaded by phyint_ipsq_next
261  *	* The illgroup list threaded by ill_group_next.
262  *	* <ill-phyint> association
263  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
264  *   into an ill, changing the <ill-ipsq> mapping of an ill, insertion/deletion
265  *   of an ill into the illgrp list, changing the <ill-phyint> assoc of an ill
266  *   will all have to hold the ill_g_lock as writer for the actual duration
267  *   of the insertion/deletion/change. More details about the <ill-ipsq> mapping
268  *   may be found in the IPMP section.
269  *
270  * - ill_lock:  This is a per ill mutex.
271  *   It protects some members of the ill and is documented below.
272  *   It also protects the <ill-ipsq> mapping
273  *   It also protects the illgroup list threaded by ill_group_next.
274  *   It also protects the <ill-phyint> assoc.
275  *   It also protects the list of ipifs hanging off the ill.
276  *
277  * - ipsq_lock: This is a per ipsq_t mutex lock.
278  *   This protects all the other members of the ipsq struct except
279  *   ipsq_refs and ipsq_phyint_list which are protected by ill_g_lock
280  *
281  * - illgrp_lock: This is a per ill_group mutex lock.
282  *   The only thing it protects is the illgrp_ill_schednext member of ill_group
283  *   which dictates which is the next ill in an ill_group that is to be chosen
284  *   for sending outgoing packets, through creation of an IRE_CACHE that
285  *   references this ill.
286  *
287  * - phyint_lock: This is a per phyint mutex lock. Protects just the
288  *   phyint_flags
289  *
290  * - ip_g_nd_lock: This is a global reader/writer lock.
291  *   Any call to nd_load to load a new parameter to the ND table must hold the
292  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
293  *   as reader.
294  *
295  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
296  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
297  *   uniqueness check also done atomically.
298  *
299  * - ipsec_capab_ills_lock: This readers/writer lock protects the global
300  *   lists of IPsec capable ills (ipsec_capab_ills_{ah,esp}). It is taken
301  *   as a writer when adding or deleting elements from these lists, and
302  *   as a reader when walking these lists to send a SADB update to the
303  *   IPsec capable ills.
304  *
305  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
306  *   group list linked by ill_usesrc_grp_next. It also protects the
307  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
308  *   group is being added or deleted.  This lock is taken as a reader when
309  *   walking the list/group(eg: to get the number of members in a usesrc group).
310  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
311  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
312  *   example, it is not necessary to take this lock in the initial portion
313  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_groupname and
314  *   ip_sioctl_flags since the these operations are executed exclusively and
315  *   that ensures that the "usesrc group state" cannot change. The "usesrc
316  *   group state" change can happen only in the latter part of
317  *   ip_sioctl_slifusesrc and in ill_delete.
318  *
319  * Changing <ill-phyint>, <ill-ipsq>, <ill-illgroup> assocications.
320  *
321  * To change the <ill-phyint> association, the ill_g_lock must be held
322  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
323  * must be held.
324  *
325  * To change the <ill-ipsq> association the ill_g_lock must be held as writer
326  * and the ill_lock of the ill in question must be held.
327  *
328  * To change the <ill-illgroup> association the ill_g_lock must be held as
329  * writer and the ill_lock of the ill in question must be held.
330  *
331  * To add or delete an ipif from the list of ipifs hanging off the ill,
332  * ill_g_lock (writer) and ill_lock must be held and the thread must be
333  * a writer on the associated ipsq,.
334  *
335  * To add or delete an ill to the system, the ill_g_lock must be held as
336  * writer and the thread must be a writer on the associated ipsq.
337  *
338  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
339  * must be a writer on the associated ipsq.
340  *
341  * Lock hierarchy
342  *
343  * Some lock hierarchy scenarios are listed below.
344  *
345  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock
346  * ill_g_lock -> illgrp_lock -> ill_lock
347  * ill_g_lock -> ill_lock(s) -> phyint_lock
348  * ill_g_lock -> ndp_g_lock -> ill_lock -> nce_lock
349  * ill_g_lock -> ip_addr_avail_lock
350  * conn_lock -> irb_lock -> ill_lock -> ire_lock
351  * ill_g_lock -> ip_g_nd_lock
352  *
353  * When more than 1 ill lock is needed to be held, all ill lock addresses
354  * are sorted on address and locked starting from highest addressed lock
355  * downward.
356  *
357  * IPsec scenarios
358  *
359  * ipsa_lock -> ill_g_lock -> ill_lock
360  * ipsec_capab_ills_lock -> ill_g_lock -> ill_lock
361  * ipsec_capab_ills_lock -> ipsa_lock
362  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
363  *
364  * Trusted Solaris scenarios
365  *
366  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
367  * igsa_lock -> gcdb_lock
368  * gcgrp_rwlock -> ire_lock
369  * gcgrp_rwlock -> gcdb_lock
370  *
371  *
372  * Routing/forwarding table locking notes:
373  *
374  * Lock acquisition order: Radix tree lock, irb_lock.
375  * Requirements:
376  * i.  Walker must not hold any locks during the walker callback.
377  * ii  Walker must not see a truncated tree during the walk because of any node
378  *     deletion.
379  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
380  *     in many places in the code to walk the irb list. Thus even if all the
381  *     ires in a bucket have been deleted, we still can't free the radix node
382  *     until the ires have actually been inactive'd (freed).
383  *
384  * Tree traversal - Need to hold the global tree lock in read mode.
385  * Before dropping the global tree lock, need to either increment the ire_refcnt
386  * to ensure that the radix node can't be deleted.
387  *
388  * Tree add - Need to hold the global tree lock in write mode to add a
389  * radix node. To prevent the node from being deleted, increment the
390  * irb_refcnt, after the node is added to the tree. The ire itself is
391  * added later while holding the irb_lock, but not the tree lock.
392  *
393  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
394  * All associated ires must be inactive (i.e. freed), and irb_refcnt
395  * must be zero.
396  *
397  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
398  * global tree lock (read mode) for traversal.
399  *
400  * IPsec notes :
401  *
402  * IP interacts with the IPsec code (AH/ESP) by tagging a M_CTL message
403  * in front of the actual packet. For outbound datagrams, the M_CTL
404  * contains a ipsec_out_t (defined in ipsec_info.h), which has the
405  * information used by the IPsec code for applying the right level of
406  * protection. The information initialized by IP in the ipsec_out_t
407  * is determined by the per-socket policy or global policy in the system.
408  * For inbound datagrams, the M_CTL contains a ipsec_in_t (defined in
409  * ipsec_info.h) which starts out with nothing in it. It gets filled
410  * with the right information if it goes through the AH/ESP code, which
411  * happens if the incoming packet is secure. The information initialized
412  * by AH/ESP, is later used by IP(during fanouts to ULP) to see whether
413  * the policy requirements needed by per-socket policy or global policy
414  * is met or not.
415  *
416  * If there is both per-socket policy (set using setsockopt) and there
417  * is also global policy match for the 5 tuples of the socket,
418  * ipsec_override_policy() makes the decision of which one to use.
419  *
420  * For fully connected sockets i.e dst, src [addr, port] is known,
421  * conn_policy_cached is set indicating that policy has been cached.
422  * conn_in_enforce_policy may or may not be set depending on whether
423  * there is a global policy match or per-socket policy match.
424  * Policy inheriting happpens in ip_bind during the ipa_conn_t bind.
425  * Once the right policy is set on the conn_t, policy cannot change for
426  * this socket. This makes life simpler for TCP (UDP ?) where
427  * re-transmissions go out with the same policy. For symmetry, policy
428  * is cached for fully connected UDP sockets also. Thus if policy is cached,
429  * it also implies that policy is latched i.e policy cannot change
430  * on these sockets. As we have the right policy on the conn, we don't
431  * have to lookup global policy for every outbound and inbound datagram
432  * and thus serving as an optimization. Note that a global policy change
433  * does not affect fully connected sockets if they have policy. If fully
434  * connected sockets did not have any policy associated with it, global
435  * policy change may affect them.
436  *
437  * IP Flow control notes:
438  *
439  * Non-TCP streams are flow controlled by IP. On the send side, if the packet
440  * cannot be sent down to the driver by IP, because of a canput failure, IP
441  * does a putq on the conn_wq. This will cause ip_wsrv to run on the conn_wq.
442  * ip_wsrv in turn, inserts the conn in a list of conn's that need to be drained
443  * when the flowcontrol condition subsides. Ultimately STREAMS backenables the
444  * ip_wsrv on the IP module, which in turn does a qenable of the conn_wq of the
445  * first conn in the list of conn's to be drained. ip_wsrv on this conn drains
446  * the queued messages, and removes the conn from the drain list, if all
447  * messages were drained. It also qenables the next conn in the drain list to
448  * continue the drain process.
449  *
450  * In reality the drain list is not a single list, but a configurable number
451  * of lists. The ip_wsrv on the IP module, qenables the first conn in each
452  * list. If the ip_wsrv of the next qenabled conn does not run, because the
453  * stream closes, ip_close takes responsibility to qenable the next conn in
454  * the drain list. The directly called ip_wput path always does a putq, if
455  * it cannot putnext. Thus synchronization problems are handled between
456  * ip_wsrv and ip_close. conn_drain_insert and conn_drain_tail are the only
457  * functions that manipulate this drain list. Furthermore conn_drain_insert
458  * is called only from ip_wsrv, and there can be only 1 instance of ip_wsrv
459  * running on a queue at any time. conn_drain_tail can be simultaneously called
460  * from both ip_wsrv and ip_close.
461  *
462  * IPQOS notes:
463  *
464  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
465  * and IPQoS modules. IPPF includes hooks in IP at different control points
466  * (callout positions) which direct packets to IPQoS modules for policy
467  * processing. Policies, if present, are global.
468  *
469  * The callout positions are located in the following paths:
470  *		o local_in (packets destined for this host)
471  *		o local_out (packets orginating from this host )
472  *		o fwd_in  (packets forwarded by this m/c - inbound)
473  *		o fwd_out (packets forwarded by this m/c - outbound)
474  * Hooks at these callout points can be enabled/disabled using the ndd variable
475  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
476  * By default all the callout positions are enabled.
477  *
478  * Outbound (local_out)
479  * Hooks are placed in ip_wput_ire and ipsec_out_process.
480  *
481  * Inbound (local_in)
482  * Hooks are placed in ip_proto_input, icmp_inbound, ip_fanout_proto and
483  * TCP and UDP fanout routines.
484  *
485  * Forwarding (in and out)
486  * Hooks are placed in ip_rput_forward.
487  *
488  * IP Policy Framework processing (IPPF processing)
489  * Policy processing for a packet is initiated by ip_process, which ascertains
490  * that the classifier (ipgpc) is loaded and configured, failing which the
491  * packet resumes normal processing in IP. If the clasifier is present, the
492  * packet is acted upon by one or more IPQoS modules (action instances), per
493  * filters configured in ipgpc and resumes normal IP processing thereafter.
494  * An action instance can drop a packet in course of its processing.
495  *
496  * A boolean variable, ip_policy, is used in all the fanout routines that can
497  * invoke ip_process for a packet. This variable indicates if the packet should
498  * to be sent for policy processing. The variable is set to B_TRUE by default,
499  * i.e. when the routines are invoked in the normal ip procesing path for a
500  * packet. The two exceptions being ip_wput_local and icmp_inbound_error_fanout;
501  * ip_policy is set to B_FALSE for all the routines called in these two
502  * functions because, in the former case,  we don't process loopback traffic
503  * currently while in the latter, the packets have already been processed in
504  * icmp_inbound.
505  *
506  * Zones notes:
507  *
508  * The partitioning rules for networking are as follows:
509  * 1) Packets coming from a zone must have a source address belonging to that
510  * zone.
511  * 2) Packets coming from a zone can only be sent on a physical interface on
512  * which the zone has an IP address.
513  * 3) Between two zones on the same machine, packet delivery is only allowed if
514  * there's a matching route for the destination and zone in the forwarding
515  * table.
516  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
517  * different zones can bind to the same port with the wildcard address
518  * (INADDR_ANY).
519  *
520  * The granularity of interface partitioning is at the logical interface level.
521  * Therefore, every zone has its own IP addresses, and incoming packets can be
522  * attributed to a zone unambiguously. A logical interface is placed into a zone
523  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
524  * structure. Rule (1) is implemented by modifying the source address selection
525  * algorithm so that the list of eligible addresses is filtered based on the
526  * sending process zone.
527  *
528  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
529  * across all zones, depending on their type. Here is the break-up:
530  *
531  * IRE type				Shared/exclusive
532  * --------				----------------
533  * IRE_BROADCAST			Exclusive
534  * IRE_DEFAULT (default routes)		Shared (*)
535  * IRE_LOCAL				Exclusive (x)
536  * IRE_LOOPBACK				Exclusive
537  * IRE_PREFIX (net routes)		Shared (*)
538  * IRE_CACHE				Exclusive
539  * IRE_IF_NORESOLVER (interface routes)	Exclusive
540  * IRE_IF_RESOLVER (interface routes)	Exclusive
541  * IRE_HOST (host routes)		Shared (*)
542  *
543  * (*) A zone can only use a default or off-subnet route if the gateway is
544  * directly reachable from the zone, that is, if the gateway's address matches
545  * one of the zone's logical interfaces.
546  *
547  * (x) IRE_LOCAL are handled a bit differently, since for all other entries
548  * in ire_ctable and IRE_INTERFACE, ire_src_addr is what can be used as source
549  * when sending packets using the IRE. For IRE_LOCAL ire_src_addr is the IP
550  * address of the zone itself (the destination). Since IRE_LOCAL is used
551  * for communication between zones, ip_wput_ire has special logic to set
552  * the right source address when sending using an IRE_LOCAL.
553  *
554  * Furthermore, when ip_restrict_interzone_loopback is set (the default),
555  * ire_cache_lookup restricts loopback using an IRE_LOCAL
556  * between zone to the case when L2 would have conceptually looped the packet
557  * back, i.e. the loopback which is required since neither Ethernet drivers
558  * nor Ethernet hardware loops them back. This is the case when the normal
559  * routes (ignoring IREs with different zoneids) would send out the packet on
560  * the same ill (or ill group) as the ill with which is IRE_LOCAL is
561  * associated.
562  *
563  * Multiple zones can share a common broadcast address; typically all zones
564  * share the 255.255.255.255 address. Incoming as well as locally originated
565  * broadcast packets must be dispatched to all the zones on the broadcast
566  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
567  * since some zones may not be on the 10.16.72/24 network. To handle this, each
568  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
569  * sent to every zone that has an IRE_BROADCAST entry for the destination
570  * address on the input ill, see conn_wantpacket().
571  *
572  * Applications in different zones can join the same multicast group address.
573  * For IPv4, group memberships are per-logical interface, so they're already
574  * inherently part of a zone. For IPv6, group memberships are per-physical
575  * interface, so we distinguish IPv6 group memberships based on group address,
576  * interface and zoneid. In both cases, received multicast packets are sent to
577  * every zone for which a group membership entry exists. On IPv6 we need to
578  * check that the target zone still has an address on the receiving physical
579  * interface; it could have been removed since the application issued the
580  * IPV6_JOIN_GROUP.
581  */
582 
583 /*
584  * Squeue Fanout flags:
585  *	0: No fanout.
586  *	1: Fanout across all squeues
587  */
588 boolean_t	ip_squeue_fanout = 0;
589 
590 /*
591  * Maximum dups allowed per packet.
592  */
593 uint_t ip_max_frag_dups = 10;
594 
595 #define	IS_SIMPLE_IPH(ipha)						\
596 	((ipha)->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION)
597 
598 /* RFC1122 Conformance */
599 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
600 
601 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
602 
603 static int	conn_set_held_ipif(conn_t *, ipif_t **, ipif_t *);
604 
605 static int	ip_open(queue_t *q, dev_t *devp, int flag, int sflag,
606 		    cred_t *credp, boolean_t isv6);
607 static mblk_t	*ip_wput_attach_llhdr(mblk_t *, ire_t *, ip_proc_t, uint32_t);
608 
609 static void	icmp_frag_needed(queue_t *, mblk_t *, int, zoneid_t,
610 		    ip_stack_t *);
611 static void	icmp_inbound(queue_t *, mblk_t *, boolean_t, ill_t *, int,
612 		    uint32_t, boolean_t, boolean_t, ill_t *, zoneid_t);
613 static ipaddr_t	icmp_get_nexthop_addr(ipha_t *, ill_t *, zoneid_t, mblk_t *mp);
614 static boolean_t icmp_inbound_too_big(icmph_t *, ipha_t *, ill_t *, zoneid_t,
615 		    mblk_t *, int, ip_stack_t *);
616 static void	icmp_inbound_error_fanout(queue_t *, ill_t *, mblk_t *,
617 		    icmph_t *, ipha_t *, int, int, boolean_t, boolean_t,
618 		    ill_t *, zoneid_t);
619 static void	icmp_options_update(ipha_t *);
620 static void	icmp_param_problem(queue_t *, mblk_t *, uint8_t, zoneid_t,
621 		    ip_stack_t *);
622 static void	icmp_pkt(queue_t *, mblk_t *, void *, size_t, boolean_t,
623 		    zoneid_t zoneid, ip_stack_t *);
624 static mblk_t	*icmp_pkt_err_ok(mblk_t *, ip_stack_t *);
625 static void	icmp_redirect(ill_t *, mblk_t *);
626 static void	icmp_send_redirect(queue_t *, mblk_t *, ipaddr_t,
627 		    ip_stack_t *);
628 
629 static void	ip_arp_news(queue_t *, mblk_t *);
630 static boolean_t ip_bind_insert_ire(mblk_t *, ire_t *, iulp_t *,
631 		    ip_stack_t *);
632 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
633 char		*ip_dot_addr(ipaddr_t, char *);
634 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
635 int		ip_close(queue_t *, int);
636 static char	*ip_dot_saddr(uchar_t *, char *);
637 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
638 		    boolean_t, boolean_t, ill_t *, zoneid_t);
639 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
640 		    boolean_t, boolean_t, zoneid_t);
641 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
642 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
643 static void	ip_lrput(queue_t *, mblk_t *);
644 ipaddr_t	ip_net_mask(ipaddr_t);
645 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, conn_t *, zoneid_t,
646 		    ip_stack_t *);
647 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
648 		    conn_t *, uint32_t, zoneid_t, ip_opt_info_t *);
649 char		*ip_nv_lookup(nv_t *, int);
650 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
651 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
652 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
653 static boolean_t	ip_param_register(IDP *ndp, ipparam_t *, size_t,
654     ipndp_t *, size_t);
655 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
656 void	ip_rput(queue_t *, mblk_t *);
657 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
658 		    void *dummy_arg);
659 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
660 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *,
661     ip_stack_t *);
662 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
663 			    ire_t *, ip_stack_t *);
664 static boolean_t	ip_rput_multimblk_ipoptions(queue_t *, ill_t *,
665 			    mblk_t *, ipha_t **, ipaddr_t *, ip_stack_t *);
666 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *,
667     ip_stack_t *);
668 static boolean_t ip_rput_fragment(queue_t *, mblk_t **, ipha_t *, uint32_t *,
669 		    uint16_t *);
670 int		ip_snmp_get(queue_t *, mblk_t *, int);
671 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *,
672 		    mib2_ipIfStatsEntry_t *, ip_stack_t *);
673 static mblk_t	*ip_snmp_get_mib2_ip_traffic_stats(queue_t *, mblk_t *,
674 		    ip_stack_t *);
675 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *, ip_stack_t *);
676 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *, ip_stack_t *ipst);
677 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *, ip_stack_t *ipst);
678 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *, ip_stack_t *ipst);
679 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *, ip_stack_t *ipst);
680 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *,
681 		    ip_stack_t *ipst);
682 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *,
683 		    ip_stack_t *ipst);
684 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *,
685 		    ip_stack_t *ipst);
686 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *,
687 		    ip_stack_t *ipst);
688 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *,
689 		    ip_stack_t *ipst);
690 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *,
691 		    ip_stack_t *ipst);
692 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *,
693 		    ip_stack_t *ipst);
694 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *,
695 		    ip_stack_t *ipst);
696 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *,
697 		    ip_stack_t *ipst);
698 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *,
699 		    ip_stack_t *ipst);
700 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
701 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
702 static int	ip_snmp_get2_v6_media(nce_t *, iproutedata_t *);
703 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
704 static boolean_t	ip_source_routed(ipha_t *, ip_stack_t *);
705 static boolean_t	ip_source_route_included(ipha_t *);
706 static void	ip_trash_ire_reclaim_stack(ip_stack_t *);
707 
708 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t,
709 		    zoneid_t, ip_stack_t *);
710 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int, ip_stack_t *);
711 static void	ip_wput_local_options(ipha_t *, ip_stack_t *);
712 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
713 		    zoneid_t, ip_stack_t *);
714 
715 static void	conn_drain_init(ip_stack_t *);
716 static void	conn_drain_fini(ip_stack_t *);
717 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
718 
719 static void	conn_walk_drain(ip_stack_t *);
720 static void	conn_walk_fanout_table(connf_t *, uint_t, pfv_t, void *,
721     zoneid_t);
722 
723 static void	*ip_stack_init(netstackid_t stackid, netstack_t *ns);
724 static void	ip_stack_shutdown(netstackid_t stackid, void *arg);
725 static void	ip_stack_fini(netstackid_t stackid, void *arg);
726 
727 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
728     zoneid_t);
729 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
730     void *dummy_arg);
731 
732 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
733 
734 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
735     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
736     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
737 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
738 
739 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
740 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
741     caddr_t, cred_t *);
742 extern int	ip_squeue_bind_set(queue_t *q, mblk_t *mp, char *value,
743     caddr_t cp, cred_t *cr);
744 extern int	ip_squeue_profile_set(queue_t *, mblk_t *, char *, caddr_t,
745     cred_t *);
746 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
747     caddr_t cp, cred_t *cr);
748 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
749     cred_t *);
750 static int	ipmp_hook_emulation_set(queue_t *, mblk_t *, char *, caddr_t,
751     cred_t *);
752 static squeue_func_t ip_squeue_switch(int);
753 
754 static void	*ip_kstat_init(netstackid_t, ip_stack_t *);
755 static void	ip_kstat_fini(netstackid_t, kstat_t *);
756 static int	ip_kstat_update(kstat_t *kp, int rw);
757 static void	*icmp_kstat_init(netstackid_t);
758 static void	icmp_kstat_fini(netstackid_t, kstat_t *);
759 static int	icmp_kstat_update(kstat_t *kp, int rw);
760 static void	*ip_kstat2_init(netstackid_t, ip_stat_t *);
761 static void	ip_kstat2_fini(netstackid_t, kstat_t *);
762 
763 static int	ip_conn_report(queue_t *, mblk_t *, caddr_t, cred_t *);
764 
765 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
766     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
767 
768 static void	ip_rput_process_forward(queue_t *, mblk_t *, ire_t *,
769     ipha_t *, ill_t *, boolean_t);
770 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
771 
772 /* How long, in seconds, we allow frags to hang around. */
773 #define	IP_FRAG_TIMEOUT	60
774 
775 /*
776  * Threshold which determines whether MDT should be used when
777  * generating IP fragments; payload size must be greater than
778  * this threshold for MDT to take place.
779  */
780 #define	IP_WPUT_FRAG_MDT_MIN	32768
781 
782 /* Setable in /etc/system only */
783 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
784 
785 static long ip_rput_pullups;
786 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
787 
788 vmem_t *ip_minor_arena;
789 
790 int	ip_debug;
791 
792 #ifdef DEBUG
793 uint32_t ipsechw_debug = 0;
794 #endif
795 
796 /*
797  * Multirouting/CGTP stuff
798  */
799 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
800 
801 /*
802  * XXX following really should only be in a header. Would need more
803  * header and .c clean up first.
804  */
805 extern optdb_obj_t	ip_opt_obj;
806 
807 ulong_t ip_squeue_enter_unbound = 0;
808 
809 /*
810  * Named Dispatch Parameter Table.
811  * All of these are alterable, within the min/max values given, at run time.
812  */
813 static ipparam_t	lcl_param_arr[] = {
814 	/* min	max	value	name */
815 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
816 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
817 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
818 	{  0,	1,	0,	"ip_respond_to_timestamp"},
819 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
820 	{  0,	1,	1,	"ip_send_redirects"},
821 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
822 	{  0,	10,	0,	"ip_mrtdebug"},
823 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
824 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
825 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
826 	{  1,	255,	255,	"ip_def_ttl" },
827 	{  0,	1,	0,	"ip_forward_src_routed"},
828 	{  0,	256,	32,	"ip_wroff_extra" },
829 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
830 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
831 	{  0,	1,	1,	"ip_path_mtu_discovery" },
832 	{  0,	240,	30,	"ip_ignore_delete_time" },
833 	{  0,	1,	0,	"ip_ignore_redirect" },
834 	{  0,	1,	1,	"ip_output_queue" },
835 	{  1,	254,	1,	"ip_broadcast_ttl" },
836 	{  0,	99999,	100,	"ip_icmp_err_interval" },
837 	{  1,	99999,	10,	"ip_icmp_err_burst" },
838 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
839 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
840 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
841 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
842 	{  0,	1,	1,	"icmp_accept_clear_messages" },
843 	{  0,	1,	1,	"igmp_accept_clear_messages" },
844 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
845 				"ip_ndp_delay_first_probe_time"},
846 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
847 				"ip_ndp_max_unicast_solicit"},
848 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
849 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
850 	{  0,	1,	0,	"ip6_forward_src_routed"},
851 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
852 	{  0,	1,	1,	"ip6_send_redirects"},
853 	{  0,	1,	0,	"ip6_ignore_redirect" },
854 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
855 
856 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
857 
858 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
859 
860 	{  0,	1,	1,	"pim_accept_clear_messages" },
861 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
862 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
863 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
864 	{  0,	15,	0,	"ip_policy_mask" },
865 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
866 	{  0,	255,	1,	"ip_multirt_ttl" },
867 	{  0,	1,	1,	"ip_multidata_outbound" },
868 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
869 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
870 	{  0,	1000,	1,	"ip_max_temp_defend" },
871 	{  0,	1000,	3,	"ip_max_defend" },
872 	{  0,	999999,	30,	"ip_defend_interval" },
873 	{  0,	3600000, 300000, "ip_dup_recovery" },
874 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
875 	{  0,	1,	1,	"ip_lso_outbound" },
876 	{  IGMP_V1_ROUTER, IGMP_V3_ROUTER, IGMP_V3_ROUTER, "igmp_max_version" },
877 	{  MLD_V1_ROUTER, MLD_V2_ROUTER, MLD_V2_ROUTER, "mld_max_version" },
878 #ifdef DEBUG
879 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
880 #else
881 	{  0,	0,	0,	"" },
882 #endif
883 };
884 
885 /*
886  * Extended NDP table
887  * The addresses for the first two are filled in to be ips_ip_g_forward
888  * and ips_ipv6_forward at init time.
889  */
890 static ipndp_t	lcl_ndp_arr[] = {
891 	/* getf			setf		data			name */
892 #define	IPNDP_IP_FORWARDING_OFFSET	0
893 	{  ip_param_generic_get,	ip_forward_set,	NULL,
894 	    "ip_forwarding" },
895 #define	IPNDP_IP6_FORWARDING_OFFSET	1
896 	{  ip_param_generic_get,	ip_forward_set,	NULL,
897 	    "ip6_forwarding" },
898 	{  ip_ill_report,	NULL,		NULL,
899 	    "ip_ill_status" },
900 	{  ip_ipif_report,	NULL,		NULL,
901 	    "ip_ipif_status" },
902 	{  ip_ire_report,	NULL,		NULL,
903 	    "ipv4_ire_status" },
904 	{  ip_ire_report_v6,	NULL,		NULL,
905 	    "ipv6_ire_status" },
906 	{  ip_conn_report,	NULL,		NULL,
907 	    "ip_conn_status" },
908 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
909 	    "ip_rput_pullups" },
910 	{  ndp_report,		NULL,		NULL,
911 	    "ip_ndp_cache_report" },
912 	{  ip_srcid_report,	NULL,		NULL,
913 	    "ip_srcid_status" },
914 	{ ip_param_generic_get, ip_squeue_profile_set,
915 	    (caddr_t)&ip_squeue_profile, "ip_squeue_profile" },
916 	{ ip_param_generic_get, ip_squeue_bind_set,
917 	    (caddr_t)&ip_squeue_bind, "ip_squeue_bind" },
918 	{ ip_param_generic_get, ip_input_proc_set,
919 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
920 	{ ip_param_generic_get, ip_int_set,
921 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
922 #define	IPNDP_CGTP_FILTER_OFFSET	14
923 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, NULL,
924 	    "ip_cgtp_filter" },
925 	{ ip_param_generic_get, ip_int_set,
926 	    (caddr_t)&ip_soft_rings_cnt, "ip_soft_rings_cnt" },
927 #define	IPNDP_IPMP_HOOK_OFFSET	16
928 	{  ip_param_generic_get, ipmp_hook_emulation_set, NULL,
929 	    "ipmp_hook_emulation" },
930 	{  ip_param_generic_get, ip_int_set, (caddr_t)&ip_debug,
931 	    "ip_debug" },
932 };
933 
934 /*
935  * Table of IP ioctls encoding the various properties of the ioctl and
936  * indexed based on the last byte of the ioctl command. Occasionally there
937  * is a clash, and there is more than 1 ioctl with the same last byte.
938  * In such a case 1 ioctl is encoded in the ndx table and the remaining
939  * ioctls are encoded in the misc table. An entry in the ndx table is
940  * retrieved by indexing on the last byte of the ioctl command and comparing
941  * the ioctl command with the value in the ndx table. In the event of a
942  * mismatch the misc table is then searched sequentially for the desired
943  * ioctl command.
944  *
945  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
946  */
947 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
948 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
949 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
950 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
951 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
952 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
953 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
954 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
955 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
956 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
957 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
958 
959 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
960 			MISC_CMD, ip_siocaddrt, NULL },
961 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
962 			MISC_CMD, ip_siocdelrt, NULL },
963 
964 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
965 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
966 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
967 			IF_CMD, ip_sioctl_get_addr, NULL },
968 
969 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
970 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
971 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
972 			IPI_GET_CMD | IPI_REPL,
973 			IF_CMD, ip_sioctl_get_dstaddr, NULL },
974 
975 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
976 			IPI_PRIV | IPI_WR | IPI_REPL,
977 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
978 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
979 			IPI_MODOK | IPI_GET_CMD | IPI_REPL,
980 			IF_CMD, ip_sioctl_get_flags, NULL },
981 
982 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
983 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
984 
985 	/* copyin size cannot be coded for SIOCGIFCONF */
986 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD,
987 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
988 
989 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
990 			IF_CMD, ip_sioctl_mtu, NULL },
991 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
992 			IF_CMD, ip_sioctl_get_mtu, NULL },
993 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
994 			IPI_GET_CMD | IPI_REPL,
995 			IF_CMD, ip_sioctl_get_brdaddr, NULL },
996 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
997 			IF_CMD, ip_sioctl_brdaddr, NULL },
998 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
999 			IPI_GET_CMD | IPI_REPL,
1000 			IF_CMD, ip_sioctl_get_netmask, NULL },
1001 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1002 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1003 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1004 			IPI_GET_CMD | IPI_REPL,
1005 			IF_CMD, ip_sioctl_get_metric, NULL },
1006 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1007 			IF_CMD, ip_sioctl_metric, NULL },
1008 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1009 
1010 	/* See 166-168 below for extended SIOC*XARP ioctls */
1011 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV,
1012 			ARP_CMD, ip_sioctl_arp, NULL },
1013 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD | IPI_REPL,
1014 			ARP_CMD, ip_sioctl_arp, NULL },
1015 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV,
1016 			ARP_CMD, ip_sioctl_arp, NULL },
1017 
1018 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1019 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1020 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1021 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1022 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1023 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1024 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1025 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1026 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1027 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1028 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1029 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1030 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1031 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1032 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1033 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1034 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1035 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1036 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1037 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1038 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1039 
1040 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1041 			MISC_CMD, if_unitsel, if_unitsel_restart },
1042 
1043 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1044 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1045 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1046 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1047 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1048 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1049 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1050 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1051 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1052 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1053 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1054 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1055 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1056 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1057 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1058 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1059 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1060 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1061 
1062 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1063 			IPI_PRIV | IPI_WR | IPI_MODOK,
1064 			IF_CMD, ip_sioctl_sifname, NULL },
1065 
1066 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1067 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1068 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1069 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1070 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1071 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1072 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1073 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1074 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1075 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1076 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1077 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1078 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1079 
1080 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD | IPI_REPL,
1081 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1082 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1083 			IF_CMD, ip_sioctl_get_muxid, NULL },
1084 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1085 			IPI_PRIV | IPI_WR | IPI_REPL,
1086 			IF_CMD, ip_sioctl_muxid, NULL },
1087 
1088 	/* Both if and lif variants share same func */
1089 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1090 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1091 	/* Both if and lif variants share same func */
1092 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1093 			IPI_PRIV | IPI_WR | IPI_REPL,
1094 			IF_CMD, ip_sioctl_slifindex, NULL },
1095 
1096 	/* copyin size cannot be coded for SIOCGIFCONF */
1097 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD,
1098 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1099 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1100 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1101 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1102 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1103 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1104 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1105 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1106 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1107 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1108 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1109 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1110 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1111 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1112 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1113 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1114 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1115 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1116 
1117 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1118 			IPI_PRIV | IPI_WR | IPI_REPL,
1119 			LIF_CMD, ip_sioctl_removeif,
1120 			ip_sioctl_removeif_restart },
1121 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1122 			IPI_GET_CMD | IPI_PRIV | IPI_WR | IPI_REPL,
1123 			LIF_CMD, ip_sioctl_addif, NULL },
1124 #define	SIOCLIFADDR_NDX 112
1125 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1126 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1127 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1128 			IPI_GET_CMD | IPI_REPL,
1129 			LIF_CMD, ip_sioctl_get_addr, NULL },
1130 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1131 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1132 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1133 			IPI_GET_CMD | IPI_REPL,
1134 			LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1135 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1136 			IPI_PRIV | IPI_WR | IPI_REPL,
1137 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1138 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1139 			IPI_GET_CMD | IPI_MODOK | IPI_REPL,
1140 			LIF_CMD, ip_sioctl_get_flags, NULL },
1141 
1142 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1143 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1144 
1145 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1146 			ip_sioctl_get_lifconf, NULL },
1147 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1148 			LIF_CMD, ip_sioctl_mtu, NULL },
1149 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD | IPI_REPL,
1150 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1151 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1152 			IPI_GET_CMD | IPI_REPL,
1153 			LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1154 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1155 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1156 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1157 			IPI_GET_CMD | IPI_REPL,
1158 			LIF_CMD, ip_sioctl_get_netmask, NULL },
1159 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1160 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1161 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1162 			IPI_GET_CMD | IPI_REPL,
1163 			LIF_CMD, ip_sioctl_get_metric, NULL },
1164 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1165 			LIF_CMD, ip_sioctl_metric, NULL },
1166 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1167 			IPI_PRIV | IPI_WR | IPI_MODOK | IPI_REPL,
1168 			LIF_CMD, ip_sioctl_slifname,
1169 			ip_sioctl_slifname_restart },
1170 
1171 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD | IPI_REPL,
1172 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1173 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1174 			IPI_GET_CMD | IPI_REPL,
1175 			LIF_CMD, ip_sioctl_get_muxid, NULL },
1176 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1177 			IPI_PRIV | IPI_WR | IPI_REPL,
1178 			LIF_CMD, ip_sioctl_muxid, NULL },
1179 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1180 			IPI_GET_CMD | IPI_REPL,
1181 			LIF_CMD, ip_sioctl_get_lifindex, 0 },
1182 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1183 			IPI_PRIV | IPI_WR | IPI_REPL,
1184 			LIF_CMD, ip_sioctl_slifindex, 0 },
1185 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1186 			LIF_CMD, ip_sioctl_token, NULL },
1187 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1188 			IPI_GET_CMD | IPI_REPL,
1189 			LIF_CMD, ip_sioctl_get_token, NULL },
1190 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1191 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1192 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1193 			IPI_GET_CMD | IPI_REPL,
1194 			LIF_CMD, ip_sioctl_get_subnet, NULL },
1195 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1196 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1197 
1198 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1199 			IPI_GET_CMD | IPI_REPL,
1200 			LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1201 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1202 			LIF_CMD, ip_siocdelndp_v6, NULL },
1203 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1204 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1205 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1206 			LIF_CMD, ip_siocsetndp_v6, NULL },
1207 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1208 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1209 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1210 			MISC_CMD, ip_sioctl_tonlink, NULL },
1211 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1212 			MISC_CMD, ip_sioctl_tmysite, NULL },
1213 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), IPI_REPL,
1214 			TUN_CMD, ip_sioctl_tunparam, NULL },
1215 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1216 			IPI_PRIV | IPI_WR,
1217 			TUN_CMD, ip_sioctl_tunparam, NULL },
1218 
1219 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1220 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1221 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1222 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1223 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1224 
1225 	/* 153 */ { SIOCLIFFAILOVER, sizeof (struct lifreq),
1226 			IPI_PRIV | IPI_WR | IPI_REPL,
1227 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1228 	/* 154 */ { SIOCLIFFAILBACK, sizeof (struct lifreq),
1229 			IPI_PRIV | IPI_WR | IPI_REPL,
1230 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1231 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1232 			IPI_PRIV | IPI_WR,
1233 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1234 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1235 			IPI_GET_CMD | IPI_REPL,
1236 			LIF_CMD, ip_sioctl_get_groupname, NULL },
1237 	/* 157 */ { SIOCGLIFOINDEX, sizeof (struct lifreq),
1238 			IPI_GET_CMD | IPI_REPL,
1239 			LIF_CMD, ip_sioctl_get_oindex, NULL },
1240 
1241 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1242 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1243 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1244 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1245 
1246 	/* 161 */ { SIOCSLIFOINDEX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1247 		    LIF_CMD, ip_sioctl_slifoindex, NULL },
1248 
1249 	/* These are handled in ip_sioctl_copyin_setup itself */
1250 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1251 			MISC_CMD, NULL, NULL },
1252 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1253 			MISC_CMD, NULL, NULL },
1254 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1255 
1256 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1257 			ip_sioctl_get_lifconf, NULL },
1258 
1259 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV,
1260 			XARP_CMD, ip_sioctl_arp, NULL },
1261 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD | IPI_REPL,
1262 			XARP_CMD, ip_sioctl_arp, NULL },
1263 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV,
1264 			XARP_CMD, ip_sioctl_arp, NULL },
1265 
1266 	/* SIOCPOPSOCKFS is not handled by IP */
1267 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1268 
1269 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1270 			IPI_GET_CMD | IPI_REPL,
1271 			LIF_CMD, ip_sioctl_get_lifzone, NULL },
1272 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1273 			IPI_PRIV | IPI_WR | IPI_REPL,
1274 			LIF_CMD, ip_sioctl_slifzone,
1275 			ip_sioctl_slifzone_restart },
1276 	/* 172-174 are SCTP ioctls and not handled by IP */
1277 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1278 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1279 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1280 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1281 			IPI_GET_CMD, LIF_CMD,
1282 			ip_sioctl_get_lifusesrc, 0 },
1283 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1284 			IPI_PRIV | IPI_WR,
1285 			LIF_CMD, ip_sioctl_slifusesrc,
1286 			NULL },
1287 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1288 			ip_sioctl_get_lifsrcof, NULL },
1289 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1290 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1291 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1292 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1293 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1294 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1295 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1296 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1297 	/* 182 */ { SIOCSIPMPFAILBACK, sizeof (int), IPI_PRIV, MISC_CMD,
1298 			ip_sioctl_set_ipmpfailback, NULL },
1299 	/* SIOCSENABLESDP is handled by SDP */
1300 	/* 183 */ { IPI_DONTCARE /* SIOCSENABLESDP */, 0, 0, 0, NULL, NULL },
1301 };
1302 
1303 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1304 
1305 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1306 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1307 		IPI_GET_CMD | IPI_REPL, TUN_CMD, ip_sioctl_tunparam, NULL },
1308 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1309 		TUN_CMD, ip_sioctl_tunparam, NULL },
1310 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1311 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1312 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1313 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1314 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1315 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1316 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1317 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_REPL | IPI_GET_CMD,
1318 		MISC_CMD, mrt_ioctl},
1319 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_REPL | IPI_GET_CMD,
1320 		MISC_CMD, mrt_ioctl},
1321 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_REPL | IPI_GET_CMD,
1322 		MISC_CMD, mrt_ioctl}
1323 };
1324 
1325 int ip_misc_ioctl_count =
1326     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1327 
1328 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1329 					/* Settable in /etc/system */
1330 /* Defined in ip_ire.c */
1331 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1332 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1333 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1334 
1335 static nv_t	ire_nv_arr[] = {
1336 	{ IRE_BROADCAST, "BROADCAST" },
1337 	{ IRE_LOCAL, "LOCAL" },
1338 	{ IRE_LOOPBACK, "LOOPBACK" },
1339 	{ IRE_CACHE, "CACHE" },
1340 	{ IRE_DEFAULT, "DEFAULT" },
1341 	{ IRE_PREFIX, "PREFIX" },
1342 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1343 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1344 	{ IRE_HOST, "HOST" },
1345 	{ 0 }
1346 };
1347 
1348 nv_t	*ire_nv_tbl = ire_nv_arr;
1349 
1350 /* Defined in ip_netinfo.c */
1351 extern ddi_taskq_t	*eventq_queue_nic;
1352 
1353 /* Simple ICMP IP Header Template */
1354 static ipha_t icmp_ipha = {
1355 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1356 };
1357 
1358 struct module_info ip_mod_info = {
1359 	IP_MOD_ID, IP_MOD_NAME, 1, INFPSZ, 65536, 1024
1360 };
1361 
1362 /*
1363  * Duplicate static symbols within a module confuses mdb; so we avoid the
1364  * problem by making the symbols here distinct from those in udp.c.
1365  */
1366 
1367 /*
1368  * Entry points for IP as a device and as a module.
1369  * FIXME: down the road we might want a separate module and driver qinit.
1370  * We have separate open functions for the /dev/ip and /dev/ip6 devices.
1371  */
1372 static struct qinit iprinitv4 = {
1373 	(pfi_t)ip_rput, NULL, ip_openv4, ip_close, NULL,
1374 	&ip_mod_info
1375 };
1376 
1377 struct qinit iprinitv6 = {
1378 	(pfi_t)ip_rput_v6, NULL, ip_openv6, ip_close, NULL,
1379 	&ip_mod_info
1380 };
1381 
1382 static struct qinit ipwinitv4 = {
1383 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1384 	&ip_mod_info
1385 };
1386 
1387 struct qinit ipwinitv6 = {
1388 	(pfi_t)ip_wput_v6, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1389 	&ip_mod_info
1390 };
1391 
1392 static struct qinit iplrinit = {
1393 	(pfi_t)ip_lrput, NULL, ip_openv4, ip_close, NULL,
1394 	&ip_mod_info
1395 };
1396 
1397 static struct qinit iplwinit = {
1398 	(pfi_t)ip_lwput, NULL, NULL, NULL, NULL,
1399 	&ip_mod_info
1400 };
1401 
1402 /* For AF_INET aka /dev/ip */
1403 struct streamtab ipinfov4 = {
1404 	&iprinitv4, &ipwinitv4, &iplrinit, &iplwinit
1405 };
1406 
1407 /* For AF_INET6 aka /dev/ip6 */
1408 struct streamtab ipinfov6 = {
1409 	&iprinitv6, &ipwinitv6, &iplrinit, &iplwinit
1410 };
1411 
1412 #ifdef	DEBUG
1413 static boolean_t skip_sctp_cksum = B_FALSE;
1414 #endif
1415 
1416 /*
1417  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1418  * ip_rput_v6(), ip_output(), etc.  If the message
1419  * block already has a M_CTL at the front of it, then simply set the zoneid
1420  * appropriately.
1421  */
1422 mblk_t *
1423 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid, ip_stack_t *ipst)
1424 {
1425 	mblk_t		*first_mp;
1426 	ipsec_out_t	*io;
1427 
1428 	ASSERT(zoneid != ALL_ZONES);
1429 	if (mp->b_datap->db_type == M_CTL) {
1430 		io = (ipsec_out_t *)mp->b_rptr;
1431 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1432 		io->ipsec_out_zoneid = zoneid;
1433 		return (mp);
1434 	}
1435 
1436 	first_mp = ipsec_alloc_ipsec_out(ipst->ips_netstack);
1437 	if (first_mp == NULL)
1438 		return (NULL);
1439 	io = (ipsec_out_t *)first_mp->b_rptr;
1440 	/* This is not a secure packet */
1441 	io->ipsec_out_secure = B_FALSE;
1442 	io->ipsec_out_zoneid = zoneid;
1443 	first_mp->b_cont = mp;
1444 	return (first_mp);
1445 }
1446 
1447 /*
1448  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1449  */
1450 mblk_t *
1451 ip_copymsg(mblk_t *mp)
1452 {
1453 	mblk_t *nmp;
1454 	ipsec_info_t *in;
1455 
1456 	if (mp->b_datap->db_type != M_CTL)
1457 		return (copymsg(mp));
1458 
1459 	in = (ipsec_info_t *)mp->b_rptr;
1460 
1461 	/*
1462 	 * Note that M_CTL is also used for delivering ICMP error messages
1463 	 * upstream to transport layers.
1464 	 */
1465 	if (in->ipsec_info_type != IPSEC_OUT &&
1466 	    in->ipsec_info_type != IPSEC_IN)
1467 		return (copymsg(mp));
1468 
1469 	nmp = copymsg(mp->b_cont);
1470 
1471 	if (in->ipsec_info_type == IPSEC_OUT) {
1472 		return (ipsec_out_tag(mp, nmp,
1473 		    ((ipsec_out_t *)in)->ipsec_out_ns));
1474 	} else {
1475 		return (ipsec_in_tag(mp, nmp,
1476 		    ((ipsec_in_t *)in)->ipsec_in_ns));
1477 	}
1478 }
1479 
1480 /* Generate an ICMP fragmentation needed message. */
1481 static void
1482 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid,
1483     ip_stack_t *ipst)
1484 {
1485 	icmph_t	icmph;
1486 	mblk_t *first_mp;
1487 	boolean_t mctl_present;
1488 
1489 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1490 
1491 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
1492 		if (mctl_present)
1493 			freeb(first_mp);
1494 		return;
1495 	}
1496 
1497 	bzero(&icmph, sizeof (icmph_t));
1498 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1499 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1500 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1501 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1502 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1503 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
1504 	    ipst);
1505 }
1506 
1507 /*
1508  * icmp_inbound deals with ICMP messages in the following ways.
1509  *
1510  * 1) It needs to send a reply back and possibly delivering it
1511  *    to the "interested" upper clients.
1512  * 2) It needs to send it to the upper clients only.
1513  * 3) It needs to change some values in IP only.
1514  * 4) It needs to change some values in IP and upper layers e.g TCP.
1515  *
1516  * We need to accomodate icmp messages coming in clear until we get
1517  * everything secure from the wire. If icmp_accept_clear_messages
1518  * is zero we check with the global policy and act accordingly. If
1519  * it is non-zero, we accept the message without any checks. But
1520  * *this does not mean* that this will be delivered to the upper
1521  * clients. By accepting we might send replies back, change our MTU
1522  * value etc. but delivery to the ULP/clients depends on their policy
1523  * dispositions.
1524  *
1525  * We handle the above 4 cases in the context of IPsec in the
1526  * following way :
1527  *
1528  * 1) Send the reply back in the same way as the request came in.
1529  *    If it came in encrypted, it goes out encrypted. If it came in
1530  *    clear, it goes out in clear. Thus, this will prevent chosen
1531  *    plain text attack.
1532  * 2) The client may or may not expect things to come in secure.
1533  *    If it comes in secure, the policy constraints are checked
1534  *    before delivering it to the upper layers. If it comes in
1535  *    clear, ipsec_inbound_accept_clear will decide whether to
1536  *    accept this in clear or not. In both the cases, if the returned
1537  *    message (IP header + 8 bytes) that caused the icmp message has
1538  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1539  *    sending up. If there are only 8 bytes of returned message, then
1540  *    upper client will not be notified.
1541  * 3) Check with global policy to see whether it matches the constaints.
1542  *    But this will be done only if icmp_accept_messages_in_clear is
1543  *    zero.
1544  * 4) If we need to change both in IP and ULP, then the decision taken
1545  *    while affecting the values in IP and while delivering up to TCP
1546  *    should be the same.
1547  *
1548  * 	There are two cases.
1549  *
1550  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1551  *	   failed), we will not deliver it to the ULP, even though they
1552  *	   are *willing* to accept in *clear*. This is fine as our global
1553  *	   disposition to icmp messages asks us reject the datagram.
1554  *
1555  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1556  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1557  *	   to deliver it to ULP (policy failed), it can lead to
1558  *	   consistency problems. The cases known at this time are
1559  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1560  *	   values :
1561  *
1562  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1563  *	     and Upper layer rejects. Then the communication will
1564  *	     come to a stop. This is solved by making similar decisions
1565  *	     at both levels. Currently, when we are unable to deliver
1566  *	     to the Upper Layer (due to policy failures) while IP has
1567  *	     adjusted ire_max_frag, the next outbound datagram would
1568  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1569  *	     will be with the right level of protection. Thus the right
1570  *	     value will be communicated even if we are not able to
1571  *	     communicate when we get from the wire initially. But this
1572  *	     assumes there would be at least one outbound datagram after
1573  *	     IP has adjusted its ire_max_frag value. To make things
1574  *	     simpler, we accept in clear after the validation of
1575  *	     AH/ESP headers.
1576  *
1577  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1578  *	     upper layer depending on the level of protection the upper
1579  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1580  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1581  *	     should be accepted in clear when the Upper layer expects secure.
1582  *	     Thus the communication may get aborted by some bad ICMP
1583  *	     packets.
1584  *
1585  * IPQoS Notes:
1586  * The only instance when a packet is sent for processing is when there
1587  * isn't an ICMP client and if we are interested in it.
1588  * If there is a client, IPPF processing will take place in the
1589  * ip_fanout_proto routine.
1590  *
1591  * Zones notes:
1592  * The packet is only processed in the context of the specified zone: typically
1593  * only this zone will reply to an echo request, and only interested clients in
1594  * this zone will receive a copy of the packet. This means that the caller must
1595  * call icmp_inbound() for each relevant zone.
1596  */
1597 static void
1598 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1599     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1600     ill_t *recv_ill, zoneid_t zoneid)
1601 {
1602 	icmph_t	*icmph;
1603 	ipha_t	*ipha;
1604 	int	iph_hdr_length;
1605 	int	hdr_length;
1606 	boolean_t	interested;
1607 	uint32_t	ts;
1608 	uchar_t	*wptr;
1609 	ipif_t	*ipif;
1610 	mblk_t *first_mp;
1611 	ipsec_in_t *ii;
1612 	ire_t *src_ire;
1613 	boolean_t onlink;
1614 	timestruc_t now;
1615 	uint32_t ill_index;
1616 	ip_stack_t *ipst;
1617 
1618 	ASSERT(ill != NULL);
1619 	ipst = ill->ill_ipst;
1620 
1621 	first_mp = mp;
1622 	if (mctl_present) {
1623 		mp = first_mp->b_cont;
1624 		ASSERT(mp != NULL);
1625 	}
1626 
1627 	ipha = (ipha_t *)mp->b_rptr;
1628 	if (ipst->ips_icmp_accept_clear_messages == 0) {
1629 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1630 		    ipha, NULL, mctl_present, ipst->ips_netstack);
1631 		if (first_mp == NULL)
1632 			return;
1633 	}
1634 
1635 	/*
1636 	 * On a labeled system, we have to check whether the zone itself is
1637 	 * permitted to receive raw traffic.
1638 	 */
1639 	if (is_system_labeled()) {
1640 		if (zoneid == ALL_ZONES)
1641 			zoneid = tsol_packet_to_zoneid(mp);
1642 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1643 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1644 			    zoneid));
1645 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1646 			freemsg(first_mp);
1647 			return;
1648 		}
1649 	}
1650 
1651 	/*
1652 	 * We have accepted the ICMP message. It means that we will
1653 	 * respond to the packet if needed. It may not be delivered
1654 	 * to the upper client depending on the policy constraints
1655 	 * and the disposition in ipsec_inbound_accept_clear.
1656 	 */
1657 
1658 	ASSERT(ill != NULL);
1659 
1660 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1661 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1662 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1663 		/* Last chance to get real. */
1664 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1665 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1666 			freemsg(first_mp);
1667 			return;
1668 		}
1669 		/* Refresh iph following the pullup. */
1670 		ipha = (ipha_t *)mp->b_rptr;
1671 	}
1672 	/* ICMP header checksum, including checksum field, should be zero. */
1673 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1674 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1675 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInCksumErrs);
1676 		freemsg(first_mp);
1677 		return;
1678 	}
1679 	/* The IP header will always be a multiple of four bytes */
1680 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1681 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1682 	    icmph->icmph_code));
1683 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1684 	/* We will set "interested" to "true" if we want a copy */
1685 	interested = B_FALSE;
1686 	switch (icmph->icmph_type) {
1687 	case ICMP_ECHO_REPLY:
1688 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1689 		break;
1690 	case ICMP_DEST_UNREACHABLE:
1691 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1692 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1693 		interested = B_TRUE;	/* Pass up to transport */
1694 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1695 		break;
1696 	case ICMP_SOURCE_QUENCH:
1697 		interested = B_TRUE;	/* Pass up to transport */
1698 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1699 		break;
1700 	case ICMP_REDIRECT:
1701 		if (!ipst->ips_ip_ignore_redirect)
1702 			interested = B_TRUE;
1703 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1704 		break;
1705 	case ICMP_ECHO_REQUEST:
1706 		/*
1707 		 * Whether to respond to echo requests that come in as IP
1708 		 * broadcasts or as IP multicast is subject to debate
1709 		 * (what isn't?).  We aim to please, you pick it.
1710 		 * Default is do it.
1711 		 */
1712 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1713 			/* unicast: always respond */
1714 			interested = B_TRUE;
1715 		} else if (CLASSD(ipha->ipha_dst)) {
1716 			/* multicast: respond based on tunable */
1717 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1718 		} else if (broadcast) {
1719 			/* broadcast: respond based on tunable */
1720 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1721 		}
1722 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1723 		break;
1724 	case ICMP_ROUTER_ADVERTISEMENT:
1725 	case ICMP_ROUTER_SOLICITATION:
1726 		break;
1727 	case ICMP_TIME_EXCEEDED:
1728 		interested = B_TRUE;	/* Pass up to transport */
1729 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1730 		break;
1731 	case ICMP_PARAM_PROBLEM:
1732 		interested = B_TRUE;	/* Pass up to transport */
1733 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1734 		break;
1735 	case ICMP_TIME_STAMP_REQUEST:
1736 		/* Response to Time Stamp Requests is local policy. */
1737 		if (ipst->ips_ip_g_resp_to_timestamp &&
1738 		    /* So is whether to respond if it was an IP broadcast. */
1739 		    (!broadcast || ipst->ips_ip_g_resp_to_timestamp_bcast)) {
1740 			int tstamp_len = 3 * sizeof (uint32_t);
1741 
1742 			if (wptr +  tstamp_len > mp->b_wptr) {
1743 				if (!pullupmsg(mp, wptr + tstamp_len -
1744 				    mp->b_rptr)) {
1745 					BUMP_MIB(ill->ill_ip_mib,
1746 					    ipIfStatsInDiscards);
1747 					freemsg(first_mp);
1748 					return;
1749 				}
1750 				/* Refresh ipha following the pullup. */
1751 				ipha = (ipha_t *)mp->b_rptr;
1752 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1753 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1754 			}
1755 			interested = B_TRUE;
1756 		}
1757 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1758 		break;
1759 	case ICMP_TIME_STAMP_REPLY:
1760 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1761 		break;
1762 	case ICMP_INFO_REQUEST:
1763 		/* Per RFC 1122 3.2.2.7, ignore this. */
1764 	case ICMP_INFO_REPLY:
1765 		break;
1766 	case ICMP_ADDRESS_MASK_REQUEST:
1767 		if ((ipst->ips_ip_respond_to_address_mask_broadcast ||
1768 		    !broadcast) &&
1769 		    /* TODO m_pullup of complete header? */
1770 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN) {
1771 			interested = B_TRUE;
1772 		}
1773 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1774 		break;
1775 	case ICMP_ADDRESS_MASK_REPLY:
1776 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1777 		break;
1778 	default:
1779 		interested = B_TRUE;	/* Pass up to transport */
1780 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1781 		break;
1782 	}
1783 	/* See if there is an ICMP client. */
1784 	if (ipst->ips_ipcl_proto_fanout[IPPROTO_ICMP].connf_head != NULL) {
1785 		/* If there is an ICMP client and we want one too, copy it. */
1786 		mblk_t *first_mp1;
1787 
1788 		if (!interested) {
1789 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1790 			    ip_policy, recv_ill, zoneid);
1791 			return;
1792 		}
1793 		first_mp1 = ip_copymsg(first_mp);
1794 		if (first_mp1 != NULL) {
1795 			ip_fanout_proto(q, first_mp1, ill, ipha,
1796 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1797 		}
1798 	} else if (!interested) {
1799 		freemsg(first_mp);
1800 		return;
1801 	} else {
1802 		/*
1803 		 * Initiate policy processing for this packet if ip_policy
1804 		 * is true.
1805 		 */
1806 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
1807 			ill_index = ill->ill_phyint->phyint_ifindex;
1808 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1809 			if (mp == NULL) {
1810 				if (mctl_present) {
1811 					freeb(first_mp);
1812 				}
1813 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1814 				return;
1815 			}
1816 		}
1817 	}
1818 	/* We want to do something with it. */
1819 	/* Check db_ref to make sure we can modify the packet. */
1820 	if (mp->b_datap->db_ref > 1) {
1821 		mblk_t	*first_mp1;
1822 
1823 		first_mp1 = ip_copymsg(first_mp);
1824 		freemsg(first_mp);
1825 		if (!first_mp1) {
1826 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1827 			return;
1828 		}
1829 		first_mp = first_mp1;
1830 		if (mctl_present) {
1831 			mp = first_mp->b_cont;
1832 			ASSERT(mp != NULL);
1833 		} else {
1834 			mp = first_mp;
1835 		}
1836 		ipha = (ipha_t *)mp->b_rptr;
1837 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1838 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1839 	}
1840 	switch (icmph->icmph_type) {
1841 	case ICMP_ADDRESS_MASK_REQUEST:
1842 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1843 		if (ipif == NULL) {
1844 			freemsg(first_mp);
1845 			return;
1846 		}
1847 		/*
1848 		 * outging interface must be IPv4
1849 		 */
1850 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1851 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1852 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1853 		ipif_refrele(ipif);
1854 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1855 		break;
1856 	case ICMP_ECHO_REQUEST:
1857 		icmph->icmph_type = ICMP_ECHO_REPLY;
1858 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1859 		break;
1860 	case ICMP_TIME_STAMP_REQUEST: {
1861 		uint32_t *tsp;
1862 
1863 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1864 		tsp = (uint32_t *)wptr;
1865 		tsp++;		/* Skip past 'originate time' */
1866 		/* Compute # of milliseconds since midnight */
1867 		gethrestime(&now);
1868 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1869 		    now.tv_nsec / (NANOSEC / MILLISEC);
1870 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1871 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1872 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1873 		break;
1874 	}
1875 	default:
1876 		ipha = (ipha_t *)&icmph[1];
1877 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1878 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1879 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1880 				freemsg(first_mp);
1881 				return;
1882 			}
1883 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1884 			ipha = (ipha_t *)&icmph[1];
1885 		}
1886 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1887 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1888 			freemsg(first_mp);
1889 			return;
1890 		}
1891 		hdr_length = IPH_HDR_LENGTH(ipha);
1892 		if (hdr_length < sizeof (ipha_t)) {
1893 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1894 			freemsg(first_mp);
1895 			return;
1896 		}
1897 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1898 			if (!pullupmsg(mp,
1899 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1900 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1901 				freemsg(first_mp);
1902 				return;
1903 			}
1904 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1905 			ipha = (ipha_t *)&icmph[1];
1906 		}
1907 		switch (icmph->icmph_type) {
1908 		case ICMP_REDIRECT:
1909 			/*
1910 			 * As there is no upper client to deliver, we don't
1911 			 * need the first_mp any more.
1912 			 */
1913 			if (mctl_present) {
1914 				freeb(first_mp);
1915 			}
1916 			icmp_redirect(ill, mp);
1917 			return;
1918 		case ICMP_DEST_UNREACHABLE:
1919 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1920 				if (!icmp_inbound_too_big(icmph, ipha, ill,
1921 				    zoneid, mp, iph_hdr_length, ipst)) {
1922 					freemsg(first_mp);
1923 					return;
1924 				}
1925 				/*
1926 				 * icmp_inbound_too_big() may alter mp.
1927 				 * Resynch ipha and icmph accordingly.
1928 				 */
1929 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1930 				ipha = (ipha_t *)&icmph[1];
1931 			}
1932 			/* FALLTHRU */
1933 		default :
1934 			/*
1935 			 * IPQoS notes: Since we have already done IPQoS
1936 			 * processing we don't want to do it again in
1937 			 * the fanout routines called by
1938 			 * icmp_inbound_error_fanout, hence the last
1939 			 * argument, ip_policy, is B_FALSE.
1940 			 */
1941 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
1942 			    ipha, iph_hdr_length, hdr_length, mctl_present,
1943 			    B_FALSE, recv_ill, zoneid);
1944 		}
1945 		return;
1946 	}
1947 	/* Send out an ICMP packet */
1948 	icmph->icmph_checksum = 0;
1949 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
1950 	if (broadcast || CLASSD(ipha->ipha_dst)) {
1951 		ipif_t	*ipif_chosen;
1952 		/*
1953 		 * Make it look like it was directed to us, so we don't look
1954 		 * like a fool with a broadcast or multicast source address.
1955 		 */
1956 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1957 		/*
1958 		 * Make sure that we haven't grabbed an interface that's DOWN.
1959 		 */
1960 		if (ipif != NULL) {
1961 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
1962 			    ipha->ipha_src, zoneid);
1963 			if (ipif_chosen != NULL) {
1964 				ipif_refrele(ipif);
1965 				ipif = ipif_chosen;
1966 			}
1967 		}
1968 		if (ipif == NULL) {
1969 			ip0dbg(("icmp_inbound: "
1970 			    "No source for broadcast/multicast:\n"
1971 			    "\tsrc 0x%x dst 0x%x ill %p "
1972 			    "ipif_lcl_addr 0x%x\n",
1973 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
1974 			    (void *)ill,
1975 			    ill->ill_ipif->ipif_lcl_addr));
1976 			freemsg(first_mp);
1977 			return;
1978 		}
1979 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1980 		ipha->ipha_dst = ipif->ipif_src_addr;
1981 		ipif_refrele(ipif);
1982 	}
1983 	/* Reset time to live. */
1984 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
1985 	{
1986 		/* Swap source and destination addresses */
1987 		ipaddr_t tmp;
1988 
1989 		tmp = ipha->ipha_src;
1990 		ipha->ipha_src = ipha->ipha_dst;
1991 		ipha->ipha_dst = tmp;
1992 	}
1993 	ipha->ipha_ident = 0;
1994 	if (!IS_SIMPLE_IPH(ipha))
1995 		icmp_options_update(ipha);
1996 
1997 	/*
1998 	 * ICMP echo replies should go out on the same interface
1999 	 * the request came on as probes used by in.mpathd for detecting
2000 	 * NIC failures are ECHO packets. We turn-off load spreading
2001 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
2002 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
2003 	 * function. This is in turn handled by ip_wput and ip_newroute
2004 	 * to make sure that the packet goes out on the interface it came
2005 	 * in on. If we don't turnoff load spreading, the packets might get
2006 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
2007 	 * to go out and in.mpathd would wrongly detect a failure or
2008 	 * mis-detect a NIC failure for link failure. As load spreading
2009 	 * can happen only if ill_group is not NULL, we do only for
2010 	 * that case and this does not affect the normal case.
2011 	 *
2012 	 * We turn off load spreading only on echo packets that came from
2013 	 * on-link hosts. If the interface route has been deleted, this will
2014 	 * not be enforced as we can't do much. For off-link hosts, as the
2015 	 * default routes in IPv4 does not typically have an ire_ipif
2016 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
2017 	 * Moreover, expecting a default route through this interface may
2018 	 * not be correct. We use ipha_dst because of the swap above.
2019 	 */
2020 	onlink = B_FALSE;
2021 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
2022 		/*
2023 		 * First, we need to make sure that it is not one of our
2024 		 * local addresses. If we set onlink when it is one of
2025 		 * our local addresses, we will end up creating IRE_CACHES
2026 		 * for one of our local addresses. Then, we will never
2027 		 * accept packets for them afterwards.
2028 		 */
2029 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2030 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2031 		if (src_ire == NULL) {
2032 			ipif = ipif_get_next_ipif(NULL, ill);
2033 			if (ipif == NULL) {
2034 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2035 				freemsg(mp);
2036 				return;
2037 			}
2038 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2039 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2040 			    NULL, MATCH_IRE_ILL | MATCH_IRE_TYPE, ipst);
2041 			ipif_refrele(ipif);
2042 			if (src_ire != NULL) {
2043 				onlink = B_TRUE;
2044 				ire_refrele(src_ire);
2045 			}
2046 		} else {
2047 			ire_refrele(src_ire);
2048 		}
2049 	}
2050 	if (!mctl_present) {
2051 		/*
2052 		 * This packet should go out the same way as it
2053 		 * came in i.e in clear. To make sure that global
2054 		 * policy will not be applied to this in ip_wput_ire,
2055 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2056 		 */
2057 		ASSERT(first_mp == mp);
2058 		first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2059 		if (first_mp == NULL) {
2060 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2061 			freemsg(mp);
2062 			return;
2063 		}
2064 		ii = (ipsec_in_t *)first_mp->b_rptr;
2065 
2066 		/* This is not a secure packet */
2067 		ii->ipsec_in_secure = B_FALSE;
2068 		if (onlink) {
2069 			ii->ipsec_in_attach_if = B_TRUE;
2070 			ii->ipsec_in_ill_index =
2071 			    ill->ill_phyint->phyint_ifindex;
2072 			ii->ipsec_in_rill_index =
2073 			    recv_ill->ill_phyint->phyint_ifindex;
2074 		}
2075 		first_mp->b_cont = mp;
2076 	} else if (onlink) {
2077 		ii = (ipsec_in_t *)first_mp->b_rptr;
2078 		ii->ipsec_in_attach_if = B_TRUE;
2079 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2080 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2081 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2082 	} else {
2083 		ii = (ipsec_in_t *)first_mp->b_rptr;
2084 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2085 	}
2086 	ii->ipsec_in_zoneid = zoneid;
2087 	ASSERT(zoneid != ALL_ZONES);
2088 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2089 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2090 		return;
2091 	}
2092 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2093 	put(WR(q), first_mp);
2094 }
2095 
2096 static ipaddr_t
2097 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2098 {
2099 	conn_t *connp;
2100 	connf_t *connfp;
2101 	ipaddr_t nexthop_addr = INADDR_ANY;
2102 	int hdr_length = IPH_HDR_LENGTH(ipha);
2103 	uint16_t *up;
2104 	uint32_t ports;
2105 	ip_stack_t *ipst = ill->ill_ipst;
2106 
2107 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2108 	switch (ipha->ipha_protocol) {
2109 		case IPPROTO_TCP:
2110 		{
2111 			tcph_t *tcph;
2112 
2113 			/* do a reverse lookup */
2114 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2115 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2116 			    TCPS_LISTEN, ipst);
2117 			break;
2118 		}
2119 		case IPPROTO_UDP:
2120 		{
2121 			uint32_t dstport, srcport;
2122 
2123 			((uint16_t *)&ports)[0] = up[1];
2124 			((uint16_t *)&ports)[1] = up[0];
2125 
2126 			/* Extract ports in net byte order */
2127 			dstport = htons(ntohl(ports) & 0xFFFF);
2128 			srcport = htons(ntohl(ports) >> 16);
2129 
2130 			connfp = &ipst->ips_ipcl_udp_fanout[
2131 			    IPCL_UDP_HASH(dstport, ipst)];
2132 			mutex_enter(&connfp->connf_lock);
2133 			connp = connfp->connf_head;
2134 
2135 			/* do a reverse lookup */
2136 			while ((connp != NULL) &&
2137 			    (!IPCL_UDP_MATCH(connp, dstport,
2138 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2139 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2140 				connp = connp->conn_next;
2141 			}
2142 			if (connp != NULL)
2143 				CONN_INC_REF(connp);
2144 			mutex_exit(&connfp->connf_lock);
2145 			break;
2146 		}
2147 		case IPPROTO_SCTP:
2148 		{
2149 			in6_addr_t map_src, map_dst;
2150 
2151 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2152 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2153 			((uint16_t *)&ports)[0] = up[1];
2154 			((uint16_t *)&ports)[1] = up[0];
2155 
2156 			connp = sctp_find_conn(&map_src, &map_dst, ports,
2157 			    zoneid, ipst->ips_netstack->netstack_sctp);
2158 			if (connp == NULL) {
2159 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2160 				    zoneid, ports, ipha, ipst);
2161 			} else {
2162 				CONN_INC_REF(connp);
2163 				SCTP_REFRELE(CONN2SCTP(connp));
2164 			}
2165 			break;
2166 		}
2167 		default:
2168 		{
2169 			ipha_t ripha;
2170 
2171 			ripha.ipha_src = ipha->ipha_dst;
2172 			ripha.ipha_dst = ipha->ipha_src;
2173 			ripha.ipha_protocol = ipha->ipha_protocol;
2174 
2175 			connfp = &ipst->ips_ipcl_proto_fanout[
2176 			    ipha->ipha_protocol];
2177 			mutex_enter(&connfp->connf_lock);
2178 			connp = connfp->connf_head;
2179 			for (connp = connfp->connf_head; connp != NULL;
2180 			    connp = connp->conn_next) {
2181 				if (IPCL_PROTO_MATCH(connp,
2182 				    ipha->ipha_protocol, &ripha, ill,
2183 				    0, zoneid)) {
2184 					CONN_INC_REF(connp);
2185 					break;
2186 				}
2187 			}
2188 			mutex_exit(&connfp->connf_lock);
2189 		}
2190 	}
2191 	if (connp != NULL) {
2192 		if (connp->conn_nexthop_set)
2193 			nexthop_addr = connp->conn_nexthop_v4;
2194 		CONN_DEC_REF(connp);
2195 	}
2196 	return (nexthop_addr);
2197 }
2198 
2199 /* Table from RFC 1191 */
2200 static int icmp_frag_size_table[] =
2201 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2202 
2203 /*
2204  * Process received ICMP Packet too big.
2205  * After updating any IRE it does the fanout to any matching transport streams.
2206  * Assumes the message has been pulled up till the IP header that caused
2207  * the error.
2208  *
2209  * Returns B_FALSE on failure and B_TRUE on success.
2210  */
2211 static boolean_t
2212 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2213     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length,
2214     ip_stack_t *ipst)
2215 {
2216 	ire_t	*ire, *first_ire;
2217 	int	mtu;
2218 	int	hdr_length;
2219 	ipaddr_t nexthop_addr;
2220 
2221 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2222 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2223 	ASSERT(ill != NULL);
2224 
2225 	hdr_length = IPH_HDR_LENGTH(ipha);
2226 
2227 	/* Drop if the original packet contained a source route */
2228 	if (ip_source_route_included(ipha)) {
2229 		return (B_FALSE);
2230 	}
2231 	/*
2232 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2233 	 * header.
2234 	 */
2235 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2236 	    mp->b_wptr) {
2237 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2238 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2239 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2240 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2241 			return (B_FALSE);
2242 		}
2243 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2244 		ipha = (ipha_t *)&icmph[1];
2245 	}
2246 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2247 	if (nexthop_addr != INADDR_ANY) {
2248 		/* nexthop set */
2249 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2250 		    nexthop_addr, 0, NULL, ALL_ZONES, MBLK_GETLABEL(mp),
2251 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW, ipst);
2252 	} else {
2253 		/* nexthop not set */
2254 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2255 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2256 	}
2257 
2258 	if (!first_ire) {
2259 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2260 		    ntohl(ipha->ipha_dst)));
2261 		return (B_FALSE);
2262 	}
2263 	/* Check for MTU discovery advice as described in RFC 1191 */
2264 	mtu = ntohs(icmph->icmph_du_mtu);
2265 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2266 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2267 	    ire = ire->ire_next) {
2268 		/*
2269 		 * Look for the connection to which this ICMP message is
2270 		 * directed. If it has the IP_NEXTHOP option set, then the
2271 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2272 		 * option. Else the search is limited to regular IREs.
2273 		 */
2274 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2275 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2276 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2277 		    (nexthop_addr != INADDR_ANY)))
2278 			continue;
2279 
2280 		mutex_enter(&ire->ire_lock);
2281 		if (icmph->icmph_du_zero == 0 && mtu > 68) {
2282 			/* Reduce the IRE max frag value as advised. */
2283 			ip1dbg(("Received mtu from router: %d (was %d)\n",
2284 			    mtu, ire->ire_max_frag));
2285 			ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2286 		} else {
2287 			uint32_t length;
2288 			int	i;
2289 
2290 			/*
2291 			 * Use the table from RFC 1191 to figure out
2292 			 * the next "plateau" based on the length in
2293 			 * the original IP packet.
2294 			 */
2295 			length = ntohs(ipha->ipha_length);
2296 			if (ire->ire_max_frag <= length &&
2297 			    ire->ire_max_frag >= length - hdr_length) {
2298 				/*
2299 				 * Handle broken BSD 4.2 systems that
2300 				 * return the wrong iph_length in ICMP
2301 				 * errors.
2302 				 */
2303 				ip1dbg(("Wrong mtu: sent %d, ire %d\n",
2304 				    length, ire->ire_max_frag));
2305 				length -= hdr_length;
2306 			}
2307 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2308 				if (length > icmp_frag_size_table[i])
2309 					break;
2310 			}
2311 			if (i == A_CNT(icmp_frag_size_table)) {
2312 				/* Smaller than 68! */
2313 				ip1dbg(("Too big for packet size %d\n",
2314 				    length));
2315 				ire->ire_max_frag = MIN(ire->ire_max_frag, 576);
2316 				ire->ire_frag_flag = 0;
2317 			} else {
2318 				mtu = icmp_frag_size_table[i];
2319 				ip1dbg(("Calculated mtu %d, packet size %d, "
2320 				    "before %d", mtu, length,
2321 				    ire->ire_max_frag));
2322 				ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2323 				ip1dbg((", after %d\n", ire->ire_max_frag));
2324 			}
2325 			/* Record the new max frag size for the ULP. */
2326 			icmph->icmph_du_zero = 0;
2327 			icmph->icmph_du_mtu =
2328 			    htons((uint16_t)ire->ire_max_frag);
2329 		}
2330 		mutex_exit(&ire->ire_lock);
2331 	}
2332 	rw_exit(&first_ire->ire_bucket->irb_lock);
2333 	ire_refrele(first_ire);
2334 	return (B_TRUE);
2335 }
2336 
2337 /*
2338  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2339  * calls this function.
2340  */
2341 static mblk_t *
2342 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2343 {
2344 	ipha_t *ipha;
2345 	icmph_t *icmph;
2346 	ipha_t *in_ipha;
2347 	int length;
2348 
2349 	ASSERT(mp->b_datap->db_type == M_DATA);
2350 
2351 	/*
2352 	 * For Self-encapsulated packets, we added an extra IP header
2353 	 * without the options. Inner IP header is the one from which
2354 	 * the outer IP header was formed. Thus, we need to remove the
2355 	 * outer IP header. To do this, we pullup the whole message
2356 	 * and overlay whatever follows the outer IP header over the
2357 	 * outer IP header.
2358 	 */
2359 
2360 	if (!pullupmsg(mp, -1))
2361 		return (NULL);
2362 
2363 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2364 	ipha = (ipha_t *)&icmph[1];
2365 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2366 
2367 	/*
2368 	 * The length that we want to overlay is following the inner
2369 	 * IP header. Subtracting the IP header + icmp header + outer
2370 	 * IP header's length should give us the length that we want to
2371 	 * overlay.
2372 	 */
2373 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2374 	    hdr_length;
2375 	/*
2376 	 * Overlay whatever follows the inner header over the
2377 	 * outer header.
2378 	 */
2379 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2380 
2381 	/* Set the wptr to account for the outer header */
2382 	mp->b_wptr -= hdr_length;
2383 	return (mp);
2384 }
2385 
2386 /*
2387  * Try to pass the ICMP message upstream in case the ULP cares.
2388  *
2389  * If the packet that caused the ICMP error is secure, we send
2390  * it to AH/ESP to make sure that the attached packet has a
2391  * valid association. ipha in the code below points to the
2392  * IP header of the packet that caused the error.
2393  *
2394  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2395  * in the context of IPsec. Normally we tell the upper layer
2396  * whenever we send the ire (including ip_bind), the IPsec header
2397  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2398  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2399  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2400  * same thing. As TCP has the IPsec options size that needs to be
2401  * adjusted, we just pass the MTU unchanged.
2402  *
2403  * IFN could have been generated locally or by some router.
2404  *
2405  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2406  *	    This happens because IP adjusted its value of MTU on an
2407  *	    earlier IFN message and could not tell the upper layer,
2408  *	    the new adjusted value of MTU e.g. Packet was encrypted
2409  *	    or there was not enough information to fanout to upper
2410  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2411  *	    generates the IFN, where IPsec processing has *not* been
2412  *	    done.
2413  *
2414  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2415  *	    could have generated this. This happens because ire_max_frag
2416  *	    value in IP was set to a new value, while the IPsec processing
2417  *	    was being done and after we made the fragmentation check in
2418  *	    ip_wput_ire. Thus on return from IPsec processing,
2419  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2420  *	    and generates the IFN. As IPsec processing is over, we fanout
2421  *	    to AH/ESP to remove the header.
2422  *
2423  *	    In both these cases, ipsec_in_loopback will be set indicating
2424  *	    that IFN was generated locally.
2425  *
2426  * ROUTER : IFN could be secure or non-secure.
2427  *
2428  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2429  *	      packet in error has AH/ESP headers to validate the AH/ESP
2430  *	      headers. AH/ESP will verify whether there is a valid SA or
2431  *	      not and send it back. We will fanout again if we have more
2432  *	      data in the packet.
2433  *
2434  *	      If the packet in error does not have AH/ESP, we handle it
2435  *	      like any other case.
2436  *
2437  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2438  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2439  *	      for validation. AH/ESP will verify whether there is a
2440  *	      valid SA or not and send it back. We will fanout again if
2441  *	      we have more data in the packet.
2442  *
2443  *	      If the packet in error does not have AH/ESP, we handle it
2444  *	      like any other case.
2445  */
2446 static void
2447 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2448     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2449     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2450     zoneid_t zoneid)
2451 {
2452 	uint16_t *up;	/* Pointer to ports in ULP header */
2453 	uint32_t ports;	/* reversed ports for fanout */
2454 	ipha_t ripha;	/* With reversed addresses */
2455 	mblk_t *first_mp;
2456 	ipsec_in_t *ii;
2457 	tcph_t	*tcph;
2458 	conn_t	*connp;
2459 	ip_stack_t *ipst;
2460 
2461 	ASSERT(ill != NULL);
2462 
2463 	ASSERT(recv_ill != NULL);
2464 	ipst = recv_ill->ill_ipst;
2465 
2466 	first_mp = mp;
2467 	if (mctl_present) {
2468 		mp = first_mp->b_cont;
2469 		ASSERT(mp != NULL);
2470 
2471 		ii = (ipsec_in_t *)first_mp->b_rptr;
2472 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2473 	} else {
2474 		ii = NULL;
2475 	}
2476 
2477 	switch (ipha->ipha_protocol) {
2478 	case IPPROTO_UDP:
2479 		/*
2480 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2481 		 * transport header.
2482 		 */
2483 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2484 		    mp->b_wptr) {
2485 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2486 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2487 				goto discard_pkt;
2488 			}
2489 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2490 			ipha = (ipha_t *)&icmph[1];
2491 		}
2492 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2493 
2494 		/*
2495 		 * Attempt to find a client stream based on port.
2496 		 * Note that we do a reverse lookup since the header is
2497 		 * in the form we sent it out.
2498 		 * The ripha header is only used for the IP_UDP_MATCH and we
2499 		 * only set the src and dst addresses and protocol.
2500 		 */
2501 		ripha.ipha_src = ipha->ipha_dst;
2502 		ripha.ipha_dst = ipha->ipha_src;
2503 		ripha.ipha_protocol = ipha->ipha_protocol;
2504 		((uint16_t *)&ports)[0] = up[1];
2505 		((uint16_t *)&ports)[1] = up[0];
2506 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2507 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2508 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2509 		    icmph->icmph_type, icmph->icmph_code));
2510 
2511 		/* Have to change db_type after any pullupmsg */
2512 		DB_TYPE(mp) = M_CTL;
2513 
2514 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2515 		    mctl_present, ip_policy, recv_ill, zoneid);
2516 		return;
2517 
2518 	case IPPROTO_TCP:
2519 		/*
2520 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2521 		 * transport header.
2522 		 */
2523 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2524 		    mp->b_wptr) {
2525 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2526 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2527 				goto discard_pkt;
2528 			}
2529 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2530 			ipha = (ipha_t *)&icmph[1];
2531 		}
2532 		/*
2533 		 * Find a TCP client stream for this packet.
2534 		 * Note that we do a reverse lookup since the header is
2535 		 * in the form we sent it out.
2536 		 */
2537 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2538 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN,
2539 		    ipst);
2540 		if (connp == NULL)
2541 			goto discard_pkt;
2542 
2543 		/* Have to change db_type after any pullupmsg */
2544 		DB_TYPE(mp) = M_CTL;
2545 		squeue_fill(connp->conn_sqp, first_mp, tcp_input,
2546 		    connp, SQTAG_TCP_INPUT_ICMP_ERR);
2547 		return;
2548 
2549 	case IPPROTO_SCTP:
2550 		/*
2551 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2552 		 * transport header.
2553 		 */
2554 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2555 		    mp->b_wptr) {
2556 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2557 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2558 				goto discard_pkt;
2559 			}
2560 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2561 			ipha = (ipha_t *)&icmph[1];
2562 		}
2563 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2564 		/*
2565 		 * Find a SCTP client stream for this packet.
2566 		 * Note that we do a reverse lookup since the header is
2567 		 * in the form we sent it out.
2568 		 * The ripha header is only used for the matching and we
2569 		 * only set the src and dst addresses, protocol, and version.
2570 		 */
2571 		ripha.ipha_src = ipha->ipha_dst;
2572 		ripha.ipha_dst = ipha->ipha_src;
2573 		ripha.ipha_protocol = ipha->ipha_protocol;
2574 		ripha.ipha_version_and_hdr_length =
2575 		    ipha->ipha_version_and_hdr_length;
2576 		((uint16_t *)&ports)[0] = up[1];
2577 		((uint16_t *)&ports)[1] = up[0];
2578 
2579 		/* Have to change db_type after any pullupmsg */
2580 		DB_TYPE(mp) = M_CTL;
2581 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2582 		    mctl_present, ip_policy, zoneid);
2583 		return;
2584 
2585 	case IPPROTO_ESP:
2586 	case IPPROTO_AH: {
2587 		int ipsec_rc;
2588 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
2589 
2590 		/*
2591 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2592 		 * We will re-use the IPSEC_IN if it is already present as
2593 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2594 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2595 		 * one and attach it in the front.
2596 		 */
2597 		if (ii != NULL) {
2598 			/*
2599 			 * ip_fanout_proto_again converts the ICMP errors
2600 			 * that come back from AH/ESP to M_DATA so that
2601 			 * if it is non-AH/ESP and we do a pullupmsg in
2602 			 * this function, it would work. Convert it back
2603 			 * to M_CTL before we send up as this is a ICMP
2604 			 * error. This could have been generated locally or
2605 			 * by some router. Validate the inner IPsec
2606 			 * headers.
2607 			 *
2608 			 * NOTE : ill_index is used by ip_fanout_proto_again
2609 			 * to locate the ill.
2610 			 */
2611 			ASSERT(ill != NULL);
2612 			ii->ipsec_in_ill_index =
2613 			    ill->ill_phyint->phyint_ifindex;
2614 			ii->ipsec_in_rill_index =
2615 			    recv_ill->ill_phyint->phyint_ifindex;
2616 			DB_TYPE(first_mp->b_cont) = M_CTL;
2617 		} else {
2618 			/*
2619 			 * IPSEC_IN is not present. We attach a ipsec_in
2620 			 * message and send up to IPsec for validating
2621 			 * and removing the IPsec headers. Clear
2622 			 * ipsec_in_secure so that when we return
2623 			 * from IPsec, we don't mistakenly think that this
2624 			 * is a secure packet came from the network.
2625 			 *
2626 			 * NOTE : ill_index is used by ip_fanout_proto_again
2627 			 * to locate the ill.
2628 			 */
2629 			ASSERT(first_mp == mp);
2630 			first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2631 			if (first_mp == NULL) {
2632 				freemsg(mp);
2633 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2634 				return;
2635 			}
2636 			ii = (ipsec_in_t *)first_mp->b_rptr;
2637 
2638 			/* This is not a secure packet */
2639 			ii->ipsec_in_secure = B_FALSE;
2640 			first_mp->b_cont = mp;
2641 			DB_TYPE(mp) = M_CTL;
2642 			ASSERT(ill != NULL);
2643 			ii->ipsec_in_ill_index =
2644 			    ill->ill_phyint->phyint_ifindex;
2645 			ii->ipsec_in_rill_index =
2646 			    recv_ill->ill_phyint->phyint_ifindex;
2647 		}
2648 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2649 
2650 		if (!ipsec_loaded(ipss)) {
2651 			ip_proto_not_sup(q, first_mp, 0, zoneid, ipst);
2652 			return;
2653 		}
2654 
2655 		if (ipha->ipha_protocol == IPPROTO_ESP)
2656 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2657 		else
2658 			ipsec_rc = ipsecah_icmp_error(first_mp);
2659 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2660 			return;
2661 
2662 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2663 		return;
2664 	}
2665 	default:
2666 		/*
2667 		 * The ripha header is only used for the lookup and we
2668 		 * only set the src and dst addresses and protocol.
2669 		 */
2670 		ripha.ipha_src = ipha->ipha_dst;
2671 		ripha.ipha_dst = ipha->ipha_src;
2672 		ripha.ipha_protocol = ipha->ipha_protocol;
2673 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2674 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2675 		    ntohl(ipha->ipha_dst),
2676 		    icmph->icmph_type, icmph->icmph_code));
2677 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2678 			ipha_t *in_ipha;
2679 
2680 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2681 			    mp->b_wptr) {
2682 				if (!pullupmsg(mp, (uchar_t *)ipha +
2683 				    hdr_length + sizeof (ipha_t) -
2684 				    mp->b_rptr)) {
2685 					goto discard_pkt;
2686 				}
2687 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2688 				ipha = (ipha_t *)&icmph[1];
2689 			}
2690 			/*
2691 			 * Caller has verified that length has to be
2692 			 * at least the size of IP header.
2693 			 */
2694 			ASSERT(hdr_length >= sizeof (ipha_t));
2695 			/*
2696 			 * Check the sanity of the inner IP header like
2697 			 * we did for the outer header.
2698 			 */
2699 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2700 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2701 				goto discard_pkt;
2702 			}
2703 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2704 				goto discard_pkt;
2705 			}
2706 			/* Check for Self-encapsulated tunnels */
2707 			if (in_ipha->ipha_src == ipha->ipha_src &&
2708 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2709 
2710 				mp = icmp_inbound_self_encap_error(mp,
2711 				    iph_hdr_length, hdr_length);
2712 				if (mp == NULL)
2713 					goto discard_pkt;
2714 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2715 				ipha = (ipha_t *)&icmph[1];
2716 				hdr_length = IPH_HDR_LENGTH(ipha);
2717 				/*
2718 				 * The packet in error is self-encapsualted.
2719 				 * And we are finding it further encapsulated
2720 				 * which we could not have possibly generated.
2721 				 */
2722 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2723 					goto discard_pkt;
2724 				}
2725 				icmp_inbound_error_fanout(q, ill, first_mp,
2726 				    icmph, ipha, iph_hdr_length, hdr_length,
2727 				    mctl_present, ip_policy, recv_ill, zoneid);
2728 				return;
2729 			}
2730 		}
2731 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2732 		    ipha->ipha_protocol == IPPROTO_IPV6) &&
2733 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2734 		    ii != NULL &&
2735 		    ii->ipsec_in_loopback &&
2736 		    ii->ipsec_in_secure) {
2737 			/*
2738 			 * For IP tunnels that get a looped-back
2739 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2740 			 * reported new MTU to take into account the IPsec
2741 			 * headers protecting this configured tunnel.
2742 			 *
2743 			 * This allows the tunnel module (tun.c) to blindly
2744 			 * accept the MTU reported in an ICMP "too big"
2745 			 * message.
2746 			 *
2747 			 * Non-looped back ICMP messages will just be
2748 			 * handled by the security protocols (if needed),
2749 			 * and the first subsequent packet will hit this
2750 			 * path.
2751 			 */
2752 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2753 			    ipsec_in_extra_length(first_mp));
2754 		}
2755 		/* Have to change db_type after any pullupmsg */
2756 		DB_TYPE(mp) = M_CTL;
2757 
2758 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2759 		    ip_policy, recv_ill, zoneid);
2760 		return;
2761 	}
2762 	/* NOTREACHED */
2763 discard_pkt:
2764 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2765 drop_pkt:;
2766 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2767 	freemsg(first_mp);
2768 }
2769 
2770 /*
2771  * Common IP options parser.
2772  *
2773  * Setup routine: fill in *optp with options-parsing state, then
2774  * tail-call ipoptp_next to return the first option.
2775  */
2776 uint8_t
2777 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2778 {
2779 	uint32_t totallen; /* total length of all options */
2780 
2781 	totallen = ipha->ipha_version_and_hdr_length -
2782 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2783 	totallen <<= 2;
2784 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2785 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2786 	optp->ipoptp_flags = 0;
2787 	return (ipoptp_next(optp));
2788 }
2789 
2790 /*
2791  * Common IP options parser: extract next option.
2792  */
2793 uint8_t
2794 ipoptp_next(ipoptp_t *optp)
2795 {
2796 	uint8_t *end = optp->ipoptp_end;
2797 	uint8_t *cur = optp->ipoptp_next;
2798 	uint8_t opt, len, pointer;
2799 
2800 	/*
2801 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2802 	 * has been corrupted.
2803 	 */
2804 	ASSERT(cur <= end);
2805 
2806 	if (cur == end)
2807 		return (IPOPT_EOL);
2808 
2809 	opt = cur[IPOPT_OPTVAL];
2810 
2811 	/*
2812 	 * Skip any NOP options.
2813 	 */
2814 	while (opt == IPOPT_NOP) {
2815 		cur++;
2816 		if (cur == end)
2817 			return (IPOPT_EOL);
2818 		opt = cur[IPOPT_OPTVAL];
2819 	}
2820 
2821 	if (opt == IPOPT_EOL)
2822 		return (IPOPT_EOL);
2823 
2824 	/*
2825 	 * Option requiring a length.
2826 	 */
2827 	if ((cur + 1) >= end) {
2828 		optp->ipoptp_flags |= IPOPTP_ERROR;
2829 		return (IPOPT_EOL);
2830 	}
2831 	len = cur[IPOPT_OLEN];
2832 	if (len < 2) {
2833 		optp->ipoptp_flags |= IPOPTP_ERROR;
2834 		return (IPOPT_EOL);
2835 	}
2836 	optp->ipoptp_cur = cur;
2837 	optp->ipoptp_len = len;
2838 	optp->ipoptp_next = cur + len;
2839 	if (cur + len > end) {
2840 		optp->ipoptp_flags |= IPOPTP_ERROR;
2841 		return (IPOPT_EOL);
2842 	}
2843 
2844 	/*
2845 	 * For the options which require a pointer field, make sure
2846 	 * its there, and make sure it points to either something
2847 	 * inside this option, or the end of the option.
2848 	 */
2849 	switch (opt) {
2850 	case IPOPT_RR:
2851 	case IPOPT_TS:
2852 	case IPOPT_LSRR:
2853 	case IPOPT_SSRR:
2854 		if (len <= IPOPT_OFFSET) {
2855 			optp->ipoptp_flags |= IPOPTP_ERROR;
2856 			return (opt);
2857 		}
2858 		pointer = cur[IPOPT_OFFSET];
2859 		if (pointer - 1 > len) {
2860 			optp->ipoptp_flags |= IPOPTP_ERROR;
2861 			return (opt);
2862 		}
2863 		break;
2864 	}
2865 
2866 	/*
2867 	 * Sanity check the pointer field based on the type of the
2868 	 * option.
2869 	 */
2870 	switch (opt) {
2871 	case IPOPT_RR:
2872 	case IPOPT_SSRR:
2873 	case IPOPT_LSRR:
2874 		if (pointer < IPOPT_MINOFF_SR)
2875 			optp->ipoptp_flags |= IPOPTP_ERROR;
2876 		break;
2877 	case IPOPT_TS:
2878 		if (pointer < IPOPT_MINOFF_IT)
2879 			optp->ipoptp_flags |= IPOPTP_ERROR;
2880 		/*
2881 		 * Note that the Internet Timestamp option also
2882 		 * contains two four bit fields (the Overflow field,
2883 		 * and the Flag field), which follow the pointer
2884 		 * field.  We don't need to check that these fields
2885 		 * fall within the length of the option because this
2886 		 * was implicitely done above.  We've checked that the
2887 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2888 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2889 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2890 		 */
2891 		ASSERT(len > IPOPT_POS_OV_FLG);
2892 		break;
2893 	}
2894 
2895 	return (opt);
2896 }
2897 
2898 /*
2899  * Use the outgoing IP header to create an IP_OPTIONS option the way
2900  * it was passed down from the application.
2901  */
2902 int
2903 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2904 {
2905 	ipoptp_t	opts;
2906 	const uchar_t	*opt;
2907 	uint8_t		optval;
2908 	uint8_t		optlen;
2909 	uint32_t	len = 0;
2910 	uchar_t	*buf1 = buf;
2911 
2912 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2913 	len += IP_ADDR_LEN;
2914 	bzero(buf1, IP_ADDR_LEN);
2915 
2916 	/*
2917 	 * OK to cast away const here, as we don't store through the returned
2918 	 * opts.ipoptp_cur pointer.
2919 	 */
2920 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
2921 	    optval != IPOPT_EOL;
2922 	    optval = ipoptp_next(&opts)) {
2923 		int	off;
2924 
2925 		opt = opts.ipoptp_cur;
2926 		optlen = opts.ipoptp_len;
2927 		switch (optval) {
2928 		case IPOPT_SSRR:
2929 		case IPOPT_LSRR:
2930 
2931 			/*
2932 			 * Insert ipha_dst as the first entry in the source
2933 			 * route and move down the entries on step.
2934 			 * The last entry gets placed at buf1.
2935 			 */
2936 			buf[IPOPT_OPTVAL] = optval;
2937 			buf[IPOPT_OLEN] = optlen;
2938 			buf[IPOPT_OFFSET] = optlen;
2939 
2940 			off = optlen - IP_ADDR_LEN;
2941 			if (off < 0) {
2942 				/* No entries in source route */
2943 				break;
2944 			}
2945 			/* Last entry in source route */
2946 			bcopy(opt + off, buf1, IP_ADDR_LEN);
2947 			off -= IP_ADDR_LEN;
2948 
2949 			while (off > 0) {
2950 				bcopy(opt + off,
2951 				    buf + off + IP_ADDR_LEN,
2952 				    IP_ADDR_LEN);
2953 				off -= IP_ADDR_LEN;
2954 			}
2955 			/* ipha_dst into first slot */
2956 			bcopy(&ipha->ipha_dst,
2957 			    buf + off + IP_ADDR_LEN,
2958 			    IP_ADDR_LEN);
2959 			buf += optlen;
2960 			len += optlen;
2961 			break;
2962 
2963 		case IPOPT_COMSEC:
2964 		case IPOPT_SECURITY:
2965 			/* if passing up a label is not ok, then remove */
2966 			if (is_system_labeled())
2967 				break;
2968 			/* FALLTHROUGH */
2969 		default:
2970 			bcopy(opt, buf, optlen);
2971 			buf += optlen;
2972 			len += optlen;
2973 			break;
2974 		}
2975 	}
2976 done:
2977 	/* Pad the resulting options */
2978 	while (len & 0x3) {
2979 		*buf++ = IPOPT_EOL;
2980 		len++;
2981 	}
2982 	return (len);
2983 }
2984 
2985 /*
2986  * Update any record route or timestamp options to include this host.
2987  * Reverse any source route option.
2988  * This routine assumes that the options are well formed i.e. that they
2989  * have already been checked.
2990  */
2991 static void
2992 icmp_options_update(ipha_t *ipha)
2993 {
2994 	ipoptp_t	opts;
2995 	uchar_t		*opt;
2996 	uint8_t		optval;
2997 	ipaddr_t	src;		/* Our local address */
2998 	ipaddr_t	dst;
2999 
3000 	ip2dbg(("icmp_options_update\n"));
3001 	src = ipha->ipha_src;
3002 	dst = ipha->ipha_dst;
3003 
3004 	for (optval = ipoptp_first(&opts, ipha);
3005 	    optval != IPOPT_EOL;
3006 	    optval = ipoptp_next(&opts)) {
3007 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
3008 		opt = opts.ipoptp_cur;
3009 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
3010 		    optval, opts.ipoptp_len));
3011 		switch (optval) {
3012 			int off1, off2;
3013 		case IPOPT_SSRR:
3014 		case IPOPT_LSRR:
3015 			/*
3016 			 * Reverse the source route.  The first entry
3017 			 * should be the next to last one in the current
3018 			 * source route (the last entry is our address).
3019 			 * The last entry should be the final destination.
3020 			 */
3021 			off1 = IPOPT_MINOFF_SR - 1;
3022 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
3023 			if (off2 < 0) {
3024 				/* No entries in source route */
3025 				ip1dbg((
3026 				    "icmp_options_update: bad src route\n"));
3027 				break;
3028 			}
3029 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3030 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3031 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3032 			off2 -= IP_ADDR_LEN;
3033 
3034 			while (off1 < off2) {
3035 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3036 				bcopy((char *)opt + off2, (char *)opt + off1,
3037 				    IP_ADDR_LEN);
3038 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3039 				off1 += IP_ADDR_LEN;
3040 				off2 -= IP_ADDR_LEN;
3041 			}
3042 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3043 			break;
3044 		}
3045 	}
3046 }
3047 
3048 /*
3049  * Process received ICMP Redirect messages.
3050  */
3051 static void
3052 icmp_redirect(ill_t *ill, mblk_t *mp)
3053 {
3054 	ipha_t	*ipha;
3055 	int	iph_hdr_length;
3056 	icmph_t	*icmph;
3057 	ipha_t	*ipha_err;
3058 	ire_t	*ire;
3059 	ire_t	*prev_ire;
3060 	ire_t	*save_ire;
3061 	ipaddr_t  src, dst, gateway;
3062 	iulp_t	ulp_info = { 0 };
3063 	int	error;
3064 	ip_stack_t *ipst;
3065 
3066 	ASSERT(ill != NULL);
3067 	ipst = ill->ill_ipst;
3068 
3069 	ipha = (ipha_t *)mp->b_rptr;
3070 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3071 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3072 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3073 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3074 		freemsg(mp);
3075 		return;
3076 	}
3077 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3078 	ipha_err = (ipha_t *)&icmph[1];
3079 	src = ipha->ipha_src;
3080 	dst = ipha_err->ipha_dst;
3081 	gateway = icmph->icmph_rd_gateway;
3082 	/* Make sure the new gateway is reachable somehow. */
3083 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3084 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3085 	/*
3086 	 * Make sure we had a route for the dest in question and that
3087 	 * that route was pointing to the old gateway (the source of the
3088 	 * redirect packet.)
3089 	 */
3090 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3091 	    NULL, MATCH_IRE_GW, ipst);
3092 	/*
3093 	 * Check that
3094 	 *	the redirect was not from ourselves
3095 	 *	the new gateway and the old gateway are directly reachable
3096 	 */
3097 	if (!prev_ire ||
3098 	    !ire ||
3099 	    ire->ire_type == IRE_LOCAL) {
3100 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3101 		freemsg(mp);
3102 		if (ire != NULL)
3103 			ire_refrele(ire);
3104 		if (prev_ire != NULL)
3105 			ire_refrele(prev_ire);
3106 		return;
3107 	}
3108 
3109 	/*
3110 	 * Should we use the old ULP info to create the new gateway?  From
3111 	 * a user's perspective, we should inherit the info so that it
3112 	 * is a "smooth" transition.  If we do not do that, then new
3113 	 * connections going thru the new gateway will have no route metrics,
3114 	 * which is counter-intuitive to user.  From a network point of
3115 	 * view, this may or may not make sense even though the new gateway
3116 	 * is still directly connected to us so the route metrics should not
3117 	 * change much.
3118 	 *
3119 	 * But if the old ire_uinfo is not initialized, we do another
3120 	 * recursive lookup on the dest using the new gateway.  There may
3121 	 * be a route to that.  If so, use it to initialize the redirect
3122 	 * route.
3123 	 */
3124 	if (prev_ire->ire_uinfo.iulp_set) {
3125 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3126 	} else {
3127 		ire_t *tmp_ire;
3128 		ire_t *sire;
3129 
3130 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3131 		    ALL_ZONES, 0, NULL,
3132 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT),
3133 		    ipst);
3134 		if (sire != NULL) {
3135 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3136 			/*
3137 			 * If sire != NULL, ire_ftable_lookup() should not
3138 			 * return a NULL value.
3139 			 */
3140 			ASSERT(tmp_ire != NULL);
3141 			ire_refrele(tmp_ire);
3142 			ire_refrele(sire);
3143 		} else if (tmp_ire != NULL) {
3144 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3145 			    sizeof (iulp_t));
3146 			ire_refrele(tmp_ire);
3147 		}
3148 	}
3149 	if (prev_ire->ire_type == IRE_CACHE)
3150 		ire_delete(prev_ire);
3151 	ire_refrele(prev_ire);
3152 	/*
3153 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3154 	 * require TOS routing
3155 	 */
3156 	switch (icmph->icmph_code) {
3157 	case 0:
3158 	case 1:
3159 		/* TODO: TOS specificity for cases 2 and 3 */
3160 	case 2:
3161 	case 3:
3162 		break;
3163 	default:
3164 		freemsg(mp);
3165 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3166 		ire_refrele(ire);
3167 		return;
3168 	}
3169 	/*
3170 	 * Create a Route Association.  This will allow us to remember that
3171 	 * someone we believe told us to use the particular gateway.
3172 	 */
3173 	save_ire = ire;
3174 	ire = ire_create(
3175 	    (uchar_t *)&dst,			/* dest addr */
3176 	    (uchar_t *)&ip_g_all_ones,		/* mask */
3177 	    (uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3178 	    (uchar_t *)&gateway,		/* gateway addr */
3179 	    &save_ire->ire_max_frag,		/* max frag */
3180 	    NULL,				/* no src nce */
3181 	    NULL,				/* no rfq */
3182 	    NULL,				/* no stq */
3183 	    IRE_HOST,
3184 	    NULL,				/* ipif */
3185 	    0,					/* cmask */
3186 	    0,					/* phandle */
3187 	    0,					/* ihandle */
3188 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3189 	    &ulp_info,
3190 	    NULL,				/* tsol_gc_t */
3191 	    NULL,				/* gcgrp */
3192 	    ipst);
3193 
3194 	if (ire == NULL) {
3195 		freemsg(mp);
3196 		ire_refrele(save_ire);
3197 		return;
3198 	}
3199 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3200 	ire_refrele(save_ire);
3201 	atomic_inc_32(&ipst->ips_ip_redirect_cnt);
3202 
3203 	if (error == 0) {
3204 		ire_refrele(ire);		/* Held in ire_add_v4 */
3205 		/* tell routing sockets that we received a redirect */
3206 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3207 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3208 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
3209 	}
3210 
3211 	/*
3212 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3213 	 * This together with the added IRE has the effect of
3214 	 * modifying an existing redirect.
3215 	 */
3216 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3217 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), ipst);
3218 	if (prev_ire != NULL) {
3219 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3220 			ire_delete(prev_ire);
3221 		ire_refrele(prev_ire);
3222 	}
3223 
3224 	freemsg(mp);
3225 }
3226 
3227 /*
3228  * Generate an ICMP parameter problem message.
3229  */
3230 static void
3231 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid,
3232 	ip_stack_t *ipst)
3233 {
3234 	icmph_t	icmph;
3235 	boolean_t mctl_present;
3236 	mblk_t *first_mp;
3237 
3238 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3239 
3240 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3241 		if (mctl_present)
3242 			freeb(first_mp);
3243 		return;
3244 	}
3245 
3246 	bzero(&icmph, sizeof (icmph_t));
3247 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3248 	icmph.icmph_pp_ptr = ptr;
3249 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
3250 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3251 	    ipst);
3252 }
3253 
3254 /*
3255  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3256  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3257  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3258  * an icmp error packet can be sent.
3259  * Assigns an appropriate source address to the packet. If ipha_dst is
3260  * one of our addresses use it for source. Otherwise pick a source based
3261  * on a route lookup back to ipha_src.
3262  * Note that ipha_src must be set here since the
3263  * packet is likely to arrive on an ill queue in ip_wput() which will
3264  * not set a source address.
3265  */
3266 static void
3267 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3268     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
3269 {
3270 	ipaddr_t dst;
3271 	icmph_t	*icmph;
3272 	ipha_t	*ipha;
3273 	uint_t	len_needed;
3274 	size_t	msg_len;
3275 	mblk_t	*mp1;
3276 	ipaddr_t src;
3277 	ire_t	*ire;
3278 	mblk_t *ipsec_mp;
3279 	ipsec_out_t	*io = NULL;
3280 
3281 	if (mctl_present) {
3282 		/*
3283 		 * If it is :
3284 		 *
3285 		 * 1) a IPSEC_OUT, then this is caused by outbound
3286 		 *    datagram originating on this host. IPsec processing
3287 		 *    may or may not have been done. Refer to comments above
3288 		 *    icmp_inbound_error_fanout for details.
3289 		 *
3290 		 * 2) a IPSEC_IN if we are generating a icmp_message
3291 		 *    for an incoming datagram destined for us i.e called
3292 		 *    from ip_fanout_send_icmp.
3293 		 */
3294 		ipsec_info_t *in;
3295 		ipsec_mp = mp;
3296 		mp = ipsec_mp->b_cont;
3297 
3298 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3299 		ipha = (ipha_t *)mp->b_rptr;
3300 
3301 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3302 		    in->ipsec_info_type == IPSEC_IN);
3303 
3304 		if (in->ipsec_info_type == IPSEC_IN) {
3305 			/*
3306 			 * Convert the IPSEC_IN to IPSEC_OUT.
3307 			 */
3308 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3309 				BUMP_MIB(&ipst->ips_ip_mib,
3310 				    ipIfStatsOutDiscards);
3311 				return;
3312 			}
3313 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3314 		} else {
3315 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3316 			io = (ipsec_out_t *)in;
3317 			/*
3318 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3319 			 * ire lookup.
3320 			 */
3321 			io->ipsec_out_proc_begin = B_FALSE;
3322 		}
3323 		ASSERT(zoneid == io->ipsec_out_zoneid);
3324 		ASSERT(zoneid != ALL_ZONES);
3325 	} else {
3326 		/*
3327 		 * This is in clear. The icmp message we are building
3328 		 * here should go out in clear.
3329 		 *
3330 		 * Pardon the convolution of it all, but it's easier to
3331 		 * allocate a "use cleartext" IPSEC_IN message and convert
3332 		 * it than it is to allocate a new one.
3333 		 */
3334 		ipsec_in_t *ii;
3335 		ASSERT(DB_TYPE(mp) == M_DATA);
3336 		ipsec_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
3337 		if (ipsec_mp == NULL) {
3338 			freemsg(mp);
3339 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3340 			return;
3341 		}
3342 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3343 
3344 		/* This is not a secure packet */
3345 		ii->ipsec_in_secure = B_FALSE;
3346 		/*
3347 		 * For trusted extensions using a shared IP address we can
3348 		 * send using any zoneid.
3349 		 */
3350 		if (zoneid == ALL_ZONES)
3351 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3352 		else
3353 			ii->ipsec_in_zoneid = zoneid;
3354 		ipsec_mp->b_cont = mp;
3355 		ipha = (ipha_t *)mp->b_rptr;
3356 		/*
3357 		 * Convert the IPSEC_IN to IPSEC_OUT.
3358 		 */
3359 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3360 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3361 			return;
3362 		}
3363 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3364 	}
3365 
3366 	/* Remember our eventual destination */
3367 	dst = ipha->ipha_src;
3368 
3369 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3370 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE, ipst);
3371 	if (ire != NULL &&
3372 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3373 		src = ipha->ipha_dst;
3374 	} else {
3375 		if (ire != NULL)
3376 			ire_refrele(ire);
3377 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3378 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY),
3379 		    ipst);
3380 		if (ire == NULL) {
3381 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3382 			freemsg(ipsec_mp);
3383 			return;
3384 		}
3385 		src = ire->ire_src_addr;
3386 	}
3387 
3388 	if (ire != NULL)
3389 		ire_refrele(ire);
3390 
3391 	/*
3392 	 * Check if we can send back more then 8 bytes in addition to
3393 	 * the IP header.  We try to send 64 bytes of data and the internal
3394 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
3395 	 */
3396 	len_needed = IPH_HDR_LENGTH(ipha);
3397 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
3398 	    ipha->ipha_protocol == IPPROTO_IPV6) {
3399 
3400 		if (!pullupmsg(mp, -1)) {
3401 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3402 			freemsg(ipsec_mp);
3403 			return;
3404 		}
3405 		ipha = (ipha_t *)mp->b_rptr;
3406 
3407 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
3408 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
3409 			    len_needed));
3410 		} else {
3411 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
3412 
3413 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
3414 			len_needed += ip_hdr_length_v6(mp, ip6h);
3415 		}
3416 	}
3417 	len_needed += ipst->ips_ip_icmp_return;
3418 	msg_len = msgdsize(mp);
3419 	if (msg_len > len_needed) {
3420 		(void) adjmsg(mp, len_needed - msg_len);
3421 		msg_len = len_needed;
3422 	}
3423 	mp1 = allocb_tmpl(sizeof (icmp_ipha) + len, mp);
3424 	if (mp1 == NULL) {
3425 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
3426 		freemsg(ipsec_mp);
3427 		return;
3428 	}
3429 	mp1->b_cont = mp;
3430 	mp = mp1;
3431 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3432 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3433 	    io->ipsec_out_type == IPSEC_OUT);
3434 	ipsec_mp->b_cont = mp;
3435 
3436 	/*
3437 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3438 	 * node generates be accepted in peace by all on-host destinations.
3439 	 * If we do NOT assume that all on-host destinations trust
3440 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3441 	 * (Look for ipsec_out_icmp_loopback).
3442 	 */
3443 	io->ipsec_out_icmp_loopback = B_TRUE;
3444 
3445 	ipha = (ipha_t *)mp->b_rptr;
3446 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3447 	*ipha = icmp_ipha;
3448 	ipha->ipha_src = src;
3449 	ipha->ipha_dst = dst;
3450 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
3451 	msg_len += sizeof (icmp_ipha) + len;
3452 	if (msg_len > IP_MAXPACKET) {
3453 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3454 		msg_len = IP_MAXPACKET;
3455 	}
3456 	ipha->ipha_length = htons((uint16_t)msg_len);
3457 	icmph = (icmph_t *)&ipha[1];
3458 	bcopy(stuff, icmph, len);
3459 	icmph->icmph_checksum = 0;
3460 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3461 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
3462 	put(q, ipsec_mp);
3463 }
3464 
3465 /*
3466  * Determine if an ICMP error packet can be sent given the rate limit.
3467  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3468  * in milliseconds) and a burst size. Burst size number of packets can
3469  * be sent arbitrarely closely spaced.
3470  * The state is tracked using two variables to implement an approximate
3471  * token bucket filter:
3472  *	icmp_pkt_err_last - lbolt value when the last burst started
3473  *	icmp_pkt_err_sent - number of packets sent in current burst
3474  */
3475 boolean_t
3476 icmp_err_rate_limit(ip_stack_t *ipst)
3477 {
3478 	clock_t now = TICK_TO_MSEC(lbolt);
3479 	uint_t refilled; /* Number of packets refilled in tbf since last */
3480 	/* Guard against changes by loading into local variable */
3481 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
3482 
3483 	if (err_interval == 0)
3484 		return (B_FALSE);
3485 
3486 	if (ipst->ips_icmp_pkt_err_last > now) {
3487 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3488 		ipst->ips_icmp_pkt_err_last = 0;
3489 		ipst->ips_icmp_pkt_err_sent = 0;
3490 	}
3491 	/*
3492 	 * If we are in a burst update the token bucket filter.
3493 	 * Update the "last" time to be close to "now" but make sure
3494 	 * we don't loose precision.
3495 	 */
3496 	if (ipst->ips_icmp_pkt_err_sent != 0) {
3497 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
3498 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
3499 			ipst->ips_icmp_pkt_err_sent = 0;
3500 		} else {
3501 			ipst->ips_icmp_pkt_err_sent -= refilled;
3502 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
3503 		}
3504 	}
3505 	if (ipst->ips_icmp_pkt_err_sent == 0) {
3506 		/* Start of new burst */
3507 		ipst->ips_icmp_pkt_err_last = now;
3508 	}
3509 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
3510 		ipst->ips_icmp_pkt_err_sent++;
3511 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3512 		    ipst->ips_icmp_pkt_err_sent));
3513 		return (B_FALSE);
3514 	}
3515 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3516 	return (B_TRUE);
3517 }
3518 
3519 /*
3520  * Check if it is ok to send an IPv4 ICMP error packet in
3521  * response to the IPv4 packet in mp.
3522  * Free the message and return null if no
3523  * ICMP error packet should be sent.
3524  */
3525 static mblk_t *
3526 icmp_pkt_err_ok(mblk_t *mp, ip_stack_t *ipst)
3527 {
3528 	icmph_t	*icmph;
3529 	ipha_t	*ipha;
3530 	uint_t	len_needed;
3531 	ire_t	*src_ire;
3532 	ire_t	*dst_ire;
3533 
3534 	if (!mp)
3535 		return (NULL);
3536 	ipha = (ipha_t *)mp->b_rptr;
3537 	if (ip_csum_hdr(ipha)) {
3538 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
3539 		freemsg(mp);
3540 		return (NULL);
3541 	}
3542 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3543 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3544 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3545 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3546 	if (src_ire != NULL || dst_ire != NULL ||
3547 	    CLASSD(ipha->ipha_dst) ||
3548 	    CLASSD(ipha->ipha_src) ||
3549 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3550 		/* Note: only errors to the fragment with offset 0 */
3551 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3552 		freemsg(mp);
3553 		if (src_ire != NULL)
3554 			ire_refrele(src_ire);
3555 		if (dst_ire != NULL)
3556 			ire_refrele(dst_ire);
3557 		return (NULL);
3558 	}
3559 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3560 		/*
3561 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3562 		 * errors in response to any ICMP errors.
3563 		 */
3564 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3565 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3566 			if (!pullupmsg(mp, len_needed)) {
3567 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3568 				freemsg(mp);
3569 				return (NULL);
3570 			}
3571 			ipha = (ipha_t *)mp->b_rptr;
3572 		}
3573 		icmph = (icmph_t *)
3574 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3575 		switch (icmph->icmph_type) {
3576 		case ICMP_DEST_UNREACHABLE:
3577 		case ICMP_SOURCE_QUENCH:
3578 		case ICMP_TIME_EXCEEDED:
3579 		case ICMP_PARAM_PROBLEM:
3580 		case ICMP_REDIRECT:
3581 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3582 			freemsg(mp);
3583 			return (NULL);
3584 		default:
3585 			break;
3586 		}
3587 	}
3588 	/*
3589 	 * If this is a labeled system, then check to see if we're allowed to
3590 	 * send a response to this particular sender.  If not, then just drop.
3591 	 */
3592 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3593 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3594 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3595 		freemsg(mp);
3596 		return (NULL);
3597 	}
3598 	if (icmp_err_rate_limit(ipst)) {
3599 		/*
3600 		 * Only send ICMP error packets every so often.
3601 		 * This should be done on a per port/source basis,
3602 		 * but for now this will suffice.
3603 		 */
3604 		freemsg(mp);
3605 		return (NULL);
3606 	}
3607 	return (mp);
3608 }
3609 
3610 /*
3611  * Generate an ICMP redirect message.
3612  */
3613 static void
3614 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway, ip_stack_t *ipst)
3615 {
3616 	icmph_t	icmph;
3617 
3618 	/*
3619 	 * We are called from ip_rput where we could
3620 	 * not have attached an IPSEC_IN.
3621 	 */
3622 	ASSERT(mp->b_datap->db_type == M_DATA);
3623 
3624 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3625 		return;
3626 	}
3627 
3628 	bzero(&icmph, sizeof (icmph_t));
3629 	icmph.icmph_type = ICMP_REDIRECT;
3630 	icmph.icmph_code = 1;
3631 	icmph.icmph_rd_gateway = gateway;
3632 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3633 	/* Redirects sent by router, and router is global zone */
3634 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID, ipst);
3635 }
3636 
3637 /*
3638  * Generate an ICMP time exceeded message.
3639  */
3640 void
3641 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3642     ip_stack_t *ipst)
3643 {
3644 	icmph_t	icmph;
3645 	boolean_t mctl_present;
3646 	mblk_t *first_mp;
3647 
3648 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3649 
3650 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3651 		if (mctl_present)
3652 			freeb(first_mp);
3653 		return;
3654 	}
3655 
3656 	bzero(&icmph, sizeof (icmph_t));
3657 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3658 	icmph.icmph_code = code;
3659 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3660 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3661 	    ipst);
3662 }
3663 
3664 /*
3665  * Generate an ICMP unreachable message.
3666  */
3667 void
3668 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3669     ip_stack_t *ipst)
3670 {
3671 	icmph_t	icmph;
3672 	mblk_t *first_mp;
3673 	boolean_t mctl_present;
3674 
3675 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3676 
3677 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3678 		if (mctl_present)
3679 			freeb(first_mp);
3680 		return;
3681 	}
3682 
3683 	bzero(&icmph, sizeof (icmph_t));
3684 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3685 	icmph.icmph_code = code;
3686 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3687 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3688 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3689 	    zoneid, ipst);
3690 }
3691 
3692 /*
3693  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3694  * duplicate.  As long as someone else holds the address, the interface will
3695  * stay down.  When that conflict goes away, the interface is brought back up.
3696  * This is done so that accidental shutdowns of addresses aren't made
3697  * permanent.  Your server will recover from a failure.
3698  *
3699  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3700  * user space process (dhcpagent).
3701  *
3702  * Recovery completes if ARP reports that the address is now ours (via
3703  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3704  *
3705  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3706  */
3707 static void
3708 ipif_dup_recovery(void *arg)
3709 {
3710 	ipif_t *ipif = arg;
3711 	ill_t *ill = ipif->ipif_ill;
3712 	mblk_t *arp_add_mp;
3713 	mblk_t *arp_del_mp;
3714 	area_t *area;
3715 	ip_stack_t *ipst = ill->ill_ipst;
3716 
3717 	ipif->ipif_recovery_id = 0;
3718 
3719 	/*
3720 	 * No lock needed for moving or condemned check, as this is just an
3721 	 * optimization.
3722 	 */
3723 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3724 	    (ipif->ipif_flags & IPIF_POINTOPOINT) ||
3725 	    (ipif->ipif_state_flags & (IPIF_MOVING | IPIF_CONDEMNED))) {
3726 		/* No reason to try to bring this address back. */
3727 		return;
3728 	}
3729 
3730 	if ((arp_add_mp = ipif_area_alloc(ipif)) == NULL)
3731 		goto alloc_fail;
3732 
3733 	if (ipif->ipif_arp_del_mp == NULL) {
3734 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3735 			goto alloc_fail;
3736 		ipif->ipif_arp_del_mp = arp_del_mp;
3737 	}
3738 
3739 	/* Setting the 'unverified' flag restarts DAD */
3740 	area = (area_t *)arp_add_mp->b_rptr;
3741 	area->area_flags = ACE_F_PERMANENT | ACE_F_PUBLISH | ACE_F_MYADDR |
3742 	    ACE_F_UNVERIFIED;
3743 	putnext(ill->ill_rq, arp_add_mp);
3744 	return;
3745 
3746 alloc_fail:
3747 	/*
3748 	 * On allocation failure, just restart the timer.  Note that the ipif
3749 	 * is down here, so no other thread could be trying to start a recovery
3750 	 * timer.  The ill_lock protects the condemned flag and the recovery
3751 	 * timer ID.
3752 	 */
3753 	freemsg(arp_add_mp);
3754 	mutex_enter(&ill->ill_lock);
3755 	if (ipst->ips_ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0 &&
3756 	    !(ipif->ipif_state_flags & IPIF_CONDEMNED)) {
3757 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3758 		    MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3759 	}
3760 	mutex_exit(&ill->ill_lock);
3761 }
3762 
3763 /*
3764  * This is for exclusive changes due to ARP.  Either tear down an interface due
3765  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3766  */
3767 /* ARGSUSED */
3768 static void
3769 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3770 {
3771 	ill_t	*ill = rq->q_ptr;
3772 	arh_t *arh;
3773 	ipaddr_t src;
3774 	ipif_t	*ipif;
3775 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3776 	char hbuf[MAC_STR_LEN];
3777 	char sbuf[INET_ADDRSTRLEN];
3778 	const char *failtype;
3779 	boolean_t bring_up;
3780 	ip_stack_t *ipst = ill->ill_ipst;
3781 
3782 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3783 	case AR_CN_READY:
3784 		failtype = NULL;
3785 		bring_up = B_TRUE;
3786 		break;
3787 	case AR_CN_FAILED:
3788 		failtype = "in use";
3789 		bring_up = B_FALSE;
3790 		break;
3791 	default:
3792 		failtype = "claimed";
3793 		bring_up = B_FALSE;
3794 		break;
3795 	}
3796 
3797 	arh = (arh_t *)mp->b_cont->b_rptr;
3798 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3799 
3800 	/* Handle failures due to probes */
3801 	if (src == 0) {
3802 		bcopy((char *)&arh[1] + 2 * arh->arh_hlen + IP_ADDR_LEN, &src,
3803 		    IP_ADDR_LEN);
3804 	}
3805 
3806 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3807 	    sizeof (hbuf));
3808 	(void) ip_dot_addr(src, sbuf);
3809 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3810 
3811 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3812 		    ipif->ipif_lcl_addr != src) {
3813 			continue;
3814 		}
3815 
3816 		/*
3817 		 * If we failed on a recovery probe, then restart the timer to
3818 		 * try again later.
3819 		 */
3820 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3821 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3822 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3823 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3824 		    ipst->ips_ip_dup_recovery > 0 &&
3825 		    ipif->ipif_recovery_id == 0) {
3826 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3827 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3828 			continue;
3829 		}
3830 
3831 		/*
3832 		 * If what we're trying to do has already been done, then do
3833 		 * nothing.
3834 		 */
3835 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3836 			continue;
3837 
3838 		ipif_get_name(ipif, ibuf, sizeof (ibuf));
3839 
3840 		if (failtype == NULL) {
3841 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3842 			    ibuf);
3843 		} else {
3844 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3845 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3846 		}
3847 
3848 		if (bring_up) {
3849 			ASSERT(ill->ill_dl_up);
3850 			/*
3851 			 * Free up the ARP delete message so we can allocate
3852 			 * a fresh one through the normal path.
3853 			 */
3854 			freemsg(ipif->ipif_arp_del_mp);
3855 			ipif->ipif_arp_del_mp = NULL;
3856 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3857 			    EINPROGRESS) {
3858 				ipif->ipif_addr_ready = 1;
3859 				(void) ipif_up_done(ipif);
3860 			}
3861 			continue;
3862 		}
3863 
3864 		mutex_enter(&ill->ill_lock);
3865 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3866 		ipif->ipif_flags |= IPIF_DUPLICATE;
3867 		ill->ill_ipif_dup_count++;
3868 		mutex_exit(&ill->ill_lock);
3869 		/*
3870 		 * Already exclusive on the ill; no need to handle deferred
3871 		 * processing here.
3872 		 */
3873 		(void) ipif_down(ipif, NULL, NULL);
3874 		ipif_down_tail(ipif);
3875 		mutex_enter(&ill->ill_lock);
3876 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3877 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3878 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3879 		    ipst->ips_ip_dup_recovery > 0) {
3880 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3881 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3882 		}
3883 		mutex_exit(&ill->ill_lock);
3884 	}
3885 	freemsg(mp);
3886 }
3887 
3888 /* ARGSUSED */
3889 static void
3890 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3891 {
3892 	ill_t	*ill = rq->q_ptr;
3893 	arh_t *arh;
3894 	ipaddr_t src;
3895 	ipif_t	*ipif;
3896 
3897 	arh = (arh_t *)mp->b_cont->b_rptr;
3898 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3899 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3900 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3901 			(void) ipif_resolver_up(ipif, Res_act_defend);
3902 	}
3903 	freemsg(mp);
3904 }
3905 
3906 /*
3907  * News from ARP.  ARP sends notification of interesting events down
3908  * to its clients using M_CTL messages with the interesting ARP packet
3909  * attached via b_cont.
3910  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3911  * queue as opposed to ARP sending the message to all the clients, i.e. all
3912  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3913  * table if a cache IRE is found to delete all the entries for the address in
3914  * the packet.
3915  */
3916 static void
3917 ip_arp_news(queue_t *q, mblk_t *mp)
3918 {
3919 	arcn_t		*arcn;
3920 	arh_t		*arh;
3921 	ire_t		*ire = NULL;
3922 	char		hbuf[MAC_STR_LEN];
3923 	char		sbuf[INET_ADDRSTRLEN];
3924 	ipaddr_t	src;
3925 	in6_addr_t	v6src;
3926 	boolean_t	isv6 = B_FALSE;
3927 	ipif_t		*ipif;
3928 	ill_t		*ill;
3929 	ip_stack_t	*ipst;
3930 
3931 	if (CONN_Q(q)) {
3932 		conn_t *connp = Q_TO_CONN(q);
3933 
3934 		ipst = connp->conn_netstack->netstack_ip;
3935 	} else {
3936 		ill_t *ill = (ill_t *)q->q_ptr;
3937 
3938 		ipst = ill->ill_ipst;
3939 	}
3940 
3941 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3942 		if (q->q_next) {
3943 			putnext(q, mp);
3944 		} else
3945 			freemsg(mp);
3946 		return;
3947 	}
3948 	arh = (arh_t *)mp->b_cont->b_rptr;
3949 	/* Is it one we are interested in? */
3950 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3951 		isv6 = B_TRUE;
3952 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3953 		    IPV6_ADDR_LEN);
3954 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3955 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3956 		    IP_ADDR_LEN);
3957 	} else {
3958 		freemsg(mp);
3959 		return;
3960 	}
3961 
3962 	ill = q->q_ptr;
3963 
3964 	arcn = (arcn_t *)mp->b_rptr;
3965 	switch (arcn->arcn_code) {
3966 	case AR_CN_BOGON:
3967 		/*
3968 		 * Someone is sending ARP packets with a source protocol
3969 		 * address that we have published and for which we believe our
3970 		 * entry is authoritative and (when ill_arp_extend is set)
3971 		 * verified to be unique on the network.
3972 		 *
3973 		 * The ARP module internally handles the cases where the sender
3974 		 * is just probing (for DAD) and where the hardware address of
3975 		 * a non-authoritative entry has changed.  Thus, these are the
3976 		 * real conflicts, and we have to do resolution.
3977 		 *
3978 		 * We back away quickly from the address if it's from DHCP or
3979 		 * otherwise temporary and hasn't been used recently (or at
3980 		 * all).  We'd like to include "deprecated" addresses here as
3981 		 * well (as there's no real reason to defend something we're
3982 		 * discarding), but IPMP "reuses" this flag to mean something
3983 		 * other than the standard meaning.
3984 		 *
3985 		 * If the ARP module above is not extended (meaning that it
3986 		 * doesn't know how to defend the address), then we just log
3987 		 * the problem as we always did and continue on.  It's not
3988 		 * right, but there's little else we can do, and those old ATM
3989 		 * users are going away anyway.
3990 		 */
3991 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
3992 		    hbuf, sizeof (hbuf));
3993 		(void) ip_dot_addr(src, sbuf);
3994 		if (isv6) {
3995 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL,
3996 			    ipst);
3997 		} else {
3998 			ire = ire_cache_lookup(src, ALL_ZONES, NULL, ipst);
3999 		}
4000 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
4001 			uint32_t now;
4002 			uint32_t maxage;
4003 			clock_t lused;
4004 			uint_t maxdefense;
4005 			uint_t defs;
4006 
4007 			/*
4008 			 * First, figure out if this address hasn't been used
4009 			 * in a while.  If it hasn't, then it's a better
4010 			 * candidate for abandoning.
4011 			 */
4012 			ipif = ire->ire_ipif;
4013 			ASSERT(ipif != NULL);
4014 			now = gethrestime_sec();
4015 			maxage = now - ire->ire_create_time;
4016 			if (maxage > ipst->ips_ip_max_temp_idle)
4017 				maxage = ipst->ips_ip_max_temp_idle;
4018 			lused = drv_hztousec(ddi_get_lbolt() -
4019 			    ire->ire_last_used_time) / MICROSEC + 1;
4020 			if (lused >= maxage && (ipif->ipif_flags &
4021 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
4022 				maxdefense = ipst->ips_ip_max_temp_defend;
4023 			else
4024 				maxdefense = ipst->ips_ip_max_defend;
4025 
4026 			/*
4027 			 * Now figure out how many times we've defended
4028 			 * ourselves.  Ignore defenses that happened long in
4029 			 * the past.
4030 			 */
4031 			mutex_enter(&ire->ire_lock);
4032 			if ((defs = ire->ire_defense_count) > 0 &&
4033 			    now - ire->ire_defense_time >
4034 			    ipst->ips_ip_defend_interval) {
4035 				ire->ire_defense_count = defs = 0;
4036 			}
4037 			ire->ire_defense_count++;
4038 			ire->ire_defense_time = now;
4039 			mutex_exit(&ire->ire_lock);
4040 			ill_refhold(ill);
4041 			ire_refrele(ire);
4042 
4043 			/*
4044 			 * If we've defended ourselves too many times already,
4045 			 * then give up and tear down the interface(s) using
4046 			 * this address.  Otherwise, defend by sending out a
4047 			 * gratuitous ARP.
4048 			 */
4049 			if (defs >= maxdefense && ill->ill_arp_extend) {
4050 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4051 				    B_FALSE);
4052 			} else {
4053 				cmn_err(CE_WARN,
4054 				    "node %s is using our IP address %s on %s",
4055 				    hbuf, sbuf, ill->ill_name);
4056 				/*
4057 				 * If this is an old (ATM) ARP module, then
4058 				 * don't try to defend the address.  Remain
4059 				 * compatible with the old behavior.  Defend
4060 				 * only with new ARP.
4061 				 */
4062 				if (ill->ill_arp_extend) {
4063 					qwriter_ip(ill, q, mp, ip_arp_defend,
4064 					    NEW_OP, B_FALSE);
4065 				} else {
4066 					ill_refrele(ill);
4067 				}
4068 			}
4069 			return;
4070 		}
4071 		cmn_err(CE_WARN,
4072 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4073 		    hbuf, sbuf, ill->ill_name);
4074 		if (ire != NULL)
4075 			ire_refrele(ire);
4076 		break;
4077 	case AR_CN_ANNOUNCE:
4078 		if (isv6) {
4079 			/*
4080 			 * For XRESOLV interfaces.
4081 			 * Delete the IRE cache entry and NCE for this
4082 			 * v6 address
4083 			 */
4084 			ip_ire_clookup_and_delete_v6(&v6src, ipst);
4085 			/*
4086 			 * If v6src is a non-zero, it's a router address
4087 			 * as below. Do the same sort of thing to clean
4088 			 * out off-net IRE_CACHE entries that go through
4089 			 * the router.
4090 			 */
4091 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4092 				ire_walk_v6(ire_delete_cache_gw_v6,
4093 				    (char *)&v6src, ALL_ZONES, ipst);
4094 			}
4095 		} else {
4096 			nce_hw_map_t hwm;
4097 
4098 			/*
4099 			 * ARP gives us a copy of any packet where it thinks
4100 			 * the address has changed, so that we can update our
4101 			 * caches.  We're responsible for caching known answers
4102 			 * in the current design.  We check whether the
4103 			 * hardware address really has changed in all of our
4104 			 * entries that have cached this mapping, and if so, we
4105 			 * blow them away.  This way we will immediately pick
4106 			 * up the rare case of a host changing hardware
4107 			 * address.
4108 			 */
4109 			if (src == 0)
4110 				break;
4111 			hwm.hwm_addr = src;
4112 			hwm.hwm_hwlen = arh->arh_hlen;
4113 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4114 			NDP_HW_CHANGE_INCR(ipst->ips_ndp4);
4115 			ndp_walk_common(ipst->ips_ndp4, NULL,
4116 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4117 			NDP_HW_CHANGE_DECR(ipst->ips_ndp4);
4118 		}
4119 		break;
4120 	case AR_CN_READY:
4121 		/* No external v6 resolver has a contract to use this */
4122 		if (isv6)
4123 			break;
4124 		/* If the link is down, we'll retry this later */
4125 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4126 			break;
4127 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4128 		    NULL, NULL, ipst);
4129 		if (ipif != NULL) {
4130 			/*
4131 			 * If this is a duplicate recovery, then we now need to
4132 			 * go exclusive to bring this thing back up.
4133 			 */
4134 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4135 			    IPIF_DUPLICATE) {
4136 				ipif_refrele(ipif);
4137 				ill_refhold(ill);
4138 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4139 				    B_FALSE);
4140 				return;
4141 			}
4142 			/*
4143 			 * If this is the first notice that this address is
4144 			 * ready, then let the user know now.
4145 			 */
4146 			if ((ipif->ipif_flags & IPIF_UP) &&
4147 			    !ipif->ipif_addr_ready) {
4148 				ipif_mask_reply(ipif);
4149 				ip_rts_ifmsg(ipif);
4150 				ip_rts_newaddrmsg(RTM_ADD, 0, ipif);
4151 				sctp_update_ipif(ipif, SCTP_IPIF_UP);
4152 			}
4153 			ipif->ipif_addr_ready = 1;
4154 			ipif_refrele(ipif);
4155 		}
4156 		ire = ire_cache_lookup(src, ALL_ZONES, MBLK_GETLABEL(mp), ipst);
4157 		if (ire != NULL) {
4158 			ire->ire_defense_count = 0;
4159 			ire_refrele(ire);
4160 		}
4161 		break;
4162 	case AR_CN_FAILED:
4163 		/* No external v6 resolver has a contract to use this */
4164 		if (isv6)
4165 			break;
4166 		ill_refhold(ill);
4167 		qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP, B_FALSE);
4168 		return;
4169 	}
4170 	freemsg(mp);
4171 }
4172 
4173 /*
4174  * Create a mblk suitable for carrying the interface index and/or source link
4175  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4176  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4177  * application.
4178  */
4179 mblk_t *
4180 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags, zoneid_t zoneid,
4181     ip_stack_t *ipst)
4182 {
4183 	mblk_t		*mp;
4184 	ip_pktinfo_t	*pinfo;
4185 	ipha_t *ipha;
4186 	struct ether_header *pether;
4187 
4188 	mp = allocb(sizeof (ip_pktinfo_t), BPRI_MED);
4189 	if (mp == NULL) {
4190 		ip1dbg(("ip_add_info: allocation failure.\n"));
4191 		return (data_mp);
4192 	}
4193 
4194 	ipha	= (ipha_t *)data_mp->b_rptr;
4195 	pinfo = (ip_pktinfo_t *)mp->b_rptr;
4196 	bzero(pinfo, sizeof (ip_pktinfo_t));
4197 	pinfo->ip_pkt_flags = (uchar_t)flags;
4198 	pinfo->ip_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4199 
4200 	if (flags & (IPF_RECVIF | IPF_RECVADDR))
4201 		pinfo->ip_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4202 	if (flags & IPF_RECVADDR) {
4203 		ipif_t	*ipif;
4204 		ire_t	*ire;
4205 
4206 		/*
4207 		 * Only valid for V4
4208 		 */
4209 		ASSERT((ipha->ipha_version_and_hdr_length & 0xf0) ==
4210 		    (IPV4_VERSION << 4));
4211 
4212 		ipif = ipif_get_next_ipif(NULL, ill);
4213 		if (ipif != NULL) {
4214 			/*
4215 			 * Since a decision has already been made to deliver the
4216 			 * packet, there is no need to test for SECATTR and
4217 			 * ZONEONLY.
4218 			 * When a multicast packet is transmitted
4219 			 * a cache entry is created for the multicast address.
4220 			 * When delivering a copy of the packet or when new
4221 			 * packets are received we do not want to match on the
4222 			 * cached entry so explicitly match on
4223 			 * IRE_LOCAL and IRE_LOOPBACK
4224 			 */
4225 			ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4226 			    IRE_LOCAL | IRE_LOOPBACK,
4227 			    ipif, zoneid, NULL,
4228 			    MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP, ipst);
4229 			if (ire == NULL) {
4230 				/*
4231 				 * packet must have come on a different
4232 				 * interface.
4233 				 * Since a decision has already been made to
4234 				 * deliver the packet, there is no need to test
4235 				 * for SECATTR and ZONEONLY.
4236 				 * Only match on local and broadcast ire's.
4237 				 * See detailed comment above.
4238 				 */
4239 				ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4240 				    IRE_LOCAL | IRE_LOOPBACK, ipif, zoneid,
4241 				    NULL, MATCH_IRE_TYPE, ipst);
4242 			}
4243 
4244 			if (ire == NULL) {
4245 				/*
4246 				 * This is either a multicast packet or
4247 				 * the address has been removed since
4248 				 * the packet was received.
4249 				 * Return INADDR_ANY so that normal source
4250 				 * selection occurs for the response.
4251 				 */
4252 
4253 				pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4254 			} else {
4255 				pinfo->ip_pkt_match_addr.s_addr =
4256 				    ire->ire_src_addr;
4257 				ire_refrele(ire);
4258 			}
4259 			ipif_refrele(ipif);
4260 		} else {
4261 			pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4262 		}
4263 	}
4264 
4265 	pether = (struct ether_header *)((char *)ipha
4266 	    - sizeof (struct ether_header));
4267 	/*
4268 	 * Make sure the interface is an ethernet type, since this option
4269 	 * is currently supported only on this type of interface. Also make
4270 	 * sure we are pointing correctly above db_base.
4271 	 */
4272 
4273 	if ((flags & IPF_RECVSLLA) &&
4274 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4275 	    (ill->ill_type == IFT_ETHER) &&
4276 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4277 
4278 		pinfo->ip_pkt_slla.sdl_type = IFT_ETHER;
4279 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
4280 		    (uchar_t *)pinfo->ip_pkt_slla.sdl_data, ETHERADDRL);
4281 	} else {
4282 		/*
4283 		 * Clear the bit. Indicate to upper layer that IP is not
4284 		 * sending this ancillary info.
4285 		 */
4286 		pinfo->ip_pkt_flags = pinfo->ip_pkt_flags & ~IPF_RECVSLLA;
4287 	}
4288 
4289 	mp->b_datap->db_type = M_CTL;
4290 	mp->b_wptr += sizeof (ip_pktinfo_t);
4291 	mp->b_cont = data_mp;
4292 
4293 	return (mp);
4294 }
4295 
4296 /*
4297  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4298  * part of the bind request.
4299  */
4300 
4301 boolean_t
4302 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4303 {
4304 	ipsec_in_t *ii;
4305 
4306 	ASSERT(policy_mp != NULL);
4307 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4308 
4309 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4310 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4311 
4312 	connp->conn_policy = ii->ipsec_in_policy;
4313 	ii->ipsec_in_policy = NULL;
4314 
4315 	if (ii->ipsec_in_action != NULL) {
4316 		if (connp->conn_latch == NULL) {
4317 			connp->conn_latch = iplatch_create();
4318 			if (connp->conn_latch == NULL)
4319 				return (B_FALSE);
4320 		}
4321 		ipsec_latch_inbound(connp->conn_latch, ii);
4322 	}
4323 	return (B_TRUE);
4324 }
4325 
4326 /*
4327  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4328  * and to arrange for power-fanout assist.  The ULP is identified by
4329  * adding a single byte at the end of the original bind message.
4330  * A ULP other than UDP or TCP that wishes to be recognized passes
4331  * down a bind with a zero length address.
4332  *
4333  * The binding works as follows:
4334  * - A zero byte address means just bind to the protocol.
4335  * - A four byte address is treated as a request to validate
4336  *   that the address is a valid local address, appropriate for
4337  *   an application to bind to. This does not affect any fanout
4338  *   information in IP.
4339  * - A sizeof sin_t byte address is used to bind to only the local address
4340  *   and port.
4341  * - A sizeof ipa_conn_t byte address contains complete fanout information
4342  *   consisting of local and remote addresses and ports.  In
4343  *   this case, the addresses are both validated as appropriate
4344  *   for this operation, and, if so, the information is retained
4345  *   for use in the inbound fanout.
4346  *
4347  * The ULP (except in the zero-length bind) can append an
4348  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4349  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4350  * a copy of the source or destination IRE (source for local bind;
4351  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4352  * policy information contained should be copied on to the conn.
4353  *
4354  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4355  */
4356 mblk_t *
4357 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4358 {
4359 	ssize_t		len;
4360 	struct T_bind_req	*tbr;
4361 	sin_t		*sin;
4362 	ipa_conn_t	*ac;
4363 	uchar_t		*ucp;
4364 	mblk_t		*mp1;
4365 	boolean_t	ire_requested;
4366 	boolean_t	ipsec_policy_set = B_FALSE;
4367 	int		error = 0;
4368 	int		protocol;
4369 	ipa_conn_x_t	*acx;
4370 
4371 	ASSERT(!connp->conn_af_isv6);
4372 	connp->conn_pkt_isv6 = B_FALSE;
4373 
4374 	len = MBLKL(mp);
4375 	if (len < (sizeof (*tbr) + 1)) {
4376 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4377 		    "ip_bind: bogus msg, len %ld", len);
4378 		/* XXX: Need to return something better */
4379 		goto bad_addr;
4380 	}
4381 	/* Back up and extract the protocol identifier. */
4382 	mp->b_wptr--;
4383 	protocol = *mp->b_wptr & 0xFF;
4384 	tbr = (struct T_bind_req *)mp->b_rptr;
4385 	/* Reset the message type in preparation for shipping it back. */
4386 	DB_TYPE(mp) = M_PCPROTO;
4387 
4388 	connp->conn_ulp = (uint8_t)protocol;
4389 
4390 	/*
4391 	 * Check for a zero length address.  This is from a protocol that
4392 	 * wants to register to receive all packets of its type.
4393 	 */
4394 	if (tbr->ADDR_length == 0) {
4395 		/*
4396 		 * These protocols are now intercepted in ip_bind_v6().
4397 		 * Reject protocol-level binds here for now.
4398 		 *
4399 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4400 		 * so that the protocol type cannot be SCTP.
4401 		 */
4402 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4403 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4404 			goto bad_addr;
4405 		}
4406 
4407 		/*
4408 		 *
4409 		 * The udp module never sends down a zero-length address,
4410 		 * and allowing this on a labeled system will break MLP
4411 		 * functionality.
4412 		 */
4413 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4414 			goto bad_addr;
4415 
4416 		if (connp->conn_mac_exempt)
4417 			goto bad_addr;
4418 
4419 		/* No hash here really.  The table is big enough. */
4420 		connp->conn_srcv6 = ipv6_all_zeros;
4421 
4422 		ipcl_proto_insert(connp, protocol);
4423 
4424 		tbr->PRIM_type = T_BIND_ACK;
4425 		return (mp);
4426 	}
4427 
4428 	/* Extract the address pointer from the message. */
4429 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4430 	    tbr->ADDR_length);
4431 	if (ucp == NULL) {
4432 		ip1dbg(("ip_bind: no address\n"));
4433 		goto bad_addr;
4434 	}
4435 	if (!OK_32PTR(ucp)) {
4436 		ip1dbg(("ip_bind: unaligned address\n"));
4437 		goto bad_addr;
4438 	}
4439 	/*
4440 	 * Check for trailing mps.
4441 	 */
4442 
4443 	mp1 = mp->b_cont;
4444 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4445 	ipsec_policy_set = (mp1 != NULL && DB_TYPE(mp1) == IPSEC_POLICY_SET);
4446 
4447 	switch (tbr->ADDR_length) {
4448 	default:
4449 		ip1dbg(("ip_bind: bad address length %d\n",
4450 		    (int)tbr->ADDR_length));
4451 		goto bad_addr;
4452 
4453 	case IP_ADDR_LEN:
4454 		/* Verification of local address only */
4455 		error = ip_bind_laddr(connp, mp, *(ipaddr_t *)ucp, 0,
4456 		    ire_requested, ipsec_policy_set, B_FALSE);
4457 		break;
4458 
4459 	case sizeof (sin_t):
4460 		sin = (sin_t *)ucp;
4461 		error = ip_bind_laddr(connp, mp, sin->sin_addr.s_addr,
4462 		    sin->sin_port, ire_requested, ipsec_policy_set, B_TRUE);
4463 		break;
4464 
4465 	case sizeof (ipa_conn_t):
4466 		ac = (ipa_conn_t *)ucp;
4467 		/* For raw socket, the local port is not set. */
4468 		if (ac->ac_lport == 0)
4469 			ac->ac_lport = connp->conn_lport;
4470 		/* Always verify destination reachability. */
4471 		error = ip_bind_connected(connp, mp, &ac->ac_laddr,
4472 		    ac->ac_lport, ac->ac_faddr, ac->ac_fport, ire_requested,
4473 		    ipsec_policy_set, B_TRUE, B_TRUE);
4474 		break;
4475 
4476 	case sizeof (ipa_conn_x_t):
4477 		acx = (ipa_conn_x_t *)ucp;
4478 		/*
4479 		 * Whether or not to verify destination reachability depends
4480 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4481 		 */
4482 		error = ip_bind_connected(connp, mp, &acx->acx_conn.ac_laddr,
4483 		    acx->acx_conn.ac_lport, acx->acx_conn.ac_faddr,
4484 		    acx->acx_conn.ac_fport, ire_requested, ipsec_policy_set,
4485 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
4486 		break;
4487 	}
4488 	if (error == EINPROGRESS)
4489 		return (NULL);
4490 	else if (error != 0)
4491 		goto bad_addr;
4492 	/*
4493 	 * Pass the IPsec headers size in ire_ipsec_overhead.
4494 	 * We can't do this in ip_bind_insert_ire because the policy
4495 	 * may not have been inherited at that point in time and hence
4496 	 * conn_out_enforce_policy may not be set.
4497 	 */
4498 	mp1 = mp->b_cont;
4499 	if (ire_requested && connp->conn_out_enforce_policy &&
4500 	    mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE) {
4501 		ire_t *ire = (ire_t *)mp1->b_rptr;
4502 		ASSERT(MBLKL(mp1) >= sizeof (ire_t));
4503 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4504 	}
4505 
4506 	/* Send it home. */
4507 	mp->b_datap->db_type = M_PCPROTO;
4508 	tbr->PRIM_type = T_BIND_ACK;
4509 	return (mp);
4510 
4511 bad_addr:
4512 	/*
4513 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4514 	 * a unix errno.
4515 	 */
4516 	if (error > 0)
4517 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4518 	else
4519 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4520 	return (mp);
4521 }
4522 
4523 /*
4524  * Here address is verified to be a valid local address.
4525  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4526  * address is also considered a valid local address.
4527  * In the case of a broadcast/multicast address, however, the
4528  * upper protocol is expected to reset the src address
4529  * to 0 if it sees a IRE_BROADCAST type returned so that
4530  * no packets are emitted with broadcast/multicast address as
4531  * source address (that violates hosts requirements RFC1122)
4532  * The addresses valid for bind are:
4533  *	(1) - INADDR_ANY (0)
4534  *	(2) - IP address of an UP interface
4535  *	(3) - IP address of a DOWN interface
4536  *	(4) - valid local IP broadcast addresses. In this case
4537  *	the conn will only receive packets destined to
4538  *	the specified broadcast address.
4539  *	(5) - a multicast address. In this case
4540  *	the conn will only receive packets destined to
4541  *	the specified multicast address. Note: the
4542  *	application still has to issue an
4543  *	IP_ADD_MEMBERSHIP socket option.
4544  *
4545  * On error, return -1 for TBADADDR otherwise pass the
4546  * errno with TSYSERR reply.
4547  *
4548  * In all the above cases, the bound address must be valid in the current zone.
4549  * When the address is loopback, multicast or broadcast, there might be many
4550  * matching IREs so bind has to look up based on the zone.
4551  *
4552  * Note: lport is in network byte order.
4553  */
4554 int
4555 ip_bind_laddr(conn_t *connp, mblk_t *mp, ipaddr_t src_addr, uint16_t lport,
4556     boolean_t ire_requested, boolean_t ipsec_policy_set,
4557     boolean_t fanout_insert)
4558 {
4559 	int		error = 0;
4560 	ire_t		*src_ire;
4561 	mblk_t		*policy_mp;
4562 	ipif_t		*ipif;
4563 	zoneid_t	zoneid;
4564 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4565 
4566 	if (ipsec_policy_set) {
4567 		policy_mp = mp->b_cont;
4568 	}
4569 
4570 	/*
4571 	 * If it was previously connected, conn_fully_bound would have
4572 	 * been set.
4573 	 */
4574 	connp->conn_fully_bound = B_FALSE;
4575 
4576 	src_ire = NULL;
4577 	ipif = NULL;
4578 
4579 	zoneid = IPCL_ZONEID(connp);
4580 
4581 	if (src_addr) {
4582 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4583 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
4584 		/*
4585 		 * If an address other than 0.0.0.0 is requested,
4586 		 * we verify that it is a valid address for bind
4587 		 * Note: Following code is in if-else-if form for
4588 		 * readability compared to a condition check.
4589 		 */
4590 		/* LINTED - statement has no consequent */
4591 		if (IRE_IS_LOCAL(src_ire)) {
4592 			/*
4593 			 * (2) Bind to address of local UP interface
4594 			 */
4595 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4596 			/*
4597 			 * (4) Bind to broadcast address
4598 			 * Note: permitted only from transports that
4599 			 * request IRE
4600 			 */
4601 			if (!ire_requested)
4602 				error = EADDRNOTAVAIL;
4603 		} else {
4604 			/*
4605 			 * (3) Bind to address of local DOWN interface
4606 			 * (ipif_lookup_addr() looks up all interfaces
4607 			 * but we do not get here for UP interfaces
4608 			 * - case (2) above)
4609 			 * We put the protocol byte back into the mblk
4610 			 * since we may come back via ip_wput_nondata()
4611 			 * later with this mblk if ipif_lookup_addr chooses
4612 			 * to defer processing.
4613 			 */
4614 			*mp->b_wptr++ = (char)connp->conn_ulp;
4615 			if ((ipif = ipif_lookup_addr(src_addr, NULL, zoneid,
4616 			    CONNP_TO_WQ(connp), mp, ip_wput_nondata,
4617 			    &error, ipst)) != NULL) {
4618 				ipif_refrele(ipif);
4619 			} else if (error == EINPROGRESS) {
4620 				if (src_ire != NULL)
4621 					ire_refrele(src_ire);
4622 				return (EINPROGRESS);
4623 			} else if (CLASSD(src_addr)) {
4624 				error = 0;
4625 				if (src_ire != NULL)
4626 					ire_refrele(src_ire);
4627 				/*
4628 				 * (5) bind to multicast address.
4629 				 * Fake out the IRE returned to upper
4630 				 * layer to be a broadcast IRE.
4631 				 */
4632 				src_ire = ire_ctable_lookup(
4633 				    INADDR_BROADCAST, INADDR_ANY,
4634 				    IRE_BROADCAST, NULL, zoneid, NULL,
4635 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY),
4636 				    ipst);
4637 				if (src_ire == NULL || !ire_requested)
4638 					error = EADDRNOTAVAIL;
4639 			} else {
4640 				/*
4641 				 * Not a valid address for bind
4642 				 */
4643 				error = EADDRNOTAVAIL;
4644 			}
4645 			/*
4646 			 * Just to keep it consistent with the processing in
4647 			 * ip_bind_v4()
4648 			 */
4649 			mp->b_wptr--;
4650 		}
4651 		if (error) {
4652 			/* Red Alert!  Attempting to be a bogon! */
4653 			ip1dbg(("ip_bind: bad src address 0x%x\n",
4654 			    ntohl(src_addr)));
4655 			goto bad_addr;
4656 		}
4657 	}
4658 
4659 	/*
4660 	 * Allow setting new policies. For example, disconnects come
4661 	 * down as ipa_t bind. As we would have set conn_policy_cached
4662 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4663 	 * can change after the disconnect.
4664 	 */
4665 	connp->conn_policy_cached = B_FALSE;
4666 
4667 	/*
4668 	 * If not fanout_insert this was just an address verification
4669 	 */
4670 	if (fanout_insert) {
4671 		/*
4672 		 * The addresses have been verified. Time to insert in
4673 		 * the correct fanout list.
4674 		 */
4675 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4676 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4677 		connp->conn_lport = lport;
4678 		connp->conn_fport = 0;
4679 		/*
4680 		 * Do we need to add a check to reject Multicast packets
4681 		 */
4682 		error = ipcl_bind_insert(connp, *mp->b_wptr, src_addr, lport);
4683 	}
4684 
4685 	if (error == 0) {
4686 		if (ire_requested) {
4687 			if (!ip_bind_insert_ire(mp, src_ire, NULL, ipst)) {
4688 				error = -1;
4689 				/* Falls through to bad_addr */
4690 			}
4691 		} else if (ipsec_policy_set) {
4692 			if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4693 				error = -1;
4694 				/* Falls through to bad_addr */
4695 			}
4696 		}
4697 	}
4698 bad_addr:
4699 	if (error != 0) {
4700 		if (connp->conn_anon_port) {
4701 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4702 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4703 			    B_FALSE);
4704 		}
4705 		connp->conn_mlp_type = mlptSingle;
4706 	}
4707 	if (src_ire != NULL)
4708 		IRE_REFRELE(src_ire);
4709 	if (ipsec_policy_set) {
4710 		ASSERT(policy_mp == mp->b_cont);
4711 		ASSERT(policy_mp != NULL);
4712 		freeb(policy_mp);
4713 		/*
4714 		 * As of now assume that nothing else accompanies
4715 		 * IPSEC_POLICY_SET.
4716 		 */
4717 		mp->b_cont = NULL;
4718 	}
4719 	return (error);
4720 }
4721 
4722 /*
4723  * Verify that both the source and destination addresses
4724  * are valid.  If verify_dst is false, then the destination address may be
4725  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4726  * destination reachability, while tunnels do not.
4727  * Note that we allow connect to broadcast and multicast
4728  * addresses when ire_requested is set. Thus the ULP
4729  * has to check for IRE_BROADCAST and multicast.
4730  *
4731  * Returns zero if ok.
4732  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4733  * (for use with TSYSERR reply).
4734  *
4735  * Note: lport and fport are in network byte order.
4736  */
4737 int
4738 ip_bind_connected(conn_t *connp, mblk_t *mp, ipaddr_t *src_addrp,
4739     uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4740     boolean_t ire_requested, boolean_t ipsec_policy_set,
4741     boolean_t fanout_insert, boolean_t verify_dst)
4742 {
4743 	ire_t		*src_ire;
4744 	ire_t		*dst_ire;
4745 	int		error = 0;
4746 	int 		protocol;
4747 	mblk_t		*policy_mp;
4748 	ire_t		*sire = NULL;
4749 	ire_t		*md_dst_ire = NULL;
4750 	ire_t		*lso_dst_ire = NULL;
4751 	ill_t		*ill = NULL;
4752 	zoneid_t	zoneid;
4753 	ipaddr_t	src_addr = *src_addrp;
4754 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4755 
4756 	src_ire = dst_ire = NULL;
4757 	protocol = *mp->b_wptr & 0xFF;
4758 
4759 	/*
4760 	 * If we never got a disconnect before, clear it now.
4761 	 */
4762 	connp->conn_fully_bound = B_FALSE;
4763 
4764 	if (ipsec_policy_set) {
4765 		policy_mp = mp->b_cont;
4766 	}
4767 
4768 	zoneid = IPCL_ZONEID(connp);
4769 
4770 	if (CLASSD(dst_addr)) {
4771 		/* Pick up an IRE_BROADCAST */
4772 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4773 		    NULL, zoneid, MBLK_GETLABEL(mp),
4774 		    (MATCH_IRE_RECURSIVE |
4775 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4776 		    MATCH_IRE_SECATTR), ipst);
4777 	} else {
4778 		/*
4779 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4780 		 * and onlink ipif is not found set ENETUNREACH error.
4781 		 */
4782 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4783 			ipif_t *ipif;
4784 
4785 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4786 			    dst_addr : connp->conn_nexthop_v4, zoneid, ipst);
4787 			if (ipif == NULL) {
4788 				error = ENETUNREACH;
4789 				goto bad_addr;
4790 			}
4791 			ipif_refrele(ipif);
4792 		}
4793 
4794 		if (connp->conn_nexthop_set) {
4795 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4796 			    0, 0, NULL, NULL, zoneid, MBLK_GETLABEL(mp),
4797 			    MATCH_IRE_SECATTR, ipst);
4798 		} else {
4799 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4800 			    &sire, zoneid, MBLK_GETLABEL(mp),
4801 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4802 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4803 			    MATCH_IRE_SECATTR), ipst);
4804 		}
4805 	}
4806 	/*
4807 	 * dst_ire can't be a broadcast when not ire_requested.
4808 	 * We also prevent ire's with src address INADDR_ANY to
4809 	 * be used, which are created temporarily for
4810 	 * sending out packets from endpoints that have
4811 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4812 	 * reachable.  If verify_dst is false, the destination needn't be
4813 	 * reachable.
4814 	 *
4815 	 * If we match on a reject or black hole, then we've got a
4816 	 * local failure.  May as well fail out the connect() attempt,
4817 	 * since it's never going to succeed.
4818 	 */
4819 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4820 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4821 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4822 		/*
4823 		 * If we're verifying destination reachability, we always want
4824 		 * to complain here.
4825 		 *
4826 		 * If we're not verifying destination reachability but the
4827 		 * destination has a route, we still want to fail on the
4828 		 * temporary address and broadcast address tests.
4829 		 */
4830 		if (verify_dst || (dst_ire != NULL)) {
4831 			if (ip_debug > 2) {
4832 				pr_addr_dbg("ip_bind_connected: bad connected "
4833 				    "dst %s\n", AF_INET, &dst_addr);
4834 			}
4835 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4836 				error = ENETUNREACH;
4837 			else
4838 				error = EHOSTUNREACH;
4839 			goto bad_addr;
4840 		}
4841 	}
4842 
4843 	/*
4844 	 * We now know that routing will allow us to reach the destination.
4845 	 * Check whether Trusted Solaris policy allows communication with this
4846 	 * host, and pretend that the destination is unreachable if not.
4847 	 *
4848 	 * This is never a problem for TCP, since that transport is known to
4849 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4850 	 * handling.  If the remote is unreachable, it will be detected at that
4851 	 * point, so there's no reason to check it here.
4852 	 *
4853 	 * Note that for sendto (and other datagram-oriented friends), this
4854 	 * check is done as part of the data path label computation instead.
4855 	 * The check here is just to make non-TCP connect() report the right
4856 	 * error.
4857 	 */
4858 	if (dst_ire != NULL && is_system_labeled() &&
4859 	    !IPCL_IS_TCP(connp) &&
4860 	    tsol_compute_label(DB_CREDDEF(mp, connp->conn_cred), dst_addr, NULL,
4861 	    connp->conn_mac_exempt, ipst) != 0) {
4862 		error = EHOSTUNREACH;
4863 		if (ip_debug > 2) {
4864 			pr_addr_dbg("ip_bind_connected: no label for dst %s\n",
4865 			    AF_INET, &dst_addr);
4866 		}
4867 		goto bad_addr;
4868 	}
4869 
4870 	/*
4871 	 * If the app does a connect(), it means that it will most likely
4872 	 * send more than 1 packet to the destination.  It makes sense
4873 	 * to clear the temporary flag.
4874 	 */
4875 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4876 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4877 		irb_t *irb = dst_ire->ire_bucket;
4878 
4879 		rw_enter(&irb->irb_lock, RW_WRITER);
4880 		/*
4881 		 * We need to recheck for IRE_MARK_TEMPORARY after acquiring
4882 		 * the lock to guarantee irb_tmp_ire_cnt.
4883 		 */
4884 		if (dst_ire->ire_marks & IRE_MARK_TEMPORARY) {
4885 			dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4886 			irb->irb_tmp_ire_cnt--;
4887 		}
4888 		rw_exit(&irb->irb_lock);
4889 	}
4890 
4891 	/*
4892 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4893 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4894 	 * eligibility tests for passive connects are handled separately
4895 	 * through tcp_adapt_ire().  We do this before the source address
4896 	 * selection, because dst_ire may change after a call to
4897 	 * ipif_select_source().  This is a best-effort check, as the
4898 	 * packet for this connection may not actually go through
4899 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4900 	 * calling ip_newroute().  This is why we further check on the
4901 	 * IRE during LSO/Multidata packet transmission in
4902 	 * tcp_lsosend()/tcp_multisend().
4903 	 */
4904 	if (!ipsec_policy_set && dst_ire != NULL &&
4905 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4906 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4907 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4908 			lso_dst_ire = dst_ire;
4909 			IRE_REFHOLD(lso_dst_ire);
4910 		} else if (ipst->ips_ip_multidata_outbound &&
4911 		    ILL_MDT_CAPABLE(ill)) {
4912 			md_dst_ire = dst_ire;
4913 			IRE_REFHOLD(md_dst_ire);
4914 		}
4915 	}
4916 
4917 	if (dst_ire != NULL &&
4918 	    dst_ire->ire_type == IRE_LOCAL &&
4919 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4920 		/*
4921 		 * If the IRE belongs to a different zone, look for a matching
4922 		 * route in the forwarding table and use the source address from
4923 		 * that route.
4924 		 */
4925 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4926 		    zoneid, 0, NULL,
4927 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4928 		    MATCH_IRE_RJ_BHOLE, ipst);
4929 		if (src_ire == NULL) {
4930 			error = EHOSTUNREACH;
4931 			goto bad_addr;
4932 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4933 			if (!(src_ire->ire_type & IRE_HOST))
4934 				error = ENETUNREACH;
4935 			else
4936 				error = EHOSTUNREACH;
4937 			goto bad_addr;
4938 		}
4939 		if (src_addr == INADDR_ANY)
4940 			src_addr = src_ire->ire_src_addr;
4941 		ire_refrele(src_ire);
4942 		src_ire = NULL;
4943 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4944 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4945 			src_addr = sire->ire_src_addr;
4946 			ire_refrele(dst_ire);
4947 			dst_ire = sire;
4948 			sire = NULL;
4949 		} else {
4950 			/*
4951 			 * Pick a source address so that a proper inbound
4952 			 * load spreading would happen.
4953 			 */
4954 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4955 			ipif_t *src_ipif = NULL;
4956 			ire_t *ipif_ire;
4957 
4958 			/*
4959 			 * Supply a local source address such that inbound
4960 			 * load spreading happens.
4961 			 *
4962 			 * Determine the best source address on this ill for
4963 			 * the destination.
4964 			 *
4965 			 * 1) For broadcast, we should return a broadcast ire
4966 			 *    found above so that upper layers know that the
4967 			 *    destination address is a broadcast address.
4968 			 *
4969 			 * 2) If this is part of a group, select a better
4970 			 *    source address so that better inbound load
4971 			 *    balancing happens. Do the same if the ipif
4972 			 *    is DEPRECATED.
4973 			 *
4974 			 * 3) If the outgoing interface is part of a usesrc
4975 			 *    group, then try selecting a source address from
4976 			 *    the usesrc ILL.
4977 			 */
4978 			if ((dst_ire->ire_zoneid != zoneid &&
4979 			    dst_ire->ire_zoneid != ALL_ZONES) ||
4980 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
4981 			    ((dst_ill->ill_group != NULL) ||
4982 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
4983 			    (dst_ill->ill_usesrc_ifindex != 0)))) {
4984 				/*
4985 				 * If the destination is reachable via a
4986 				 * given gateway, the selected source address
4987 				 * should be in the same subnet as the gateway.
4988 				 * Otherwise, the destination is not reachable.
4989 				 *
4990 				 * If there are no interfaces on the same subnet
4991 				 * as the destination, ipif_select_source gives
4992 				 * first non-deprecated interface which might be
4993 				 * on a different subnet than the gateway.
4994 				 * This is not desirable. Hence pass the dst_ire
4995 				 * source address to ipif_select_source.
4996 				 * It is sure that the destination is reachable
4997 				 * with the dst_ire source address subnet.
4998 				 * So passing dst_ire source address to
4999 				 * ipif_select_source will make sure that the
5000 				 * selected source will be on the same subnet
5001 				 * as dst_ire source address.
5002 				 */
5003 				ipaddr_t saddr =
5004 				    dst_ire->ire_ipif->ipif_src_addr;
5005 				src_ipif = ipif_select_source(dst_ill,
5006 				    saddr, zoneid);
5007 				if (src_ipif != NULL) {
5008 					if (IS_VNI(src_ipif->ipif_ill)) {
5009 						/*
5010 						 * For VNI there is no
5011 						 * interface route
5012 						 */
5013 						src_addr =
5014 						    src_ipif->ipif_src_addr;
5015 					} else {
5016 						ipif_ire =
5017 						    ipif_to_ire(src_ipif);
5018 						if (ipif_ire != NULL) {
5019 							IRE_REFRELE(dst_ire);
5020 							dst_ire = ipif_ire;
5021 						}
5022 						src_addr =
5023 						    dst_ire->ire_src_addr;
5024 					}
5025 					ipif_refrele(src_ipif);
5026 				} else {
5027 					src_addr = dst_ire->ire_src_addr;
5028 				}
5029 			} else {
5030 				src_addr = dst_ire->ire_src_addr;
5031 			}
5032 		}
5033 	}
5034 
5035 	/*
5036 	 * We do ire_route_lookup() here (and not
5037 	 * interface lookup as we assert that
5038 	 * src_addr should only come from an
5039 	 * UP interface for hard binding.
5040 	 */
5041 	ASSERT(src_ire == NULL);
5042 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5043 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
5044 	/* src_ire must be a local|loopback */
5045 	if (!IRE_IS_LOCAL(src_ire)) {
5046 		if (ip_debug > 2) {
5047 			pr_addr_dbg("ip_bind_connected: bad connected "
5048 			    "src %s\n", AF_INET, &src_addr);
5049 		}
5050 		error = EADDRNOTAVAIL;
5051 		goto bad_addr;
5052 	}
5053 
5054 	/*
5055 	 * If the source address is a loopback address, the
5056 	 * destination had best be local or multicast.
5057 	 * The transports that can't handle multicast will reject
5058 	 * those addresses.
5059 	 */
5060 	if (src_ire->ire_type == IRE_LOOPBACK &&
5061 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5062 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
5063 		error = -1;
5064 		goto bad_addr;
5065 	}
5066 
5067 	/*
5068 	 * Allow setting new policies. For example, disconnects come
5069 	 * down as ipa_t bind. As we would have set conn_policy_cached
5070 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5071 	 * can change after the disconnect.
5072 	 */
5073 	connp->conn_policy_cached = B_FALSE;
5074 
5075 	/*
5076 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5077 	 * can handle their passed-in conn's.
5078 	 */
5079 
5080 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5081 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5082 	connp->conn_lport = lport;
5083 	connp->conn_fport = fport;
5084 	*src_addrp = src_addr;
5085 
5086 	ASSERT(!(ipsec_policy_set && ire_requested));
5087 	if (ire_requested) {
5088 		iulp_t *ulp_info = NULL;
5089 
5090 		/*
5091 		 * Note that sire will not be NULL if this is an off-link
5092 		 * connection and there is not cache for that dest yet.
5093 		 *
5094 		 * XXX Because of an existing bug, if there are multiple
5095 		 * default routes, the IRE returned now may not be the actual
5096 		 * default route used (default routes are chosen in a
5097 		 * round robin fashion).  So if the metrics for different
5098 		 * default routes are different, we may return the wrong
5099 		 * metrics.  This will not be a problem if the existing
5100 		 * bug is fixed.
5101 		 */
5102 		if (sire != NULL) {
5103 			ulp_info = &(sire->ire_uinfo);
5104 		}
5105 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info, ipst)) {
5106 			error = -1;
5107 			goto bad_addr;
5108 		}
5109 	} else if (ipsec_policy_set) {
5110 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
5111 			error = -1;
5112 			goto bad_addr;
5113 		}
5114 	}
5115 
5116 	/*
5117 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5118 	 * we'll cache that.  If we don't, we'll inherit global policy.
5119 	 *
5120 	 * We can't insert until the conn reflects the policy. Note that
5121 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5122 	 * connections where we don't have a policy. This is to prevent
5123 	 * global policy lookups in the inbound path.
5124 	 *
5125 	 * If we insert before we set conn_policy_cached,
5126 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5127 	 * because global policy cound be non-empty. We normally call
5128 	 * ipsec_check_policy() for conn_policy_cached connections only if
5129 	 * ipc_in_enforce_policy is set. But in this case,
5130 	 * conn_policy_cached can get set anytime since we made the
5131 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5132 	 * called, which will make the above assumption false.  Thus, we
5133 	 * need to insert after we set conn_policy_cached.
5134 	 */
5135 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5136 		goto bad_addr;
5137 
5138 	if (fanout_insert) {
5139 		/*
5140 		 * The addresses have been verified. Time to insert in
5141 		 * the correct fanout list.
5142 		 */
5143 		error = ipcl_conn_insert(connp, protocol, src_addr,
5144 		    dst_addr, connp->conn_ports);
5145 	}
5146 
5147 	if (error == 0) {
5148 		connp->conn_fully_bound = B_TRUE;
5149 		/*
5150 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5151 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5152 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5153 		 * ip_xxinfo_return(), which performs further checks
5154 		 * against them and upon success, returns the LSO/MDT info
5155 		 * mblk which we will attach to the bind acknowledgment.
5156 		 */
5157 		if (lso_dst_ire != NULL) {
5158 			mblk_t *lsoinfo_mp;
5159 
5160 			ASSERT(ill->ill_lso_capab != NULL);
5161 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5162 			    ill->ill_name, ill->ill_lso_capab)) != NULL)
5163 				linkb(mp, lsoinfo_mp);
5164 		} else if (md_dst_ire != NULL) {
5165 			mblk_t *mdinfo_mp;
5166 
5167 			ASSERT(ill->ill_mdt_capab != NULL);
5168 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5169 			    ill->ill_name, ill->ill_mdt_capab)) != NULL)
5170 				linkb(mp, mdinfo_mp);
5171 		}
5172 	}
5173 bad_addr:
5174 	if (ipsec_policy_set) {
5175 		ASSERT(policy_mp == mp->b_cont);
5176 		ASSERT(policy_mp != NULL);
5177 		freeb(policy_mp);
5178 		/*
5179 		 * As of now assume that nothing else accompanies
5180 		 * IPSEC_POLICY_SET.
5181 		 */
5182 		mp->b_cont = NULL;
5183 	}
5184 	if (src_ire != NULL)
5185 		IRE_REFRELE(src_ire);
5186 	if (dst_ire != NULL)
5187 		IRE_REFRELE(dst_ire);
5188 	if (sire != NULL)
5189 		IRE_REFRELE(sire);
5190 	if (md_dst_ire != NULL)
5191 		IRE_REFRELE(md_dst_ire);
5192 	if (lso_dst_ire != NULL)
5193 		IRE_REFRELE(lso_dst_ire);
5194 	return (error);
5195 }
5196 
5197 /*
5198  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
5199  * Prefers dst_ire over src_ire.
5200  */
5201 static boolean_t
5202 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info, ip_stack_t *ipst)
5203 {
5204 	mblk_t	*mp1;
5205 	ire_t *ret_ire = NULL;
5206 
5207 	mp1 = mp->b_cont;
5208 	ASSERT(mp1 != NULL);
5209 
5210 	if (ire != NULL) {
5211 		/*
5212 		 * mp1 initialized above to IRE_DB_REQ_TYPE
5213 		 * appended mblk. Its <upper protocol>'s
5214 		 * job to make sure there is room.
5215 		 */
5216 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
5217 			return (0);
5218 
5219 		mp1->b_datap->db_type = IRE_DB_TYPE;
5220 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
5221 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
5222 		ret_ire = (ire_t *)mp1->b_rptr;
5223 		/*
5224 		 * Pass the latest setting of the ip_path_mtu_discovery and
5225 		 * copy the ulp info if any.
5226 		 */
5227 		ret_ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ?
5228 		    IPH_DF : 0;
5229 		if (ulp_info != NULL) {
5230 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5231 			    sizeof (iulp_t));
5232 		}
5233 		ret_ire->ire_mp = mp1;
5234 	} else {
5235 		/*
5236 		 * No IRE was found. Remove IRE mblk.
5237 		 */
5238 		mp->b_cont = mp1->b_cont;
5239 		freeb(mp1);
5240 	}
5241 
5242 	return (1);
5243 }
5244 
5245 /*
5246  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5247  * the final piece where we don't.  Return a pointer to the first mblk in the
5248  * result, and update the pointer to the next mblk to chew on.  If anything
5249  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5250  * NULL pointer.
5251  */
5252 mblk_t *
5253 ip_carve_mp(mblk_t **mpp, ssize_t len)
5254 {
5255 	mblk_t	*mp0;
5256 	mblk_t	*mp1;
5257 	mblk_t	*mp2;
5258 
5259 	if (!len || !mpp || !(mp0 = *mpp))
5260 		return (NULL);
5261 	/* If we aren't going to consume the first mblk, we need a dup. */
5262 	if (mp0->b_wptr - mp0->b_rptr > len) {
5263 		mp1 = dupb(mp0);
5264 		if (mp1) {
5265 			/* Partition the data between the two mblks. */
5266 			mp1->b_wptr = mp1->b_rptr + len;
5267 			mp0->b_rptr = mp1->b_wptr;
5268 			/*
5269 			 * after adjustments if mblk not consumed is now
5270 			 * unaligned, try to align it. If this fails free
5271 			 * all messages and let upper layer recover.
5272 			 */
5273 			if (!OK_32PTR(mp0->b_rptr)) {
5274 				if (!pullupmsg(mp0, -1)) {
5275 					freemsg(mp0);
5276 					freemsg(mp1);
5277 					*mpp = NULL;
5278 					return (NULL);
5279 				}
5280 			}
5281 		}
5282 		return (mp1);
5283 	}
5284 	/* Eat through as many mblks as we need to get len bytes. */
5285 	len -= mp0->b_wptr - mp0->b_rptr;
5286 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5287 		if (mp2->b_wptr - mp2->b_rptr > len) {
5288 			/*
5289 			 * We won't consume the entire last mblk.  Like
5290 			 * above, dup and partition it.
5291 			 */
5292 			mp1->b_cont = dupb(mp2);
5293 			mp1 = mp1->b_cont;
5294 			if (!mp1) {
5295 				/*
5296 				 * Trouble.  Rather than go to a lot of
5297 				 * trouble to clean up, we free the messages.
5298 				 * This won't be any worse than losing it on
5299 				 * the wire.
5300 				 */
5301 				freemsg(mp0);
5302 				freemsg(mp2);
5303 				*mpp = NULL;
5304 				return (NULL);
5305 			}
5306 			mp1->b_wptr = mp1->b_rptr + len;
5307 			mp2->b_rptr = mp1->b_wptr;
5308 			/*
5309 			 * after adjustments if mblk not consumed is now
5310 			 * unaligned, try to align it. If this fails free
5311 			 * all messages and let upper layer recover.
5312 			 */
5313 			if (!OK_32PTR(mp2->b_rptr)) {
5314 				if (!pullupmsg(mp2, -1)) {
5315 					freemsg(mp0);
5316 					freemsg(mp2);
5317 					*mpp = NULL;
5318 					return (NULL);
5319 				}
5320 			}
5321 			*mpp = mp2;
5322 			return (mp0);
5323 		}
5324 		/* Decrement len by the amount we just got. */
5325 		len -= mp2->b_wptr - mp2->b_rptr;
5326 	}
5327 	/*
5328 	 * len should be reduced to zero now.  If not our caller has
5329 	 * screwed up.
5330 	 */
5331 	if (len) {
5332 		/* Shouldn't happen! */
5333 		freemsg(mp0);
5334 		*mpp = NULL;
5335 		return (NULL);
5336 	}
5337 	/*
5338 	 * We consumed up to exactly the end of an mblk.  Detach the part
5339 	 * we are returning from the rest of the chain.
5340 	 */
5341 	mp1->b_cont = NULL;
5342 	*mpp = mp2;
5343 	return (mp0);
5344 }
5345 
5346 /* The ill stream is being unplumbed. Called from ip_close */
5347 int
5348 ip_modclose(ill_t *ill)
5349 {
5350 	boolean_t success;
5351 	ipsq_t	*ipsq;
5352 	ipif_t	*ipif;
5353 	queue_t	*q = ill->ill_rq;
5354 	ip_stack_t	*ipst = ill->ill_ipst;
5355 	clock_t timeout;
5356 
5357 	/*
5358 	 * Wait for the ACKs of all deferred control messages to be processed.
5359 	 * In particular, we wait for a potential capability reset initiated
5360 	 * in ip_sioctl_plink() to complete before proceeding.
5361 	 *
5362 	 * Note: we wait for at most ip_modclose_ackwait_ms (by default 3000 ms)
5363 	 * in case the driver never replies.
5364 	 */
5365 	timeout = lbolt + MSEC_TO_TICK(ip_modclose_ackwait_ms);
5366 	mutex_enter(&ill->ill_lock);
5367 	while (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
5368 		if (cv_timedwait(&ill->ill_cv, &ill->ill_lock, timeout) < 0) {
5369 			/* Timeout */
5370 			break;
5371 		}
5372 	}
5373 	mutex_exit(&ill->ill_lock);
5374 
5375 	/*
5376 	 * Forcibly enter the ipsq after some delay. This is to take
5377 	 * care of the case when some ioctl does not complete because
5378 	 * we sent a control message to the driver and it did not
5379 	 * send us a reply. We want to be able to at least unplumb
5380 	 * and replumb rather than force the user to reboot the system.
5381 	 */
5382 	success = ipsq_enter(ill, B_FALSE);
5383 
5384 	/*
5385 	 * Open/close/push/pop is guaranteed to be single threaded
5386 	 * per stream by STREAMS. FS guarantees that all references
5387 	 * from top are gone before close is called. So there can't
5388 	 * be another close thread that has set CONDEMNED on this ill.
5389 	 * and cause ipsq_enter to return failure.
5390 	 */
5391 	ASSERT(success);
5392 	ipsq = ill->ill_phyint->phyint_ipsq;
5393 
5394 	/*
5395 	 * Mark it condemned. No new reference will be made to this ill.
5396 	 * Lookup functions will return an error. Threads that try to
5397 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5398 	 * that the refcnt will drop down to zero.
5399 	 */
5400 	mutex_enter(&ill->ill_lock);
5401 	ill->ill_state_flags |= ILL_CONDEMNED;
5402 	for (ipif = ill->ill_ipif; ipif != NULL;
5403 	    ipif = ipif->ipif_next) {
5404 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5405 	}
5406 	/*
5407 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5408 	 * returns  error if ILL_CONDEMNED is set
5409 	 */
5410 	cv_broadcast(&ill->ill_cv);
5411 	mutex_exit(&ill->ill_lock);
5412 
5413 	/*
5414 	 * Send all the deferred DLPI messages downstream which came in
5415 	 * during the small window right before ipsq_enter(). We do this
5416 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5417 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5418 	 */
5419 	ill_dlpi_send_deferred(ill);
5420 
5421 	/*
5422 	 * Shut down fragmentation reassembly.
5423 	 * ill_frag_timer won't start a timer again.
5424 	 * Now cancel any existing timer
5425 	 */
5426 	(void) untimeout(ill->ill_frag_timer_id);
5427 	(void) ill_frag_timeout(ill, 0);
5428 
5429 	/*
5430 	 * If MOVE was in progress, clear the
5431 	 * move_in_progress fields also.
5432 	 */
5433 	if (ill->ill_move_in_progress) {
5434 		ILL_CLEAR_MOVE(ill);
5435 	}
5436 
5437 	/*
5438 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5439 	 * this ill. Then wait for the refcnts to drop to zero.
5440 	 * ill_is_quiescent checks whether the ill is really quiescent.
5441 	 * Then make sure that threads that are waiting to enter the
5442 	 * ipsq have seen the error returned by ipsq_enter and have
5443 	 * gone away. Then we call ill_delete_tail which does the
5444 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
5445 	 */
5446 	ill_delete(ill);
5447 	mutex_enter(&ill->ill_lock);
5448 	while (!ill_is_quiescent(ill))
5449 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5450 	while (ill->ill_waiters)
5451 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5452 
5453 	mutex_exit(&ill->ill_lock);
5454 
5455 	/*
5456 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
5457 	 * it held until the end of the function since the cleanup
5458 	 * below needs to be able to use the ip_stack_t.
5459 	 */
5460 	netstack_hold(ipst->ips_netstack);
5461 
5462 	/* qprocsoff is called in ill_delete_tail */
5463 	ill_delete_tail(ill);
5464 	ASSERT(ill->ill_ipst == NULL);
5465 
5466 	/*
5467 	 * Walk through all upper (conn) streams and qenable
5468 	 * those that have queued data.
5469 	 * close synchronization needs this to
5470 	 * be done to ensure that all upper layers blocked
5471 	 * due to flow control to the closing device
5472 	 * get unblocked.
5473 	 */
5474 	ip1dbg(("ip_wsrv: walking\n"));
5475 	conn_walk_drain(ipst);
5476 
5477 	mutex_enter(&ipst->ips_ip_mi_lock);
5478 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
5479 	mutex_exit(&ipst->ips_ip_mi_lock);
5480 
5481 	/*
5482 	 * credp could be null if the open didn't succeed and ip_modopen
5483 	 * itself calls ip_close.
5484 	 */
5485 	if (ill->ill_credp != NULL)
5486 		crfree(ill->ill_credp);
5487 
5488 	mutex_enter(&ill->ill_lock);
5489 	ill_nic_info_dispatch(ill);
5490 	mutex_exit(&ill->ill_lock);
5491 
5492 	/*
5493 	 * Now we are done with the module close pieces that
5494 	 * need the netstack_t.
5495 	 */
5496 	netstack_rele(ipst->ips_netstack);
5497 
5498 	mi_close_free((IDP)ill);
5499 	q->q_ptr = WR(q)->q_ptr = NULL;
5500 
5501 	ipsq_exit(ipsq, B_TRUE, B_TRUE);
5502 
5503 	return (0);
5504 }
5505 
5506 /*
5507  * This is called as part of close() for IP, UDP, ICMP, and RTS
5508  * in order to quiesce the conn.
5509  */
5510 void
5511 ip_quiesce_conn(conn_t *connp)
5512 {
5513 	boolean_t	drain_cleanup_reqd = B_FALSE;
5514 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5515 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5516 	ip_stack_t	*ipst;
5517 
5518 	ASSERT(!IPCL_IS_TCP(connp));
5519 	ipst = connp->conn_netstack->netstack_ip;
5520 
5521 	/*
5522 	 * Mark the conn as closing, and this conn must not be
5523 	 * inserted in future into any list. Eg. conn_drain_insert(),
5524 	 * won't insert this conn into the conn_drain_list.
5525 	 * Similarly ill_pending_mp_add() will not add any mp to
5526 	 * the pending mp list, after this conn has started closing.
5527 	 *
5528 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5529 	 * cannot get set henceforth.
5530 	 */
5531 	mutex_enter(&connp->conn_lock);
5532 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5533 	connp->conn_state_flags |= CONN_CLOSING;
5534 	if (connp->conn_idl != NULL)
5535 		drain_cleanup_reqd = B_TRUE;
5536 	if (connp->conn_oper_pending_ill != NULL)
5537 		conn_ioctl_cleanup_reqd = B_TRUE;
5538 	if (connp->conn_dhcpinit_ill != NULL) {
5539 		ASSERT(connp->conn_dhcpinit_ill->ill_dhcpinit != 0);
5540 		atomic_dec_32(&connp->conn_dhcpinit_ill->ill_dhcpinit);
5541 		connp->conn_dhcpinit_ill = NULL;
5542 	}
5543 	if (connp->conn_ilg_inuse != 0)
5544 		ilg_cleanup_reqd = B_TRUE;
5545 	mutex_exit(&connp->conn_lock);
5546 
5547 	if (conn_ioctl_cleanup_reqd)
5548 		conn_ioctl_cleanup(connp);
5549 
5550 	if (is_system_labeled() && connp->conn_anon_port) {
5551 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5552 		    connp->conn_mlp_type, connp->conn_ulp,
5553 		    ntohs(connp->conn_lport), B_FALSE);
5554 		connp->conn_anon_port = 0;
5555 	}
5556 	connp->conn_mlp_type = mlptSingle;
5557 
5558 	/*
5559 	 * Remove this conn from any fanout list it is on.
5560 	 * and then wait for any threads currently operating
5561 	 * on this endpoint to finish
5562 	 */
5563 	ipcl_hash_remove(connp);
5564 
5565 	/*
5566 	 * Remove this conn from the drain list, and do
5567 	 * any other cleanup that may be required.
5568 	 * (Only non-tcp streams may have a non-null conn_idl.
5569 	 * TCP streams are never flow controlled, and
5570 	 * conn_idl will be null)
5571 	 */
5572 	if (drain_cleanup_reqd)
5573 		conn_drain_tail(connp, B_TRUE);
5574 
5575 	if (connp == ipst->ips_ip_g_mrouter)
5576 		(void) ip_mrouter_done(NULL, ipst);
5577 
5578 	if (ilg_cleanup_reqd)
5579 		ilg_delete_all(connp);
5580 
5581 	conn_delete_ire(connp, NULL);
5582 
5583 	/*
5584 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5585 	 * callers from write side can't be there now because close
5586 	 * is in progress. The only other caller is ipcl_walk
5587 	 * which checks for the condemned flag.
5588 	 */
5589 	mutex_enter(&connp->conn_lock);
5590 	connp->conn_state_flags |= CONN_CONDEMNED;
5591 	while (connp->conn_ref != 1)
5592 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5593 	connp->conn_state_flags |= CONN_QUIESCED;
5594 	mutex_exit(&connp->conn_lock);
5595 }
5596 
5597 /* ARGSUSED */
5598 int
5599 ip_close(queue_t *q, int flags)
5600 {
5601 	conn_t		*connp;
5602 
5603 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5604 
5605 	/*
5606 	 * Call the appropriate delete routine depending on whether this is
5607 	 * a module or device.
5608 	 */
5609 	if (WR(q)->q_next != NULL) {
5610 		/* This is a module close */
5611 		return (ip_modclose((ill_t *)q->q_ptr));
5612 	}
5613 
5614 	connp = q->q_ptr;
5615 	ip_quiesce_conn(connp);
5616 
5617 	qprocsoff(q);
5618 
5619 	/*
5620 	 * Now we are truly single threaded on this stream, and can
5621 	 * delete the things hanging off the connp, and finally the connp.
5622 	 * We removed this connp from the fanout list, it cannot be
5623 	 * accessed thru the fanouts, and we already waited for the
5624 	 * conn_ref to drop to 0. We are already in close, so
5625 	 * there cannot be any other thread from the top. qprocsoff
5626 	 * has completed, and service has completed or won't run in
5627 	 * future.
5628 	 */
5629 	ASSERT(connp->conn_ref == 1);
5630 
5631 	inet_minor_free(ip_minor_arena, connp->conn_dev);
5632 
5633 	connp->conn_ref--;
5634 	ipcl_conn_destroy(connp);
5635 
5636 	q->q_ptr = WR(q)->q_ptr = NULL;
5637 	return (0);
5638 }
5639 
5640 /*
5641  * Wapper around putnext() so that ip_rts_request can merely use
5642  * conn_recv.
5643  */
5644 /*ARGSUSED2*/
5645 static void
5646 ip_conn_input(void *arg1, mblk_t *mp, void *arg2)
5647 {
5648 	conn_t *connp = (conn_t *)arg1;
5649 
5650 	putnext(connp->conn_rq, mp);
5651 }
5652 
5653 /* Return the IP checksum for the IP header at "iph". */
5654 uint16_t
5655 ip_csum_hdr(ipha_t *ipha)
5656 {
5657 	uint16_t	*uph;
5658 	uint32_t	sum;
5659 	int		opt_len;
5660 
5661 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
5662 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
5663 	uph = (uint16_t *)ipha;
5664 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
5665 	    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
5666 	if (opt_len > 0) {
5667 		do {
5668 			sum += uph[10];
5669 			sum += uph[11];
5670 			uph += 2;
5671 		} while (--opt_len);
5672 	}
5673 	sum = (sum & 0xFFFF) + (sum >> 16);
5674 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
5675 	if (sum == 0xffff)
5676 		sum = 0;
5677 	return ((uint16_t)sum);
5678 }
5679 
5680 /*
5681  * Called when the module is about to be unloaded
5682  */
5683 void
5684 ip_ddi_destroy(void)
5685 {
5686 	tnet_fini();
5687 
5688 	icmp_ddi_destroy();
5689 	rts_ddi_destroy();
5690 	udp_ddi_destroy();
5691 	sctp_ddi_g_destroy();
5692 	tcp_ddi_g_destroy();
5693 	ipsec_policy_g_destroy();
5694 	ipcl_g_destroy();
5695 	ip_net_g_destroy();
5696 	ip_ire_g_fini();
5697 	inet_minor_destroy(ip_minor_arena);
5698 
5699 #ifdef DEBUG
5700 	list_destroy(&ip_thread_list);
5701 	rw_destroy(&ip_thread_rwlock);
5702 	tsd_destroy(&ip_thread_data);
5703 #endif
5704 
5705 	netstack_unregister(NS_IP);
5706 }
5707 
5708 /*
5709  * First step in cleanup.
5710  */
5711 /* ARGSUSED */
5712 static void
5713 ip_stack_shutdown(netstackid_t stackid, void *arg)
5714 {
5715 	ip_stack_t *ipst = (ip_stack_t *)arg;
5716 
5717 #ifdef NS_DEBUG
5718 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
5719 #endif
5720 
5721 	/* Get rid of loopback interfaces and their IREs */
5722 	ip_loopback_cleanup(ipst);
5723 }
5724 
5725 /*
5726  * Free the IP stack instance.
5727  */
5728 static void
5729 ip_stack_fini(netstackid_t stackid, void *arg)
5730 {
5731 	ip_stack_t *ipst = (ip_stack_t *)arg;
5732 	int ret;
5733 
5734 #ifdef NS_DEBUG
5735 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5736 #endif
5737 	ipv4_hook_destroy(ipst);
5738 	ipv6_hook_destroy(ipst);
5739 	ip_net_destroy(ipst);
5740 
5741 	rw_destroy(&ipst->ips_srcid_lock);
5742 
5743 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5744 	ipst->ips_ip_mibkp = NULL;
5745 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5746 	ipst->ips_icmp_mibkp = NULL;
5747 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5748 	ipst->ips_ip_kstat = NULL;
5749 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5750 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5751 	ipst->ips_ip6_kstat = NULL;
5752 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5753 
5754 	nd_free(&ipst->ips_ip_g_nd);
5755 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5756 	ipst->ips_param_arr = NULL;
5757 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5758 	ipst->ips_ndp_arr = NULL;
5759 
5760 	ip_mrouter_stack_destroy(ipst);
5761 
5762 	mutex_destroy(&ipst->ips_ip_mi_lock);
5763 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5764 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5765 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5766 
5767 	ret = untimeout(ipst->ips_igmp_timeout_id);
5768 	if (ret == -1) {
5769 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5770 	} else {
5771 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5772 		ipst->ips_igmp_timeout_id = 0;
5773 	}
5774 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5775 	if (ret == -1) {
5776 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5777 	} else {
5778 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5779 		ipst->ips_igmp_slowtimeout_id = 0;
5780 	}
5781 	ret = untimeout(ipst->ips_mld_timeout_id);
5782 	if (ret == -1) {
5783 		ASSERT(ipst->ips_mld_timeout_id == 0);
5784 	} else {
5785 		ASSERT(ipst->ips_mld_timeout_id != 0);
5786 		ipst->ips_mld_timeout_id = 0;
5787 	}
5788 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5789 	if (ret == -1) {
5790 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5791 	} else {
5792 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5793 		ipst->ips_mld_slowtimeout_id = 0;
5794 	}
5795 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5796 	if (ret == -1) {
5797 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5798 	} else {
5799 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5800 		ipst->ips_ip_ire_expire_id = 0;
5801 	}
5802 
5803 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5804 	mutex_destroy(&ipst->ips_mld_timer_lock);
5805 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5806 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5807 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5808 	rw_destroy(&ipst->ips_ill_g_lock);
5809 
5810 	ip_ire_fini(ipst);
5811 	ip6_asp_free(ipst);
5812 	conn_drain_fini(ipst);
5813 	ipcl_destroy(ipst);
5814 
5815 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5816 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5817 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5818 	ipst->ips_ndp4 = NULL;
5819 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5820 	ipst->ips_ndp6 = NULL;
5821 
5822 	if (ipst->ips_loopback_ksp != NULL) {
5823 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5824 		ipst->ips_loopback_ksp = NULL;
5825 	}
5826 
5827 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5828 	ipst->ips_phyint_g_list = NULL;
5829 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5830 	ipst->ips_ill_g_heads = NULL;
5831 
5832 	kmem_free(ipst, sizeof (*ipst));
5833 }
5834 
5835 /*
5836  * This function is called from the TSD destructor, and is used to debug
5837  * reference count issues in IP. See block comment in <inet/ip_if.h> for
5838  * details.
5839  */
5840 static void
5841 ip_thread_exit(void *phash)
5842 {
5843 	th_hash_t *thh = phash;
5844 
5845 	rw_enter(&ip_thread_rwlock, RW_WRITER);
5846 	list_remove(&ip_thread_list, thh);
5847 	rw_exit(&ip_thread_rwlock);
5848 	mod_hash_destroy_hash(thh->thh_hash);
5849 	kmem_free(thh, sizeof (*thh));
5850 }
5851 
5852 /*
5853  * Called when the IP kernel module is loaded into the kernel
5854  */
5855 void
5856 ip_ddi_init(void)
5857 {
5858 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
5859 
5860 	/*
5861 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5862 	 * initial devices: ip, ip6, tcp, tcp6.
5863 	 */
5864 	if ((ip_minor_arena = inet_minor_create("ip_minor_arena",
5865 	    INET_MIN_DEV + 2, KM_SLEEP)) == NULL) {
5866 		cmn_err(CE_PANIC,
5867 		    "ip_ddi_init: ip_minor_arena creation failed\n");
5868 	}
5869 
5870 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5871 
5872 	ipcl_g_init();
5873 	ip_ire_g_init();
5874 	ip_net_g_init();
5875 
5876 #ifdef DEBUG
5877 	tsd_create(&ip_thread_data, ip_thread_exit);
5878 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
5879 	list_create(&ip_thread_list, sizeof (th_hash_t),
5880 	    offsetof(th_hash_t, thh_link));
5881 #endif
5882 
5883 	/*
5884 	 * We want to be informed each time a stack is created or
5885 	 * destroyed in the kernel, so we can maintain the
5886 	 * set of udp_stack_t's.
5887 	 */
5888 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
5889 	    ip_stack_fini);
5890 
5891 	ipsec_policy_g_init();
5892 	tcp_ddi_g_init();
5893 	sctp_ddi_g_init();
5894 
5895 	tnet_init();
5896 
5897 	udp_ddi_init();
5898 	rts_ddi_init();
5899 	icmp_ddi_init();
5900 }
5901 
5902 /*
5903  * Initialize the IP stack instance.
5904  */
5905 static void *
5906 ip_stack_init(netstackid_t stackid, netstack_t *ns)
5907 {
5908 	ip_stack_t	*ipst;
5909 	ipparam_t	*pa;
5910 	ipndp_t		*na;
5911 
5912 #ifdef NS_DEBUG
5913 	printf("ip_stack_init(stack %d)\n", stackid);
5914 #endif
5915 
5916 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
5917 	ipst->ips_netstack = ns;
5918 
5919 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
5920 	    KM_SLEEP);
5921 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
5922 	    KM_SLEEP);
5923 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5924 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5925 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5926 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5927 
5928 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5929 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5930 	ipst->ips_igmp_deferred_next = INFINITY;
5931 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5932 	ipst->ips_mld_deferred_next = INFINITY;
5933 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5934 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5935 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
5936 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
5937 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
5938 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
5939 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
5940 
5941 	ipcl_init(ipst);
5942 	ip_ire_init(ipst);
5943 	ip6_asp_init(ipst);
5944 	ipif_init(ipst);
5945 	conn_drain_init(ipst);
5946 	ip_mrouter_stack_init(ipst);
5947 
5948 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
5949 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
5950 
5951 	ipst->ips_ip_multirt_log_interval = 1000;
5952 
5953 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
5954 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
5955 	ipst->ips_ill_index = 1;
5956 
5957 	ipst->ips_saved_ip_g_forward = -1;
5958 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
5959 
5960 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
5961 	ipst->ips_param_arr = pa;
5962 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
5963 
5964 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
5965 	ipst->ips_ndp_arr = na;
5966 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5967 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
5968 	    (caddr_t)&ipst->ips_ip_g_forward;
5969 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
5970 	    (caddr_t)&ipst->ips_ipv6_forward;
5971 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
5972 	    "ip_cgtp_filter") == 0);
5973 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
5974 	    (caddr_t)&ipst->ips_ip_cgtp_filter;
5975 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_name,
5976 	    "ipmp_hook_emulation") == 0);
5977 	ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_data =
5978 	    (caddr_t)&ipst->ips_ipmp_hook_emulation;
5979 
5980 	(void) ip_param_register(&ipst->ips_ip_g_nd,
5981 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
5982 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
5983 
5984 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
5985 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
5986 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
5987 	ipst->ips_ip6_kstat =
5988 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
5989 
5990 	ipst->ips_ipmp_enable_failback = B_TRUE;
5991 
5992 	ipst->ips_ip_src_id = 1;
5993 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
5994 
5995 	ip_net_init(ipst, ns);
5996 	ipv4_hook_init(ipst);
5997 	ipv6_hook_init(ipst);
5998 
5999 	return (ipst);
6000 }
6001 
6002 /*
6003  * Allocate and initialize a DLPI template of the specified length.  (May be
6004  * called as writer.)
6005  */
6006 mblk_t *
6007 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
6008 {
6009 	mblk_t	*mp;
6010 
6011 	mp = allocb(len, BPRI_MED);
6012 	if (!mp)
6013 		return (NULL);
6014 
6015 	/*
6016 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
6017 	 * of which we don't seem to use) are sent with M_PCPROTO, and
6018 	 * that other DLPI are M_PROTO.
6019 	 */
6020 	if (prim == DL_INFO_REQ) {
6021 		mp->b_datap->db_type = M_PCPROTO;
6022 	} else {
6023 		mp->b_datap->db_type = M_PROTO;
6024 	}
6025 
6026 	mp->b_wptr = mp->b_rptr + len;
6027 	bzero(mp->b_rptr, len);
6028 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6029 	return (mp);
6030 }
6031 
6032 const char *
6033 dlpi_prim_str(int prim)
6034 {
6035 	switch (prim) {
6036 	case DL_INFO_REQ:	return ("DL_INFO_REQ");
6037 	case DL_INFO_ACK:	return ("DL_INFO_ACK");
6038 	case DL_ATTACH_REQ:	return ("DL_ATTACH_REQ");
6039 	case DL_DETACH_REQ:	return ("DL_DETACH_REQ");
6040 	case DL_BIND_REQ:	return ("DL_BIND_REQ");
6041 	case DL_BIND_ACK:	return ("DL_BIND_ACK");
6042 	case DL_UNBIND_REQ:	return ("DL_UNBIND_REQ");
6043 	case DL_OK_ACK:		return ("DL_OK_ACK");
6044 	case DL_ERROR_ACK:	return ("DL_ERROR_ACK");
6045 	case DL_ENABMULTI_REQ:	return ("DL_ENABMULTI_REQ");
6046 	case DL_DISABMULTI_REQ:	return ("DL_DISABMULTI_REQ");
6047 	case DL_PROMISCON_REQ:	return ("DL_PROMISCON_REQ");
6048 	case DL_PROMISCOFF_REQ:	return ("DL_PROMISCOFF_REQ");
6049 	case DL_UNITDATA_REQ:	return ("DL_UNITDATA_REQ");
6050 	case DL_UNITDATA_IND:	return ("DL_UNITDATA_IND");
6051 	case DL_UDERROR_IND:	return ("DL_UDERROR_IND");
6052 	case DL_PHYS_ADDR_REQ:	return ("DL_PHYS_ADDR_REQ");
6053 	case DL_PHYS_ADDR_ACK:	return ("DL_PHYS_ADDR_ACK");
6054 	case DL_SET_PHYS_ADDR_REQ:	return ("DL_SET_PHYS_ADDR_REQ");
6055 	case DL_NOTIFY_REQ:	return ("DL_NOTIFY_REQ");
6056 	case DL_NOTIFY_ACK:	return ("DL_NOTIFY_ACK");
6057 	case DL_NOTIFY_IND:	return ("DL_NOTIFY_IND");
6058 	case DL_CAPABILITY_REQ:	return ("DL_CAPABILITY_REQ");
6059 	case DL_CAPABILITY_ACK:	return ("DL_CAPABILITY_ACK");
6060 	case DL_CONTROL_REQ:	return ("DL_CONTROL_REQ");
6061 	case DL_CONTROL_ACK:	return ("DL_CONTROL_ACK");
6062 	default:		return ("<unknown primitive>");
6063 	}
6064 }
6065 
6066 const char *
6067 dlpi_err_str(int err)
6068 {
6069 	switch (err) {
6070 	case DL_ACCESS:		return ("DL_ACCESS");
6071 	case DL_BADADDR:	return ("DL_BADADDR");
6072 	case DL_BADCORR:	return ("DL_BADCORR");
6073 	case DL_BADDATA:	return ("DL_BADDATA");
6074 	case DL_BADPPA:		return ("DL_BADPPA");
6075 	case DL_BADPRIM:	return ("DL_BADPRIM");
6076 	case DL_BADQOSPARAM:	return ("DL_BADQOSPARAM");
6077 	case DL_BADQOSTYPE:	return ("DL_BADQOSTYPE");
6078 	case DL_BADSAP:		return ("DL_BADSAP");
6079 	case DL_BADTOKEN:	return ("DL_BADTOKEN");
6080 	case DL_BOUND:		return ("DL_BOUND");
6081 	case DL_INITFAILED:	return ("DL_INITFAILED");
6082 	case DL_NOADDR:		return ("DL_NOADDR");
6083 	case DL_NOTINIT:	return ("DL_NOTINIT");
6084 	case DL_OUTSTATE:	return ("DL_OUTSTATE");
6085 	case DL_SYSERR:		return ("DL_SYSERR");
6086 	case DL_UNSUPPORTED:	return ("DL_UNSUPPORTED");
6087 	case DL_UNDELIVERABLE:	return ("DL_UNDELIVERABLE");
6088 	case DL_NOTSUPPORTED :	return ("DL_NOTSUPPORTED ");
6089 	case DL_TOOMANY:	return ("DL_TOOMANY");
6090 	case DL_NOTENAB:	return ("DL_NOTENAB");
6091 	case DL_BUSY:		return ("DL_BUSY");
6092 	case DL_NOAUTO:		return ("DL_NOAUTO");
6093 	case DL_NOXIDAUTO:	return ("DL_NOXIDAUTO");
6094 	case DL_NOTESTAUTO:	return ("DL_NOTESTAUTO");
6095 	case DL_XIDAUTO:	return ("DL_XIDAUTO");
6096 	case DL_TESTAUTO:	return ("DL_TESTAUTO");
6097 	case DL_PENDING:	return ("DL_PENDING");
6098 	default:		return ("<unknown error>");
6099 	}
6100 }
6101 
6102 /*
6103  * Debug formatting routine.  Returns a character string representation of the
6104  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6105  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6106  *
6107  * Once the ndd table-printing interfaces are removed, this can be changed to
6108  * standard dotted-decimal form.
6109  */
6110 char *
6111 ip_dot_addr(ipaddr_t addr, char *buf)
6112 {
6113 	uint8_t *ap = (uint8_t *)&addr;
6114 
6115 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6116 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6117 	return (buf);
6118 }
6119 
6120 /*
6121  * Write the given MAC address as a printable string in the usual colon-
6122  * separated format.
6123  */
6124 const char *
6125 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6126 {
6127 	char *bp;
6128 
6129 	if (alen == 0 || buflen < 4)
6130 		return ("?");
6131 	bp = buf;
6132 	for (;;) {
6133 		/*
6134 		 * If there are more MAC address bytes available, but we won't
6135 		 * have any room to print them, then add "..." to the string
6136 		 * instead.  See below for the 'magic number' explanation.
6137 		 */
6138 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6139 			(void) strcpy(bp, "...");
6140 			break;
6141 		}
6142 		(void) sprintf(bp, "%02x", *addr++);
6143 		bp += 2;
6144 		if (--alen == 0)
6145 			break;
6146 		*bp++ = ':';
6147 		buflen -= 3;
6148 		/*
6149 		 * At this point, based on the first 'if' statement above,
6150 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6151 		 * buflen >= 4.  The first case leaves room for the final "xx"
6152 		 * number and trailing NUL byte.  The second leaves room for at
6153 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6154 		 * that statement.
6155 		 */
6156 	}
6157 	return (buf);
6158 }
6159 
6160 /*
6161  * Send an ICMP error after patching up the packet appropriately.  Returns
6162  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6163  */
6164 static boolean_t
6165 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6166     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6167     zoneid_t zoneid, ip_stack_t *ipst)
6168 {
6169 	ipha_t *ipha;
6170 	mblk_t *first_mp;
6171 	boolean_t secure;
6172 	unsigned char db_type;
6173 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6174 
6175 	first_mp = mp;
6176 	if (mctl_present) {
6177 		mp = mp->b_cont;
6178 		secure = ipsec_in_is_secure(first_mp);
6179 		ASSERT(mp != NULL);
6180 	} else {
6181 		/*
6182 		 * If this is an ICMP error being reported - which goes
6183 		 * up as M_CTLs, we need to convert them to M_DATA till
6184 		 * we finish checking with global policy because
6185 		 * ipsec_check_global_policy() assumes M_DATA as clear
6186 		 * and M_CTL as secure.
6187 		 */
6188 		db_type = DB_TYPE(mp);
6189 		DB_TYPE(mp) = M_DATA;
6190 		secure = B_FALSE;
6191 	}
6192 	/*
6193 	 * We are generating an icmp error for some inbound packet.
6194 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6195 	 * Before we generate an error, check with global policy
6196 	 * to see whether this is allowed to enter the system. As
6197 	 * there is no "conn", we are checking with global policy.
6198 	 */
6199 	ipha = (ipha_t *)mp->b_rptr;
6200 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6201 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6202 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6203 		if (first_mp == NULL)
6204 			return (B_FALSE);
6205 	}
6206 
6207 	if (!mctl_present)
6208 		DB_TYPE(mp) = db_type;
6209 
6210 	if (flags & IP_FF_SEND_ICMP) {
6211 		if (flags & IP_FF_HDR_COMPLETE) {
6212 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6213 				freemsg(first_mp);
6214 				return (B_TRUE);
6215 			}
6216 		}
6217 		if (flags & IP_FF_CKSUM) {
6218 			/*
6219 			 * Have to correct checksum since
6220 			 * the packet might have been
6221 			 * fragmented and the reassembly code in ip_rput
6222 			 * does not restore the IP checksum.
6223 			 */
6224 			ipha->ipha_hdr_checksum = 0;
6225 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6226 		}
6227 		switch (icmp_type) {
6228 		case ICMP_DEST_UNREACHABLE:
6229 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6230 			    ipst);
6231 			break;
6232 		default:
6233 			freemsg(first_mp);
6234 			break;
6235 		}
6236 	} else {
6237 		freemsg(first_mp);
6238 		return (B_FALSE);
6239 	}
6240 
6241 	return (B_TRUE);
6242 }
6243 
6244 /*
6245  * Used to send an ICMP error message when a packet is received for
6246  * a protocol that is not supported. The mblk passed as argument
6247  * is consumed by this function.
6248  */
6249 void
6250 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6251     ip_stack_t *ipst)
6252 {
6253 	mblk_t *mp;
6254 	ipha_t *ipha;
6255 	ill_t *ill;
6256 	ipsec_in_t *ii;
6257 
6258 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6259 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6260 
6261 	mp = ipsec_mp->b_cont;
6262 	ipsec_mp->b_cont = NULL;
6263 	ipha = (ipha_t *)mp->b_rptr;
6264 	/* Get ill from index in ipsec_in_t. */
6265 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6266 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6267 	    ipst);
6268 	if (ill != NULL) {
6269 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6270 			if (ip_fanout_send_icmp(q, mp, flags,
6271 			    ICMP_DEST_UNREACHABLE,
6272 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6273 				BUMP_MIB(ill->ill_ip_mib,
6274 				    ipIfStatsInUnknownProtos);
6275 			}
6276 		} else {
6277 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6278 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6279 			    0, B_FALSE, zoneid, ipst)) {
6280 				BUMP_MIB(ill->ill_ip_mib,
6281 				    ipIfStatsInUnknownProtos);
6282 			}
6283 		}
6284 		ill_refrele(ill);
6285 	} else { /* re-link for the freemsg() below. */
6286 		ipsec_mp->b_cont = mp;
6287 	}
6288 
6289 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6290 	freemsg(ipsec_mp);
6291 }
6292 
6293 /*
6294  * See if the inbound datagram has had IPsec processing applied to it.
6295  */
6296 boolean_t
6297 ipsec_in_is_secure(mblk_t *ipsec_mp)
6298 {
6299 	ipsec_in_t *ii;
6300 
6301 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6302 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6303 
6304 	if (ii->ipsec_in_loopback) {
6305 		return (ii->ipsec_in_secure);
6306 	} else {
6307 		return (ii->ipsec_in_ah_sa != NULL ||
6308 		    ii->ipsec_in_esp_sa != NULL ||
6309 		    ii->ipsec_in_decaps);
6310 	}
6311 }
6312 
6313 /*
6314  * Handle protocols with which IP is less intimate.  There
6315  * can be more than one stream bound to a particular
6316  * protocol.  When this is the case, normally each one gets a copy
6317  * of any incoming packets.
6318  *
6319  * IPsec NOTE :
6320  *
6321  * Don't allow a secure packet going up a non-secure connection.
6322  * We don't allow this because
6323  *
6324  * 1) Reply might go out in clear which will be dropped at
6325  *    the sending side.
6326  * 2) If the reply goes out in clear it will give the
6327  *    adversary enough information for getting the key in
6328  *    most of the cases.
6329  *
6330  * Moreover getting a secure packet when we expect clear
6331  * implies that SA's were added without checking for
6332  * policy on both ends. This should not happen once ISAKMP
6333  * is used to negotiate SAs as SAs will be added only after
6334  * verifying the policy.
6335  *
6336  * NOTE : If the packet was tunneled and not multicast we only send
6337  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6338  * back to delivering packets to AF_INET6 raw sockets.
6339  *
6340  * IPQoS Notes:
6341  * Once we have determined the client, invoke IPPF processing.
6342  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6343  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6344  * ip_policy will be false.
6345  *
6346  * Zones notes:
6347  * Currently only applications in the global zone can create raw sockets for
6348  * protocols other than ICMP. So unlike the broadcast / multicast case of
6349  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6350  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6351  */
6352 static void
6353 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6354     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6355     zoneid_t zoneid)
6356 {
6357 	queue_t	*rq;
6358 	mblk_t	*mp1, *first_mp1;
6359 	uint_t	protocol = ipha->ipha_protocol;
6360 	ipaddr_t dst;
6361 	boolean_t one_only;
6362 	mblk_t *first_mp = mp;
6363 	boolean_t secure;
6364 	uint32_t ill_index;
6365 	conn_t	*connp, *first_connp, *next_connp;
6366 	connf_t	*connfp;
6367 	boolean_t shared_addr;
6368 	mib2_ipIfStatsEntry_t *mibptr;
6369 	ip_stack_t *ipst = recv_ill->ill_ipst;
6370 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6371 
6372 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6373 	if (mctl_present) {
6374 		mp = first_mp->b_cont;
6375 		secure = ipsec_in_is_secure(first_mp);
6376 		ASSERT(mp != NULL);
6377 	} else {
6378 		secure = B_FALSE;
6379 	}
6380 	dst = ipha->ipha_dst;
6381 	/*
6382 	 * If the packet was tunneled and not multicast we only send to it
6383 	 * the first match.
6384 	 */
6385 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6386 	    !CLASSD(dst));
6387 
6388 	shared_addr = (zoneid == ALL_ZONES);
6389 	if (shared_addr) {
6390 		/*
6391 		 * We don't allow multilevel ports for raw IP, so no need to
6392 		 * check for that here.
6393 		 */
6394 		zoneid = tsol_packet_to_zoneid(mp);
6395 	}
6396 
6397 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6398 	mutex_enter(&connfp->connf_lock);
6399 	connp = connfp->connf_head;
6400 	for (connp = connfp->connf_head; connp != NULL;
6401 	    connp = connp->conn_next) {
6402 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6403 		    zoneid) &&
6404 		    (!is_system_labeled() ||
6405 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6406 		    connp))) {
6407 			break;
6408 		}
6409 	}
6410 
6411 	if (connp == NULL || connp->conn_upq == NULL) {
6412 		/*
6413 		 * No one bound to these addresses.  Is
6414 		 * there a client that wants all
6415 		 * unclaimed datagrams?
6416 		 */
6417 		mutex_exit(&connfp->connf_lock);
6418 		/*
6419 		 * Check for IPPROTO_ENCAP...
6420 		 */
6421 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6422 			/*
6423 			 * If an IPsec mblk is here on a multicast
6424 			 * tunnel (using ip_mroute stuff), check policy here,
6425 			 * THEN ship off to ip_mroute_decap().
6426 			 *
6427 			 * BTW,  If I match a configured IP-in-IP
6428 			 * tunnel, this path will not be reached, and
6429 			 * ip_mroute_decap will never be called.
6430 			 */
6431 			first_mp = ipsec_check_global_policy(first_mp, connp,
6432 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6433 			if (first_mp != NULL) {
6434 				if (mctl_present)
6435 					freeb(first_mp);
6436 				ip_mroute_decap(q, mp, ill);
6437 			} /* Else we already freed everything! */
6438 		} else {
6439 			/*
6440 			 * Otherwise send an ICMP protocol unreachable.
6441 			 */
6442 			if (ip_fanout_send_icmp(q, first_mp, flags,
6443 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6444 			    mctl_present, zoneid, ipst)) {
6445 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6446 			}
6447 		}
6448 		return;
6449 	}
6450 	CONN_INC_REF(connp);
6451 	first_connp = connp;
6452 
6453 	/*
6454 	 * Only send message to one tunnel driver by immediately
6455 	 * terminating the loop.
6456 	 */
6457 	connp = one_only ? NULL : connp->conn_next;
6458 
6459 	for (;;) {
6460 		while (connp != NULL) {
6461 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6462 			    flags, zoneid) &&
6463 			    (!is_system_labeled() ||
6464 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6465 			    shared_addr, connp)))
6466 				break;
6467 			connp = connp->conn_next;
6468 		}
6469 
6470 		/*
6471 		 * Copy the packet.
6472 		 */
6473 		if (connp == NULL || connp->conn_upq == NULL ||
6474 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6475 		    ((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6476 			/*
6477 			 * No more interested clients or memory
6478 			 * allocation failed
6479 			 */
6480 			connp = first_connp;
6481 			break;
6482 		}
6483 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6484 		CONN_INC_REF(connp);
6485 		mutex_exit(&connfp->connf_lock);
6486 		rq = connp->conn_rq;
6487 		if (!canputnext(rq)) {
6488 			if (flags & IP_FF_RAWIP) {
6489 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6490 			} else {
6491 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6492 			}
6493 
6494 			freemsg(first_mp1);
6495 		} else {
6496 			/*
6497 			 * Don't enforce here if we're an actual tunnel -
6498 			 * let "tun" do it instead.
6499 			 */
6500 			if (!IPCL_IS_IPTUN(connp) &&
6501 			    (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6502 			    secure)) {
6503 				first_mp1 = ipsec_check_inbound_policy
6504 				    (first_mp1, connp, ipha, NULL,
6505 				    mctl_present);
6506 			}
6507 			if (first_mp1 != NULL) {
6508 				int in_flags = 0;
6509 				/*
6510 				 * ip_fanout_proto also gets called from
6511 				 * icmp_inbound_error_fanout, in which case
6512 				 * the msg type is M_CTL.  Don't add info
6513 				 * in this case for the time being. In future
6514 				 * when there is a need for knowing the
6515 				 * inbound iface index for ICMP error msgs,
6516 				 * then this can be changed.
6517 				 */
6518 				if (connp->conn_recvif)
6519 					in_flags = IPF_RECVIF;
6520 				/*
6521 				 * The ULP may support IP_RECVPKTINFO for both
6522 				 * IP v4 and v6 so pass the appropriate argument
6523 				 * based on conn IP version.
6524 				 */
6525 				if (connp->conn_ip_recvpktinfo) {
6526 					if (connp->conn_af_isv6) {
6527 						/*
6528 						 * V6 only needs index
6529 						 */
6530 						in_flags |= IPF_RECVIF;
6531 					} else {
6532 						/*
6533 						 * V4 needs index +
6534 						 * matching address.
6535 						 */
6536 						in_flags |= IPF_RECVADDR;
6537 					}
6538 				}
6539 				if ((in_flags != 0) &&
6540 				    (mp->b_datap->db_type != M_CTL)) {
6541 					/*
6542 					 * the actual data will be
6543 					 * contained in b_cont upon
6544 					 * successful return of the
6545 					 * following call else
6546 					 * original mblk is returned
6547 					 */
6548 					ASSERT(recv_ill != NULL);
6549 					mp1 = ip_add_info(mp1, recv_ill,
6550 					    in_flags, IPCL_ZONEID(connp), ipst);
6551 				}
6552 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6553 				if (mctl_present)
6554 					freeb(first_mp1);
6555 				(connp->conn_recv)(connp, mp1, NULL);
6556 			}
6557 		}
6558 		mutex_enter(&connfp->connf_lock);
6559 		/* Follow the next pointer before releasing the conn. */
6560 		next_connp = connp->conn_next;
6561 		CONN_DEC_REF(connp);
6562 		connp = next_connp;
6563 	}
6564 
6565 	/* Last one.  Send it upstream. */
6566 	mutex_exit(&connfp->connf_lock);
6567 
6568 	/*
6569 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6570 	 * will be set to false.
6571 	 */
6572 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6573 		ill_index = ill->ill_phyint->phyint_ifindex;
6574 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6575 		if (mp == NULL) {
6576 			CONN_DEC_REF(connp);
6577 			if (mctl_present) {
6578 				freeb(first_mp);
6579 			}
6580 			return;
6581 		}
6582 	}
6583 
6584 	rq = connp->conn_rq;
6585 	if (!canputnext(rq)) {
6586 		if (flags & IP_FF_RAWIP) {
6587 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6588 		} else {
6589 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6590 		}
6591 
6592 		freemsg(first_mp);
6593 	} else {
6594 		if (IPCL_IS_IPTUN(connp)) {
6595 			/*
6596 			 * Tunneled packet.  We enforce policy in the tunnel
6597 			 * module itself.
6598 			 *
6599 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6600 			 * a policy check.
6601 			 * FIXME to use conn_recv for tun later.
6602 			 */
6603 			putnext(rq, first_mp);
6604 			CONN_DEC_REF(connp);
6605 			return;
6606 		}
6607 
6608 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6609 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6610 			    ipha, NULL, mctl_present);
6611 		}
6612 
6613 		if (first_mp != NULL) {
6614 			int in_flags = 0;
6615 
6616 			/*
6617 			 * ip_fanout_proto also gets called
6618 			 * from icmp_inbound_error_fanout, in
6619 			 * which case the msg type is M_CTL.
6620 			 * Don't add info in this case for time
6621 			 * being. In future when there is a
6622 			 * need for knowing the inbound iface
6623 			 * index for ICMP error msgs, then this
6624 			 * can be changed
6625 			 */
6626 			if (connp->conn_recvif)
6627 				in_flags = IPF_RECVIF;
6628 			if (connp->conn_ip_recvpktinfo) {
6629 				if (connp->conn_af_isv6) {
6630 					/*
6631 					 * V6 only needs index
6632 					 */
6633 					in_flags |= IPF_RECVIF;
6634 				} else {
6635 					/*
6636 					 * V4 needs index +
6637 					 * matching address.
6638 					 */
6639 					in_flags |= IPF_RECVADDR;
6640 				}
6641 			}
6642 			if ((in_flags != 0) &&
6643 			    (mp->b_datap->db_type != M_CTL)) {
6644 
6645 				/*
6646 				 * the actual data will be contained in
6647 				 * b_cont upon successful return
6648 				 * of the following call else original
6649 				 * mblk is returned
6650 				 */
6651 				ASSERT(recv_ill != NULL);
6652 				mp = ip_add_info(mp, recv_ill,
6653 				    in_flags, IPCL_ZONEID(connp), ipst);
6654 			}
6655 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6656 			(connp->conn_recv)(connp, mp, NULL);
6657 			if (mctl_present)
6658 				freeb(first_mp);
6659 		}
6660 	}
6661 	CONN_DEC_REF(connp);
6662 }
6663 
6664 /*
6665  * Fanout for TCP packets
6666  * The caller puts <fport, lport> in the ports parameter.
6667  *
6668  * IPQoS Notes
6669  * Before sending it to the client, invoke IPPF processing.
6670  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6671  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6672  * ip_policy is false.
6673  */
6674 static void
6675 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6676     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6677 {
6678 	mblk_t  *first_mp;
6679 	boolean_t secure;
6680 	uint32_t ill_index;
6681 	int	ip_hdr_len;
6682 	tcph_t	*tcph;
6683 	boolean_t syn_present = B_FALSE;
6684 	conn_t	*connp;
6685 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6686 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6687 
6688 	ASSERT(recv_ill != NULL);
6689 
6690 	first_mp = mp;
6691 	if (mctl_present) {
6692 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6693 		mp = first_mp->b_cont;
6694 		secure = ipsec_in_is_secure(first_mp);
6695 		ASSERT(mp != NULL);
6696 	} else {
6697 		secure = B_FALSE;
6698 	}
6699 
6700 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6701 
6702 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6703 	    zoneid, ipst)) == NULL) {
6704 		/*
6705 		 * No connected connection or listener. Send a
6706 		 * TH_RST via tcp_xmit_listeners_reset.
6707 		 */
6708 
6709 		/* Initiate IPPf processing, if needed. */
6710 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6711 			uint32_t ill_index;
6712 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6713 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6714 			if (first_mp == NULL)
6715 				return;
6716 		}
6717 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6718 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6719 		    zoneid));
6720 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6721 		    ipst->ips_netstack->netstack_tcp, NULL);
6722 		return;
6723 	}
6724 
6725 	/*
6726 	 * Allocate the SYN for the TCP connection here itself
6727 	 */
6728 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6729 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6730 		if (IPCL_IS_TCP(connp)) {
6731 			squeue_t *sqp;
6732 
6733 			/*
6734 			 * For fused tcp loopback, assign the eager's
6735 			 * squeue to be that of the active connect's.
6736 			 * Note that we don't check for IP_FF_LOOPBACK
6737 			 * here since this routine gets called only
6738 			 * for loopback (unlike the IPv6 counterpart).
6739 			 */
6740 			ASSERT(Q_TO_CONN(q) != NULL);
6741 			if (do_tcp_fusion &&
6742 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6743 			    !secure &&
6744 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy &&
6745 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6746 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6747 				sqp = Q_TO_CONN(q)->conn_sqp;
6748 			} else {
6749 				sqp = IP_SQUEUE_GET(lbolt);
6750 			}
6751 
6752 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6753 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6754 			syn_present = B_TRUE;
6755 		}
6756 	}
6757 
6758 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6759 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6760 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6761 		if ((flags & TH_RST) || (flags & TH_URG)) {
6762 			CONN_DEC_REF(connp);
6763 			freemsg(first_mp);
6764 			return;
6765 		}
6766 		if (flags & TH_ACK) {
6767 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6768 			    ipst->ips_netstack->netstack_tcp, connp);
6769 			CONN_DEC_REF(connp);
6770 			return;
6771 		}
6772 
6773 		CONN_DEC_REF(connp);
6774 		freemsg(first_mp);
6775 		return;
6776 	}
6777 
6778 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6779 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6780 		    NULL, mctl_present);
6781 		if (first_mp == NULL) {
6782 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6783 			CONN_DEC_REF(connp);
6784 			return;
6785 		}
6786 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6787 			ASSERT(syn_present);
6788 			if (mctl_present) {
6789 				ASSERT(first_mp != mp);
6790 				first_mp->b_datap->db_struioflag |=
6791 				    STRUIO_POLICY;
6792 			} else {
6793 				ASSERT(first_mp == mp);
6794 				mp->b_datap->db_struioflag &=
6795 				    ~STRUIO_EAGER;
6796 				mp->b_datap->db_struioflag |=
6797 				    STRUIO_POLICY;
6798 			}
6799 		} else {
6800 			/*
6801 			 * Discard first_mp early since we're dealing with a
6802 			 * fully-connected conn_t and tcp doesn't do policy in
6803 			 * this case.
6804 			 */
6805 			if (mctl_present) {
6806 				freeb(first_mp);
6807 				mctl_present = B_FALSE;
6808 			}
6809 			first_mp = mp;
6810 		}
6811 	}
6812 
6813 	/*
6814 	 * Initiate policy processing here if needed. If we get here from
6815 	 * icmp_inbound_error_fanout, ip_policy is false.
6816 	 */
6817 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6818 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6819 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6820 		if (mp == NULL) {
6821 			CONN_DEC_REF(connp);
6822 			if (mctl_present)
6823 				freeb(first_mp);
6824 			return;
6825 		} else if (mctl_present) {
6826 			ASSERT(first_mp != mp);
6827 			first_mp->b_cont = mp;
6828 		} else {
6829 			first_mp = mp;
6830 		}
6831 	}
6832 
6833 
6834 
6835 	/* Handle socket options. */
6836 	if (!syn_present &&
6837 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6838 		/* Add header */
6839 		ASSERT(recv_ill != NULL);
6840 		/*
6841 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6842 		 * IPF_RECVIF.
6843 		 */
6844 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6845 		    ipst);
6846 		if (mp == NULL) {
6847 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6848 			CONN_DEC_REF(connp);
6849 			if (mctl_present)
6850 				freeb(first_mp);
6851 			return;
6852 		} else if (mctl_present) {
6853 			/*
6854 			 * ip_add_info might return a new mp.
6855 			 */
6856 			ASSERT(first_mp != mp);
6857 			first_mp->b_cont = mp;
6858 		} else {
6859 			first_mp = mp;
6860 		}
6861 	}
6862 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6863 	if (IPCL_IS_TCP(connp)) {
6864 		/* do not drain, certain use cases can blow the stack */
6865 		squeue_enter_nodrain(connp->conn_sqp, first_mp,
6866 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
6867 	} else {
6868 		/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
6869 		(connp->conn_recv)(connp, first_mp, NULL);
6870 		CONN_DEC_REF(connp);
6871 	}
6872 }
6873 
6874 /*
6875  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
6876  * pass it along to ESP if the SPI is non-zero.  Returns TRUE if the mblk
6877  * is not consumed.
6878  *
6879  * One of four things can happen, all of which affect the passed-in mblk:
6880  *
6881  * 1.) ICMP messages that go through here just get returned TRUE.
6882  *
6883  * 2.) The packet is stock UDP and gets its zero-SPI stripped.  Return TRUE.
6884  *
6885  * 3.) The packet is ESP-in-UDP, gets transformed into an equivalent
6886  *     ESP packet, and is passed along to ESP for consumption.  Return FALSE.
6887  *
6888  * 4.) The packet is an ESP-in-UDP Keepalive.  Drop it and return FALSE.
6889  */
6890 static boolean_t
6891 zero_spi_check(queue_t *q, mblk_t *mp, ire_t *ire, ill_t *recv_ill,
6892     ipsec_stack_t *ipss)
6893 {
6894 	int shift, plen, iph_len;
6895 	ipha_t *ipha;
6896 	udpha_t *udpha;
6897 	uint32_t *spi;
6898 	uint8_t *orptr;
6899 	boolean_t udp_pkt, free_ire;
6900 
6901 	if (DB_TYPE(mp) == M_CTL) {
6902 		/*
6903 		 * ICMP message with UDP inside.  Don't bother stripping, just
6904 		 * send it up.
6905 		 *
6906 		 * NOTE: Any app with UDP_NAT_T_ENDPOINT set is probably going
6907 		 * to ignore errors set by ICMP anyway ('cause they might be
6908 		 * forged), but that's the app's decision, not ours.
6909 		 */
6910 
6911 		/* Bunch of reality checks for DEBUG kernels... */
6912 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION);
6913 		ASSERT(((ipha_t *)mp->b_rptr)->ipha_protocol == IPPROTO_ICMP);
6914 
6915 		return (B_TRUE);
6916 	}
6917 
6918 	ipha = (ipha_t *)mp->b_rptr;
6919 	iph_len = IPH_HDR_LENGTH(ipha);
6920 	plen = ntohs(ipha->ipha_length);
6921 
6922 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
6923 		/*
6924 		 * Most likely a keepalive for the benefit of an intervening
6925 		 * NAT.  These aren't for us, per se, so drop it.
6926 		 *
6927 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
6928 		 * byte packets (keepalives are 1-byte), but we'll drop them
6929 		 * also.
6930 		 */
6931 		ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6932 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
6933 		return (B_FALSE);
6934 	}
6935 
6936 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
6937 		/* might as well pull it all up - it might be ESP. */
6938 		if (!pullupmsg(mp, -1)) {
6939 			ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6940 			    DROPPER(ipss, ipds_esp_nomem),
6941 			    &ipss->ipsec_dropper);
6942 			return (B_FALSE);
6943 		}
6944 
6945 		ipha = (ipha_t *)mp->b_rptr;
6946 	}
6947 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
6948 	if (*spi == 0) {
6949 		/* UDP packet - remove 0-spi. */
6950 		shift = sizeof (uint32_t);
6951 	} else {
6952 		/* ESP-in-UDP packet - reduce to ESP. */
6953 		ipha->ipha_protocol = IPPROTO_ESP;
6954 		shift = sizeof (udpha_t);
6955 	}
6956 
6957 	/* Fix IP header */
6958 	ipha->ipha_length = htons(plen - shift);
6959 	ipha->ipha_hdr_checksum = 0;
6960 
6961 	orptr = mp->b_rptr;
6962 	mp->b_rptr += shift;
6963 
6964 	if (*spi == 0) {
6965 		ASSERT((uint8_t *)ipha == orptr);
6966 		udpha = (udpha_t *)(orptr + iph_len);
6967 		udpha->uha_length = htons(plen - shift - iph_len);
6968 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
6969 		udp_pkt = B_TRUE;
6970 	} else {
6971 		udp_pkt = B_FALSE;
6972 	}
6973 	ovbcopy(orptr, orptr + shift, iph_len);
6974 	if (!udp_pkt) /* Punt up for ESP processing. */ {
6975 		ipha = (ipha_t *)(orptr + shift);
6976 
6977 		free_ire = (ire == NULL);
6978 		if (free_ire) {
6979 			/* Re-acquire ire. */
6980 			ire = ire_cache_lookup(ipha->ipha_dst, ALL_ZONES, NULL,
6981 			    ipss->ipsec_netstack->netstack_ip);
6982 			if (ire == NULL || !(ire->ire_type & IRE_LOCAL)) {
6983 				if (ire != NULL)
6984 					ire_refrele(ire);
6985 				/*
6986 				 * Do a regular freemsg(), as this is an IP
6987 				 * error (no local route) not an IPsec one.
6988 				 */
6989 				freemsg(mp);
6990 			}
6991 		}
6992 
6993 		ip_proto_input(q, mp, ipha, ire, recv_ill, B_TRUE);
6994 		if (free_ire)
6995 			ire_refrele(ire);
6996 	}
6997 
6998 	return (udp_pkt);
6999 }
7000 
7001 /*
7002  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
7003  * We are responsible for disposing of mp, such as by freemsg() or putnext()
7004  * Caller is responsible for dropping references to the conn, and freeing
7005  * first_mp.
7006  *
7007  * IPQoS Notes
7008  * Before sending it to the client, invoke IPPF processing. Policy processing
7009  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
7010  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
7011  * ip_wput_local, ip_policy is false.
7012  */
7013 static void
7014 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
7015     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
7016     boolean_t ip_policy)
7017 {
7018 	boolean_t	mctl_present = (first_mp != NULL);
7019 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
7020 	uint32_t	ill_index;
7021 	ip_stack_t	*ipst = recv_ill->ill_ipst;
7022 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
7023 
7024 	ASSERT(ill != NULL);
7025 
7026 	if (mctl_present)
7027 		first_mp->b_cont = mp;
7028 	else
7029 		first_mp = mp;
7030 
7031 	if (CONN_UDP_FLOWCTLD(connp)) {
7032 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
7033 		freemsg(first_mp);
7034 		return;
7035 	}
7036 
7037 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
7038 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
7039 		    NULL, mctl_present);
7040 		if (first_mp == NULL) {
7041 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7042 			return;	/* Freed by ipsec_check_inbound_policy(). */
7043 		}
7044 	}
7045 	if (mctl_present)
7046 		freeb(first_mp);
7047 
7048 	/* Let's hope the compilers utter "branch, predict-not-taken..." ;) */
7049 	if (connp->conn_udp->udp_nat_t_endpoint) {
7050 		if (mctl_present) {
7051 			/* mctl_present *shouldn't* happen. */
7052 			ip_drop_packet(mp, B_TRUE, NULL, NULL,
7053 			    DROPPER(ipss, ipds_esp_nat_t_ipsec),
7054 			    &ipss->ipsec_dropper);
7055 			return;
7056 		}
7057 
7058 		if (!zero_spi_check(ill->ill_rq, mp, NULL, recv_ill, ipss))
7059 			return;
7060 	}
7061 
7062 	/* Handle options. */
7063 	if (connp->conn_recvif)
7064 		in_flags = IPF_RECVIF;
7065 	/*
7066 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
7067 	 * passed to ip_add_info is based on IP version of connp.
7068 	 */
7069 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
7070 		if (connp->conn_af_isv6) {
7071 			/*
7072 			 * V6 only needs index
7073 			 */
7074 			in_flags |= IPF_RECVIF;
7075 		} else {
7076 			/*
7077 			 * V4 needs index + matching address.
7078 			 */
7079 			in_flags |= IPF_RECVADDR;
7080 		}
7081 	}
7082 
7083 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
7084 		in_flags |= IPF_RECVSLLA;
7085 
7086 	/*
7087 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7088 	 * freed if the packet is dropped. The caller will do so.
7089 	 */
7090 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7091 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7092 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7093 		if (mp == NULL) {
7094 			return;
7095 		}
7096 	}
7097 	if ((in_flags != 0) &&
7098 	    (mp->b_datap->db_type != M_CTL)) {
7099 		/*
7100 		 * The actual data will be contained in b_cont
7101 		 * upon successful return of the following call
7102 		 * else original mblk is returned
7103 		 */
7104 		ASSERT(recv_ill != NULL);
7105 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7106 		    ipst);
7107 	}
7108 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7109 	/* Send it upstream */
7110 	(connp->conn_recv)(connp, mp, NULL);
7111 }
7112 
7113 /*
7114  * Fanout for UDP packets.
7115  * The caller puts <fport, lport> in the ports parameter.
7116  *
7117  * If SO_REUSEADDR is set all multicast and broadcast packets
7118  * will be delivered to all streams bound to the same port.
7119  *
7120  * Zones notes:
7121  * Multicast and broadcast packets will be distributed to streams in all zones.
7122  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7123  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7124  * packets. To maintain this behavior with multiple zones, the conns are grouped
7125  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7126  * each zone. If unset, all the following conns in the same zone are skipped.
7127  */
7128 static void
7129 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7130     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7131     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7132 {
7133 	uint32_t	dstport, srcport;
7134 	ipaddr_t	dst;
7135 	mblk_t		*first_mp;
7136 	boolean_t	secure;
7137 	in6_addr_t	v6src;
7138 	conn_t		*connp;
7139 	connf_t		*connfp;
7140 	conn_t		*first_connp;
7141 	conn_t		*next_connp;
7142 	mblk_t		*mp1, *first_mp1;
7143 	ipaddr_t	src;
7144 	zoneid_t	last_zoneid;
7145 	boolean_t	reuseaddr;
7146 	boolean_t	shared_addr;
7147 	ip_stack_t	*ipst;
7148 
7149 	ASSERT(recv_ill != NULL);
7150 	ipst = recv_ill->ill_ipst;
7151 
7152 	first_mp = mp;
7153 	if (mctl_present) {
7154 		mp = first_mp->b_cont;
7155 		first_mp->b_cont = NULL;
7156 		secure = ipsec_in_is_secure(first_mp);
7157 		ASSERT(mp != NULL);
7158 	} else {
7159 		first_mp = NULL;
7160 		secure = B_FALSE;
7161 	}
7162 
7163 	/* Extract ports in net byte order */
7164 	dstport = htons(ntohl(ports) & 0xFFFF);
7165 	srcport = htons(ntohl(ports) >> 16);
7166 	dst = ipha->ipha_dst;
7167 	src = ipha->ipha_src;
7168 
7169 	shared_addr = (zoneid == ALL_ZONES);
7170 	if (shared_addr) {
7171 		/*
7172 		 * No need to handle exclusive-stack zones since ALL_ZONES
7173 		 * only applies to the shared stack.
7174 		 */
7175 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7176 		if (zoneid == ALL_ZONES)
7177 			zoneid = tsol_packet_to_zoneid(mp);
7178 	}
7179 
7180 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7181 	mutex_enter(&connfp->connf_lock);
7182 	connp = connfp->connf_head;
7183 	if (!broadcast && !CLASSD(dst)) {
7184 		/*
7185 		 * Not broadcast or multicast. Send to the one (first)
7186 		 * client we find. No need to check conn_wantpacket()
7187 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7188 		 * IPv4 unicast packets.
7189 		 */
7190 		while ((connp != NULL) &&
7191 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7192 		    !IPCL_ZONE_MATCH(connp, zoneid))) {
7193 			connp = connp->conn_next;
7194 		}
7195 
7196 		if (connp == NULL || connp->conn_upq == NULL)
7197 			goto notfound;
7198 
7199 		if (is_system_labeled() &&
7200 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7201 		    connp))
7202 			goto notfound;
7203 
7204 		CONN_INC_REF(connp);
7205 		mutex_exit(&connfp->connf_lock);
7206 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7207 		    flags, recv_ill, ip_policy);
7208 		IP_STAT(ipst, ip_udp_fannorm);
7209 		CONN_DEC_REF(connp);
7210 		return;
7211 	}
7212 
7213 	/*
7214 	 * Broadcast and multicast case
7215 	 *
7216 	 * Need to check conn_wantpacket().
7217 	 * If SO_REUSEADDR has been set on the first we send the
7218 	 * packet to all clients that have joined the group and
7219 	 * match the port.
7220 	 */
7221 
7222 	while (connp != NULL) {
7223 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7224 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7225 		    (!is_system_labeled() ||
7226 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7227 		    connp)))
7228 			break;
7229 		connp = connp->conn_next;
7230 	}
7231 
7232 	if (connp == NULL || connp->conn_upq == NULL)
7233 		goto notfound;
7234 
7235 	first_connp = connp;
7236 	/*
7237 	 * When SO_REUSEADDR is not set, send the packet only to the first
7238 	 * matching connection in its zone by keeping track of the zoneid.
7239 	 */
7240 	reuseaddr = first_connp->conn_reuseaddr;
7241 	last_zoneid = first_connp->conn_zoneid;
7242 
7243 	CONN_INC_REF(connp);
7244 	connp = connp->conn_next;
7245 	for (;;) {
7246 		while (connp != NULL) {
7247 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7248 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7249 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7250 			    (!is_system_labeled() ||
7251 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7252 			    shared_addr, connp)))
7253 				break;
7254 			connp = connp->conn_next;
7255 		}
7256 		/*
7257 		 * Just copy the data part alone. The mctl part is
7258 		 * needed just for verifying policy and it is never
7259 		 * sent up.
7260 		 */
7261 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7262 		    ((mp1 = copymsg(mp)) == NULL))) {
7263 			/*
7264 			 * No more interested clients or memory
7265 			 * allocation failed
7266 			 */
7267 			connp = first_connp;
7268 			break;
7269 		}
7270 		if (connp->conn_zoneid != last_zoneid) {
7271 			/*
7272 			 * Update the zoneid so that the packet isn't sent to
7273 			 * any more conns in the same zone unless SO_REUSEADDR
7274 			 * is set.
7275 			 */
7276 			reuseaddr = connp->conn_reuseaddr;
7277 			last_zoneid = connp->conn_zoneid;
7278 		}
7279 		if (first_mp != NULL) {
7280 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7281 			    ipsec_info_type == IPSEC_IN);
7282 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7283 			    ipst->ips_netstack);
7284 			if (first_mp1 == NULL) {
7285 				freemsg(mp1);
7286 				connp = first_connp;
7287 				break;
7288 			}
7289 		} else {
7290 			first_mp1 = NULL;
7291 		}
7292 		CONN_INC_REF(connp);
7293 		mutex_exit(&connfp->connf_lock);
7294 		/*
7295 		 * IPQoS notes: We don't send the packet for policy
7296 		 * processing here, will do it for the last one (below).
7297 		 * i.e. we do it per-packet now, but if we do policy
7298 		 * processing per-conn, then we would need to do it
7299 		 * here too.
7300 		 */
7301 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7302 		    ipha, flags, recv_ill, B_FALSE);
7303 		mutex_enter(&connfp->connf_lock);
7304 		/* Follow the next pointer before releasing the conn. */
7305 		next_connp = connp->conn_next;
7306 		IP_STAT(ipst, ip_udp_fanmb);
7307 		CONN_DEC_REF(connp);
7308 		connp = next_connp;
7309 	}
7310 
7311 	/* Last one.  Send it upstream. */
7312 	mutex_exit(&connfp->connf_lock);
7313 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7314 	    recv_ill, ip_policy);
7315 	IP_STAT(ipst, ip_udp_fanmb);
7316 	CONN_DEC_REF(connp);
7317 	return;
7318 
7319 notfound:
7320 
7321 	mutex_exit(&connfp->connf_lock);
7322 	IP_STAT(ipst, ip_udp_fanothers);
7323 	/*
7324 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7325 	 * have already been matched above, since they live in the IPv4
7326 	 * fanout tables. This implies we only need to
7327 	 * check for IPv6 in6addr_any endpoints here.
7328 	 * Thus we compare using ipv6_all_zeros instead of the destination
7329 	 * address, except for the multicast group membership lookup which
7330 	 * uses the IPv4 destination.
7331 	 */
7332 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7333 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7334 	mutex_enter(&connfp->connf_lock);
7335 	connp = connfp->connf_head;
7336 	if (!broadcast && !CLASSD(dst)) {
7337 		while (connp != NULL) {
7338 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7339 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7340 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7341 			    !connp->conn_ipv6_v6only)
7342 				break;
7343 			connp = connp->conn_next;
7344 		}
7345 
7346 		if (connp != NULL && is_system_labeled() &&
7347 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7348 		    connp))
7349 			connp = NULL;
7350 
7351 		if (connp == NULL || connp->conn_upq == NULL) {
7352 			/*
7353 			 * No one bound to this port.  Is
7354 			 * there a client that wants all
7355 			 * unclaimed datagrams?
7356 			 */
7357 			mutex_exit(&connfp->connf_lock);
7358 
7359 			if (mctl_present)
7360 				first_mp->b_cont = mp;
7361 			else
7362 				first_mp = mp;
7363 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7364 			    connf_head != NULL) {
7365 				ip_fanout_proto(q, first_mp, ill, ipha,
7366 				    flags | IP_FF_RAWIP, mctl_present,
7367 				    ip_policy, recv_ill, zoneid);
7368 			} else {
7369 				if (ip_fanout_send_icmp(q, first_mp, flags,
7370 				    ICMP_DEST_UNREACHABLE,
7371 				    ICMP_PORT_UNREACHABLE,
7372 				    mctl_present, zoneid, ipst)) {
7373 					BUMP_MIB(ill->ill_ip_mib,
7374 					    udpIfStatsNoPorts);
7375 				}
7376 			}
7377 			return;
7378 		}
7379 
7380 		CONN_INC_REF(connp);
7381 		mutex_exit(&connfp->connf_lock);
7382 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7383 		    flags, recv_ill, ip_policy);
7384 		CONN_DEC_REF(connp);
7385 		return;
7386 	}
7387 	/*
7388 	 * IPv4 multicast packet being delivered to an AF_INET6
7389 	 * in6addr_any endpoint.
7390 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7391 	 * and not conn_wantpacket_v6() since any multicast membership is
7392 	 * for an IPv4-mapped multicast address.
7393 	 * The packet is sent to all clients in all zones that have joined the
7394 	 * group and match the port.
7395 	 */
7396 	while (connp != NULL) {
7397 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7398 		    srcport, v6src) &&
7399 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7400 		    (!is_system_labeled() ||
7401 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7402 		    connp)))
7403 			break;
7404 		connp = connp->conn_next;
7405 	}
7406 
7407 	if (connp == NULL || connp->conn_upq == NULL) {
7408 		/*
7409 		 * No one bound to this port.  Is
7410 		 * there a client that wants all
7411 		 * unclaimed datagrams?
7412 		 */
7413 		mutex_exit(&connfp->connf_lock);
7414 
7415 		if (mctl_present)
7416 			first_mp->b_cont = mp;
7417 		else
7418 			first_mp = mp;
7419 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7420 		    NULL) {
7421 			ip_fanout_proto(q, first_mp, ill, ipha,
7422 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7423 			    recv_ill, zoneid);
7424 		} else {
7425 			/*
7426 			 * We used to attempt to send an icmp error here, but
7427 			 * since this is known to be a multicast packet
7428 			 * and we don't send icmp errors in response to
7429 			 * multicast, just drop the packet and give up sooner.
7430 			 */
7431 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7432 			freemsg(first_mp);
7433 		}
7434 		return;
7435 	}
7436 
7437 	first_connp = connp;
7438 
7439 	CONN_INC_REF(connp);
7440 	connp = connp->conn_next;
7441 	for (;;) {
7442 		while (connp != NULL) {
7443 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7444 			    ipv6_all_zeros, srcport, v6src) &&
7445 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7446 			    (!is_system_labeled() ||
7447 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7448 			    shared_addr, connp)))
7449 				break;
7450 			connp = connp->conn_next;
7451 		}
7452 		/*
7453 		 * Just copy the data part alone. The mctl part is
7454 		 * needed just for verifying policy and it is never
7455 		 * sent up.
7456 		 */
7457 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7458 		    ((mp1 = copymsg(mp)) == NULL))) {
7459 			/*
7460 			 * No more intested clients or memory
7461 			 * allocation failed
7462 			 */
7463 			connp = first_connp;
7464 			break;
7465 		}
7466 		if (first_mp != NULL) {
7467 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7468 			    ipsec_info_type == IPSEC_IN);
7469 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7470 			    ipst->ips_netstack);
7471 			if (first_mp1 == NULL) {
7472 				freemsg(mp1);
7473 				connp = first_connp;
7474 				break;
7475 			}
7476 		} else {
7477 			first_mp1 = NULL;
7478 		}
7479 		CONN_INC_REF(connp);
7480 		mutex_exit(&connfp->connf_lock);
7481 		/*
7482 		 * IPQoS notes: We don't send the packet for policy
7483 		 * processing here, will do it for the last one (below).
7484 		 * i.e. we do it per-packet now, but if we do policy
7485 		 * processing per-conn, then we would need to do it
7486 		 * here too.
7487 		 */
7488 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7489 		    ipha, flags, recv_ill, B_FALSE);
7490 		mutex_enter(&connfp->connf_lock);
7491 		/* Follow the next pointer before releasing the conn. */
7492 		next_connp = connp->conn_next;
7493 		CONN_DEC_REF(connp);
7494 		connp = next_connp;
7495 	}
7496 
7497 	/* Last one.  Send it upstream. */
7498 	mutex_exit(&connfp->connf_lock);
7499 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7500 	    recv_ill, ip_policy);
7501 	CONN_DEC_REF(connp);
7502 }
7503 
7504 /*
7505  * Complete the ip_wput header so that it
7506  * is possible to generate ICMP
7507  * errors.
7508  */
7509 int
7510 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7511 {
7512 	ire_t *ire;
7513 
7514 	if (ipha->ipha_src == INADDR_ANY) {
7515 		ire = ire_lookup_local(zoneid, ipst);
7516 		if (ire == NULL) {
7517 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7518 			return (1);
7519 		}
7520 		ipha->ipha_src = ire->ire_addr;
7521 		ire_refrele(ire);
7522 	}
7523 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7524 	ipha->ipha_hdr_checksum = 0;
7525 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7526 	return (0);
7527 }
7528 
7529 /*
7530  * Nobody should be sending
7531  * packets up this stream
7532  */
7533 static void
7534 ip_lrput(queue_t *q, mblk_t *mp)
7535 {
7536 	mblk_t *mp1;
7537 
7538 	switch (mp->b_datap->db_type) {
7539 	case M_FLUSH:
7540 		/* Turn around */
7541 		if (*mp->b_rptr & FLUSHW) {
7542 			*mp->b_rptr &= ~FLUSHR;
7543 			qreply(q, mp);
7544 			return;
7545 		}
7546 		break;
7547 	}
7548 	/* Could receive messages that passed through ar_rput */
7549 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7550 		mp1->b_prev = mp1->b_next = NULL;
7551 	freemsg(mp);
7552 }
7553 
7554 /* Nobody should be sending packets down this stream */
7555 /* ARGSUSED */
7556 void
7557 ip_lwput(queue_t *q, mblk_t *mp)
7558 {
7559 	freemsg(mp);
7560 }
7561 
7562 /*
7563  * Move the first hop in any source route to ipha_dst and remove that part of
7564  * the source route.  Called by other protocols.  Errors in option formatting
7565  * are ignored - will be handled by ip_wput_options Return the final
7566  * destination (either ipha_dst or the last entry in a source route.)
7567  */
7568 ipaddr_t
7569 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7570 {
7571 	ipoptp_t	opts;
7572 	uchar_t		*opt;
7573 	uint8_t		optval;
7574 	uint8_t		optlen;
7575 	ipaddr_t	dst;
7576 	int		i;
7577 	ire_t		*ire;
7578 	ip_stack_t	*ipst = ns->netstack_ip;
7579 
7580 	ip2dbg(("ip_massage_options\n"));
7581 	dst = ipha->ipha_dst;
7582 	for (optval = ipoptp_first(&opts, ipha);
7583 	    optval != IPOPT_EOL;
7584 	    optval = ipoptp_next(&opts)) {
7585 		opt = opts.ipoptp_cur;
7586 		switch (optval) {
7587 			uint8_t off;
7588 		case IPOPT_SSRR:
7589 		case IPOPT_LSRR:
7590 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7591 				ip1dbg(("ip_massage_options: bad src route\n"));
7592 				break;
7593 			}
7594 			optlen = opts.ipoptp_len;
7595 			off = opt[IPOPT_OFFSET];
7596 			off--;
7597 		redo_srr:
7598 			if (optlen < IP_ADDR_LEN ||
7599 			    off > optlen - IP_ADDR_LEN) {
7600 				/* End of source route */
7601 				ip1dbg(("ip_massage_options: end of SR\n"));
7602 				break;
7603 			}
7604 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7605 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7606 			    ntohl(dst)));
7607 			/*
7608 			 * Check if our address is present more than
7609 			 * once as consecutive hops in source route.
7610 			 * XXX verify per-interface ip_forwarding
7611 			 * for source route?
7612 			 */
7613 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7614 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7615 			if (ire != NULL) {
7616 				ire_refrele(ire);
7617 				off += IP_ADDR_LEN;
7618 				goto redo_srr;
7619 			}
7620 			if (dst == htonl(INADDR_LOOPBACK)) {
7621 				ip1dbg(("ip_massage_options: loopback addr in "
7622 				    "source route!\n"));
7623 				break;
7624 			}
7625 			/*
7626 			 * Update ipha_dst to be the first hop and remove the
7627 			 * first hop from the source route (by overwriting
7628 			 * part of the option with NOP options).
7629 			 */
7630 			ipha->ipha_dst = dst;
7631 			/* Put the last entry in dst */
7632 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7633 			    3;
7634 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7635 
7636 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7637 			    ntohl(dst)));
7638 			/* Move down and overwrite */
7639 			opt[IP_ADDR_LEN] = opt[0];
7640 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7641 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7642 			for (i = 0; i < IP_ADDR_LEN; i++)
7643 				opt[i] = IPOPT_NOP;
7644 			break;
7645 		}
7646 	}
7647 	return (dst);
7648 }
7649 
7650 /*
7651  * Return the network mask
7652  * associated with the specified address.
7653  */
7654 ipaddr_t
7655 ip_net_mask(ipaddr_t addr)
7656 {
7657 	uchar_t	*up = (uchar_t *)&addr;
7658 	ipaddr_t mask = 0;
7659 	uchar_t	*maskp = (uchar_t *)&mask;
7660 
7661 #if defined(__i386) || defined(__amd64)
7662 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7663 #endif
7664 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7665 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7666 #endif
7667 	if (CLASSD(addr)) {
7668 		maskp[0] = 0xF0;
7669 		return (mask);
7670 	}
7671 	if (addr == 0)
7672 		return (0);
7673 	maskp[0] = 0xFF;
7674 	if ((up[0] & 0x80) == 0)
7675 		return (mask);
7676 
7677 	maskp[1] = 0xFF;
7678 	if ((up[0] & 0xC0) == 0x80)
7679 		return (mask);
7680 
7681 	maskp[2] = 0xFF;
7682 	if ((up[0] & 0xE0) == 0xC0)
7683 		return (mask);
7684 
7685 	/* Must be experimental or multicast, indicate as much */
7686 	return ((ipaddr_t)0);
7687 }
7688 
7689 /*
7690  * Select an ill for the packet by considering load spreading across
7691  * a different ill in the group if dst_ill is part of some group.
7692  */
7693 ill_t *
7694 ip_newroute_get_dst_ill(ill_t *dst_ill)
7695 {
7696 	ill_t *ill;
7697 
7698 	/*
7699 	 * We schedule irrespective of whether the source address is
7700 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7701 	 */
7702 	ill = illgrp_scheduler(dst_ill);
7703 	if (ill == NULL)
7704 		return (NULL);
7705 
7706 	/*
7707 	 * For groups with names ip_sioctl_groupname ensures that all
7708 	 * ills are of same type. For groups without names, ifgrp_insert
7709 	 * ensures this.
7710 	 */
7711 	ASSERT(dst_ill->ill_type == ill->ill_type);
7712 
7713 	return (ill);
7714 }
7715 
7716 /*
7717  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7718  */
7719 ill_t *
7720 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6,
7721     ip_stack_t *ipst)
7722 {
7723 	ill_t *ret_ill;
7724 
7725 	ASSERT(ifindex != 0);
7726 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7727 	    ipst);
7728 	if (ret_ill == NULL ||
7729 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7730 		if (isv6) {
7731 			if (ill != NULL) {
7732 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7733 			} else {
7734 				BUMP_MIB(&ipst->ips_ip6_mib,
7735 				    ipIfStatsOutDiscards);
7736 			}
7737 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7738 			    "bad ifindex %d.\n", ifindex));
7739 		} else {
7740 			if (ill != NULL) {
7741 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7742 			} else {
7743 				BUMP_MIB(&ipst->ips_ip_mib,
7744 				    ipIfStatsOutDiscards);
7745 			}
7746 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7747 			    "bad ifindex %d.\n", ifindex));
7748 		}
7749 		if (ret_ill != NULL)
7750 			ill_refrele(ret_ill);
7751 		freemsg(first_mp);
7752 		return (NULL);
7753 	}
7754 
7755 	return (ret_ill);
7756 }
7757 
7758 /*
7759  * IPv4 -
7760  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7761  * out a packet to a destination address for which we do not have specific
7762  * (or sufficient) routing information.
7763  *
7764  * NOTE : These are the scopes of some of the variables that point at IRE,
7765  *	  which needs to be followed while making any future modifications
7766  *	  to avoid memory leaks.
7767  *
7768  *	- ire and sire are the entries looked up initially by
7769  *	  ire_ftable_lookup.
7770  *	- ipif_ire is used to hold the interface ire associated with
7771  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7772  *	  it before branching out to error paths.
7773  *	- save_ire is initialized before ire_create, so that ire returned
7774  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7775  *	  before breaking out of the switch.
7776  *
7777  *	Thus on failures, we have to REFRELE only ire and sire, if they
7778  *	are not NULL.
7779  */
7780 void
7781 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, conn_t *connp,
7782     zoneid_t zoneid, ip_stack_t *ipst)
7783 {
7784 	areq_t	*areq;
7785 	ipaddr_t gw = 0;
7786 	ire_t	*ire = NULL;
7787 	mblk_t	*res_mp;
7788 	ipaddr_t *addrp;
7789 	ipaddr_t nexthop_addr;
7790 	ipif_t  *src_ipif = NULL;
7791 	ill_t	*dst_ill = NULL;
7792 	ipha_t  *ipha;
7793 	ire_t	*sire = NULL;
7794 	mblk_t	*first_mp;
7795 	ire_t	*save_ire;
7796 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7797 	ushort_t ire_marks = 0;
7798 	boolean_t mctl_present;
7799 	ipsec_out_t *io;
7800 	mblk_t	*saved_mp;
7801 	ire_t	*first_sire = NULL;
7802 	mblk_t	*copy_mp = NULL;
7803 	mblk_t	*xmit_mp = NULL;
7804 	ipaddr_t save_dst;
7805 	uint32_t multirt_flags =
7806 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7807 	boolean_t multirt_is_resolvable;
7808 	boolean_t multirt_resolve_next;
7809 	boolean_t unspec_src;
7810 	boolean_t do_attach_ill = B_FALSE;
7811 	boolean_t ip_nexthop = B_FALSE;
7812 	tsol_ire_gw_secattr_t *attrp = NULL;
7813 	tsol_gcgrp_t *gcgrp = NULL;
7814 	tsol_gcgrp_addr_t ga;
7815 
7816 	if (ip_debug > 2) {
7817 		/* ip1dbg */
7818 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7819 	}
7820 
7821 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7822 	if (mctl_present) {
7823 		io = (ipsec_out_t *)first_mp->b_rptr;
7824 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7825 		ASSERT(zoneid == io->ipsec_out_zoneid);
7826 		ASSERT(zoneid != ALL_ZONES);
7827 	}
7828 
7829 	ipha = (ipha_t *)mp->b_rptr;
7830 
7831 	/* All multicast lookups come through ip_newroute_ipif() */
7832 	if (CLASSD(dst)) {
7833 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7834 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7835 		freemsg(first_mp);
7836 		return;
7837 	}
7838 
7839 	if (mctl_present && io->ipsec_out_attach_if) {
7840 		/* ip_grab_attach_ill returns a held ill */
7841 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7842 		    io->ipsec_out_ill_index, B_FALSE, ipst);
7843 
7844 		/* Failure case frees things for us. */
7845 		if (attach_ill == NULL)
7846 			return;
7847 
7848 		/*
7849 		 * Check if we need an ire that will not be
7850 		 * looked up by anybody else i.e. HIDDEN.
7851 		 */
7852 		if (ill_is_probeonly(attach_ill))
7853 			ire_marks = IRE_MARK_HIDDEN;
7854 	}
7855 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7856 		ip_nexthop = B_TRUE;
7857 		nexthop_addr = io->ipsec_out_nexthop_addr;
7858 	}
7859 	/*
7860 	 * If this IRE is created for forwarding or it is not for
7861 	 * traffic for congestion controlled protocols, mark it as temporary.
7862 	 */
7863 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7864 		ire_marks |= IRE_MARK_TEMPORARY;
7865 
7866 	/*
7867 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7868 	 * chain until it gets the most specific information available.
7869 	 * For example, we know that there is no IRE_CACHE for this dest,
7870 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7871 	 * ire_ftable_lookup will look up the gateway, etc.
7872 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7873 	 * to the destination, of equal netmask length in the forward table,
7874 	 * will be recursively explored. If no information is available
7875 	 * for the final gateway of that route, we force the returned ire
7876 	 * to be equal to sire using MATCH_IRE_PARENT.
7877 	 * At least, in this case we have a starting point (in the buckets)
7878 	 * to look for other routes to the destination in the forward table.
7879 	 * This is actually used only for multirouting, where a list
7880 	 * of routes has to be processed in sequence.
7881 	 *
7882 	 * In the process of coming up with the most specific information,
7883 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7884 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7885 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7886 	 * Two caveats when handling incomplete ire's in ip_newroute:
7887 	 * - we should be careful when accessing its ire_nce (specifically
7888 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7889 	 * - not all legacy code path callers are prepared to handle
7890 	 *   incomplete ire's, so we should not create/add incomplete
7891 	 *   ire_cache entries here. (See discussion about temporary solution
7892 	 *   further below).
7893 	 *
7894 	 * In order to minimize packet dropping, and to preserve existing
7895 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7896 	 * gateway, and instead use the IF_RESOLVER ire to send out
7897 	 * another request to ARP (this is achieved by passing the
7898 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
7899 	 * arp response comes back in ip_wput_nondata, we will create
7900 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
7901 	 *
7902 	 * Note that this is a temporary solution; the correct solution is
7903 	 * to create an incomplete  per-dst ire_cache entry, and send the
7904 	 * packet out when the gw's nce is resolved. In order to achieve this,
7905 	 * all packet processing must have been completed prior to calling
7906 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
7907 	 * to be modified to accomodate this solution.
7908 	 */
7909 	if (ip_nexthop) {
7910 		/*
7911 		 * The first time we come here, we look for an IRE_INTERFACE
7912 		 * entry for the specified nexthop, set the dst to be the
7913 		 * nexthop address and create an IRE_CACHE entry for the
7914 		 * nexthop. The next time around, we are able to find an
7915 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7916 		 * nexthop address and create an IRE_CACHE entry for the
7917 		 * destination address via the specified nexthop.
7918 		 */
7919 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7920 		    MBLK_GETLABEL(mp), ipst);
7921 		if (ire != NULL) {
7922 			gw = nexthop_addr;
7923 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7924 		} else {
7925 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7926 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7927 			    MBLK_GETLABEL(mp),
7928 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
7929 			    ipst);
7930 			if (ire != NULL) {
7931 				dst = nexthop_addr;
7932 			}
7933 		}
7934 	} else if (attach_ill == NULL) {
7935 		ire = ire_ftable_lookup(dst, 0, 0, 0,
7936 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
7937 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
7938 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
7939 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
7940 		    ipst);
7941 	} else {
7942 		/*
7943 		 * attach_ill is set only for communicating with
7944 		 * on-link hosts. So, don't look for DEFAULT.
7945 		 */
7946 		ipif_t	*attach_ipif;
7947 
7948 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
7949 		if (attach_ipif == NULL) {
7950 			ill_refrele(attach_ill);
7951 			goto icmp_err_ret;
7952 		}
7953 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
7954 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
7955 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
7956 		    MATCH_IRE_SECATTR, ipst);
7957 		ipif_refrele(attach_ipif);
7958 	}
7959 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
7960 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
7961 
7962 	/*
7963 	 * This loop is run only once in most cases.
7964 	 * We loop to resolve further routes only when the destination
7965 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7966 	 */
7967 	do {
7968 		/* Clear the previous iteration's values */
7969 		if (src_ipif != NULL) {
7970 			ipif_refrele(src_ipif);
7971 			src_ipif = NULL;
7972 		}
7973 		if (dst_ill != NULL) {
7974 			ill_refrele(dst_ill);
7975 			dst_ill = NULL;
7976 		}
7977 
7978 		multirt_resolve_next = B_FALSE;
7979 		/*
7980 		 * We check if packets have to be multirouted.
7981 		 * In this case, given the current <ire, sire> couple,
7982 		 * we look for the next suitable <ire, sire>.
7983 		 * This check is done in ire_multirt_lookup(),
7984 		 * which applies various criteria to find the next route
7985 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
7986 		 * unchanged if it detects it has not been tried yet.
7987 		 */
7988 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7989 			ip3dbg(("ip_newroute: starting next_resolution "
7990 			    "with first_mp %p, tag %d\n",
7991 			    (void *)first_mp,
7992 			    MULTIRT_DEBUG_TAGGED(first_mp)));
7993 
7994 			ASSERT(sire != NULL);
7995 			multirt_is_resolvable =
7996 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
7997 			    MBLK_GETLABEL(mp), ipst);
7998 
7999 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
8000 			    "ire %p, sire %p\n",
8001 			    multirt_is_resolvable,
8002 			    (void *)ire, (void *)sire));
8003 
8004 			if (!multirt_is_resolvable) {
8005 				/*
8006 				 * No more multirt route to resolve; give up
8007 				 * (all routes resolved or no more
8008 				 * resolvable routes).
8009 				 */
8010 				if (ire != NULL) {
8011 					ire_refrele(ire);
8012 					ire = NULL;
8013 				}
8014 			} else {
8015 				ASSERT(sire != NULL);
8016 				ASSERT(ire != NULL);
8017 				/*
8018 				 * We simply use first_sire as a flag that
8019 				 * indicates if a resolvable multirt route
8020 				 * has already been found.
8021 				 * If it is not the case, we may have to send
8022 				 * an ICMP error to report that the
8023 				 * destination is unreachable.
8024 				 * We do not IRE_REFHOLD first_sire.
8025 				 */
8026 				if (first_sire == NULL) {
8027 					first_sire = sire;
8028 				}
8029 			}
8030 		}
8031 		if (ire == NULL) {
8032 			if (ip_debug > 3) {
8033 				/* ip2dbg */
8034 				pr_addr_dbg("ip_newroute: "
8035 				    "can't resolve %s\n", AF_INET, &dst);
8036 			}
8037 			ip3dbg(("ip_newroute: "
8038 			    "ire %p, sire %p, first_sire %p\n",
8039 			    (void *)ire, (void *)sire, (void *)first_sire));
8040 
8041 			if (sire != NULL) {
8042 				ire_refrele(sire);
8043 				sire = NULL;
8044 			}
8045 
8046 			if (first_sire != NULL) {
8047 				/*
8048 				 * At least one multirt route has been found
8049 				 * in the same call to ip_newroute();
8050 				 * there is no need to report an ICMP error.
8051 				 * first_sire was not IRE_REFHOLDed.
8052 				 */
8053 				MULTIRT_DEBUG_UNTAG(first_mp);
8054 				freemsg(first_mp);
8055 				return;
8056 			}
8057 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8058 			    RTA_DST, ipst);
8059 			if (attach_ill != NULL)
8060 				ill_refrele(attach_ill);
8061 			goto icmp_err_ret;
8062 		}
8063 
8064 		/*
8065 		 * Verify that the returned IRE does not have either
8066 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8067 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8068 		 */
8069 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8070 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8071 			if (attach_ill != NULL)
8072 				ill_refrele(attach_ill);
8073 			goto icmp_err_ret;
8074 		}
8075 		/*
8076 		 * Increment the ire_ob_pkt_count field for ire if it is an
8077 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8078 		 * increment the same for the parent IRE, sire, if it is some
8079 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, and HOST)
8080 		 */
8081 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8082 			UPDATE_OB_PKT_COUNT(ire);
8083 			ire->ire_last_used_time = lbolt;
8084 		}
8085 
8086 		if (sire != NULL) {
8087 			gw = sire->ire_gateway_addr;
8088 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8089 			    IRE_INTERFACE)) == 0);
8090 			UPDATE_OB_PKT_COUNT(sire);
8091 			sire->ire_last_used_time = lbolt;
8092 		}
8093 		/*
8094 		 * We have a route to reach the destination.
8095 		 *
8096 		 * 1) If the interface is part of ill group, try to get a new
8097 		 *    ill taking load spreading into account.
8098 		 *
8099 		 * 2) After selecting the ill, get a source address that
8100 		 *    might create good inbound load spreading.
8101 		 *    ipif_select_source does this for us.
8102 		 *
8103 		 * If the application specified the ill (ifindex), we still
8104 		 * load spread. Only if the packets needs to go out
8105 		 * specifically on a given ill e.g. binding to
8106 		 * IPIF_NOFAILOVER address, then we don't try to use a
8107 		 * different ill for load spreading.
8108 		 */
8109 		if (attach_ill == NULL) {
8110 			/*
8111 			 * Don't perform outbound load spreading in the
8112 			 * case of an RTF_MULTIRT route, as we actually
8113 			 * typically want to replicate outgoing packets
8114 			 * through particular interfaces.
8115 			 */
8116 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8117 				dst_ill = ire->ire_ipif->ipif_ill;
8118 				/* for uniformity */
8119 				ill_refhold(dst_ill);
8120 			} else {
8121 				/*
8122 				 * If we are here trying to create an IRE_CACHE
8123 				 * for an offlink destination and have the
8124 				 * IRE_CACHE for the next hop and the latter is
8125 				 * using virtual IP source address selection i.e
8126 				 * it's ire->ire_ipif is pointing to a virtual
8127 				 * network interface (vni) then
8128 				 * ip_newroute_get_dst_ll() will return the vni
8129 				 * interface as the dst_ill. Since the vni is
8130 				 * virtual i.e not associated with any physical
8131 				 * interface, it cannot be the dst_ill, hence
8132 				 * in such a case call ip_newroute_get_dst_ll()
8133 				 * with the stq_ill instead of the ire_ipif ILL.
8134 				 * The function returns a refheld ill.
8135 				 */
8136 				if ((ire->ire_type == IRE_CACHE) &&
8137 				    IS_VNI(ire->ire_ipif->ipif_ill))
8138 					dst_ill = ip_newroute_get_dst_ill(
8139 					    ire->ire_stq->q_ptr);
8140 				else
8141 					dst_ill = ip_newroute_get_dst_ill(
8142 					    ire->ire_ipif->ipif_ill);
8143 			}
8144 			if (dst_ill == NULL) {
8145 				if (ip_debug > 2) {
8146 					pr_addr_dbg("ip_newroute: "
8147 					    "no dst ill for dst"
8148 					    " %s\n", AF_INET, &dst);
8149 				}
8150 				goto icmp_err_ret;
8151 			}
8152 		} else {
8153 			dst_ill = ire->ire_ipif->ipif_ill;
8154 			/* for uniformity */
8155 			ill_refhold(dst_ill);
8156 			/*
8157 			 * We should have found a route matching ill as we
8158 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
8159 			 * Rather than asserting, when there is a mismatch,
8160 			 * we just drop the packet.
8161 			 */
8162 			if (dst_ill != attach_ill) {
8163 				ip0dbg(("ip_newroute: Packet dropped as "
8164 				    "IPIF_NOFAILOVER ill is %s, "
8165 				    "ire->ire_ipif->ipif_ill is %s\n",
8166 				    attach_ill->ill_name,
8167 				    dst_ill->ill_name));
8168 				ill_refrele(attach_ill);
8169 				goto icmp_err_ret;
8170 			}
8171 		}
8172 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
8173 		if (attach_ill != NULL) {
8174 			ill_refrele(attach_ill);
8175 			attach_ill = NULL;
8176 			do_attach_ill = B_TRUE;
8177 		}
8178 		ASSERT(dst_ill != NULL);
8179 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8180 
8181 		/*
8182 		 * Pick the best source address from dst_ill.
8183 		 *
8184 		 * 1) If it is part of a multipathing group, we would
8185 		 *    like to spread the inbound packets across different
8186 		 *    interfaces. ipif_select_source picks a random source
8187 		 *    across the different ills in the group.
8188 		 *
8189 		 * 2) If it is not part of a multipathing group, we try
8190 		 *    to pick the source address from the destination
8191 		 *    route. Clustering assumes that when we have multiple
8192 		 *    prefixes hosted on an interface, the prefix of the
8193 		 *    source address matches the prefix of the destination
8194 		 *    route. We do this only if the address is not
8195 		 *    DEPRECATED.
8196 		 *
8197 		 * 3) If the conn is in a different zone than the ire, we
8198 		 *    need to pick a source address from the right zone.
8199 		 *
8200 		 * NOTE : If we hit case (1) above, the prefix of the source
8201 		 *	  address picked may not match the prefix of the
8202 		 *	  destination routes prefix as ipif_select_source
8203 		 *	  does not look at "dst" while picking a source
8204 		 *	  address.
8205 		 *	  If we want the same behavior as (2), we will need
8206 		 *	  to change the behavior of ipif_select_source.
8207 		 */
8208 		ASSERT(src_ipif == NULL);
8209 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8210 			/*
8211 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8212 			 * Check that the ipif matching the requested source
8213 			 * address still exists.
8214 			 */
8215 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8216 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8217 		}
8218 
8219 		unspec_src = (connp != NULL && connp->conn_unspec_src);
8220 
8221 		if (src_ipif == NULL &&
8222 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
8223 			ire_marks |= IRE_MARK_USESRC_CHECK;
8224 			if ((dst_ill->ill_group != NULL) ||
8225 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8226 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8227 			    ire->ire_zoneid != ALL_ZONES) ||
8228 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8229 				/*
8230 				 * If the destination is reachable via a
8231 				 * given gateway, the selected source address
8232 				 * should be in the same subnet as the gateway.
8233 				 * Otherwise, the destination is not reachable.
8234 				 *
8235 				 * If there are no interfaces on the same subnet
8236 				 * as the destination, ipif_select_source gives
8237 				 * first non-deprecated interface which might be
8238 				 * on a different subnet than the gateway.
8239 				 * This is not desirable. Hence pass the dst_ire
8240 				 * source address to ipif_select_source.
8241 				 * It is sure that the destination is reachable
8242 				 * with the dst_ire source address subnet.
8243 				 * So passing dst_ire source address to
8244 				 * ipif_select_source will make sure that the
8245 				 * selected source will be on the same subnet
8246 				 * as dst_ire source address.
8247 				 */
8248 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8249 				src_ipif = ipif_select_source(dst_ill, saddr,
8250 				    zoneid);
8251 				if (src_ipif == NULL) {
8252 					if (ip_debug > 2) {
8253 						pr_addr_dbg("ip_newroute: "
8254 						    "no src for dst %s ",
8255 						    AF_INET, &dst);
8256 						printf("through interface %s\n",
8257 						    dst_ill->ill_name);
8258 					}
8259 					goto icmp_err_ret;
8260 				}
8261 			} else {
8262 				src_ipif = ire->ire_ipif;
8263 				ASSERT(src_ipif != NULL);
8264 				/* hold src_ipif for uniformity */
8265 				ipif_refhold(src_ipif);
8266 			}
8267 		}
8268 
8269 		/*
8270 		 * Assign a source address while we have the conn.
8271 		 * We can't have ip_wput_ire pick a source address when the
8272 		 * packet returns from arp since we need to look at
8273 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8274 		 * going through arp.
8275 		 *
8276 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8277 		 *	  it uses ip6i to store this information.
8278 		 */
8279 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
8280 			ipha->ipha_src = src_ipif->ipif_src_addr;
8281 
8282 		if (ip_debug > 3) {
8283 			/* ip2dbg */
8284 			pr_addr_dbg("ip_newroute: first hop %s\n",
8285 			    AF_INET, &gw);
8286 		}
8287 		ip2dbg(("\tire type %s (%d)\n",
8288 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8289 
8290 		/*
8291 		 * The TTL of multirouted packets is bounded by the
8292 		 * ip_multirt_ttl ndd variable.
8293 		 */
8294 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8295 			/* Force TTL of multirouted packets */
8296 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8297 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8298 				ip2dbg(("ip_newroute: forcing multirt TTL "
8299 				    "to %d (was %d), dst 0x%08x\n",
8300 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8301 				    ntohl(sire->ire_addr)));
8302 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8303 			}
8304 		}
8305 		/*
8306 		 * At this point in ip_newroute(), ire is either the
8307 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8308 		 * destination or an IRE_INTERFACE type that should be used
8309 		 * to resolve an on-subnet destination or an on-subnet
8310 		 * next-hop gateway.
8311 		 *
8312 		 * In the IRE_CACHE case, we have the following :
8313 		 *
8314 		 * 1) src_ipif - used for getting a source address.
8315 		 *
8316 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8317 		 *    means packets using this IRE_CACHE will go out on
8318 		 *    dst_ill.
8319 		 *
8320 		 * 3) The IRE sire will point to the prefix that is the
8321 		 *    longest  matching route for the destination. These
8322 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8323 		 *
8324 		 *    The newly created IRE_CACHE entry for the off-subnet
8325 		 *    destination is tied to both the prefix route and the
8326 		 *    interface route used to resolve the next-hop gateway
8327 		 *    via the ire_phandle and ire_ihandle fields,
8328 		 *    respectively.
8329 		 *
8330 		 * In the IRE_INTERFACE case, we have the following :
8331 		 *
8332 		 * 1) src_ipif - used for getting a source address.
8333 		 *
8334 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8335 		 *    means packets using the IRE_CACHE that we will build
8336 		 *    here will go out on dst_ill.
8337 		 *
8338 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8339 		 *    to be created will only be tied to the IRE_INTERFACE
8340 		 *    that was derived from the ire_ihandle field.
8341 		 *
8342 		 *    If sire is non-NULL, it means the destination is
8343 		 *    off-link and we will first create the IRE_CACHE for the
8344 		 *    gateway. Next time through ip_newroute, we will create
8345 		 *    the IRE_CACHE for the final destination as described
8346 		 *    above.
8347 		 *
8348 		 * In both cases, after the current resolution has been
8349 		 * completed (or possibly initialised, in the IRE_INTERFACE
8350 		 * case), the loop may be re-entered to attempt the resolution
8351 		 * of another RTF_MULTIRT route.
8352 		 *
8353 		 * When an IRE_CACHE entry for the off-subnet destination is
8354 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8355 		 * for further processing in emission loops.
8356 		 */
8357 		save_ire = ire;
8358 		switch (ire->ire_type) {
8359 		case IRE_CACHE: {
8360 			ire_t	*ipif_ire;
8361 
8362 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8363 			if (gw == 0)
8364 				gw = ire->ire_gateway_addr;
8365 			/*
8366 			 * We need 3 ire's to create a new cache ire for an
8367 			 * off-link destination from the cache ire of the
8368 			 * gateway.
8369 			 *
8370 			 *	1. The prefix ire 'sire' (Note that this does
8371 			 *	   not apply to the conn_nexthop_set case)
8372 			 *	2. The cache ire of the gateway 'ire'
8373 			 *	3. The interface ire 'ipif_ire'
8374 			 *
8375 			 * We have (1) and (2). We lookup (3) below.
8376 			 *
8377 			 * If there is no interface route to the gateway,
8378 			 * it is a race condition, where we found the cache
8379 			 * but the interface route has been deleted.
8380 			 */
8381 			if (ip_nexthop) {
8382 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8383 			} else {
8384 				ipif_ire =
8385 				    ire_ihandle_lookup_offlink(ire, sire);
8386 			}
8387 			if (ipif_ire == NULL) {
8388 				ip1dbg(("ip_newroute: "
8389 				    "ire_ihandle_lookup_offlink failed\n"));
8390 				goto icmp_err_ret;
8391 			}
8392 
8393 			/*
8394 			 * Check cached gateway IRE for any security
8395 			 * attributes; if found, associate the gateway
8396 			 * credentials group to the destination IRE.
8397 			 */
8398 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8399 				mutex_enter(&attrp->igsa_lock);
8400 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8401 					GCGRP_REFHOLD(gcgrp);
8402 				mutex_exit(&attrp->igsa_lock);
8403 			}
8404 
8405 			/*
8406 			 * XXX For the source of the resolver mp,
8407 			 * we are using the same DL_UNITDATA_REQ
8408 			 * (from save_ire->ire_nce->nce_res_mp)
8409 			 * though the save_ire is not pointing at the same ill.
8410 			 * This is incorrect. We need to send it up to the
8411 			 * resolver to get the right res_mp. For ethernets
8412 			 * this may be okay (ill_type == DL_ETHER).
8413 			 */
8414 
8415 			ire = ire_create(
8416 			    (uchar_t *)&dst,		/* dest address */
8417 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8418 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8419 			    (uchar_t *)&gw,		/* gateway address */
8420 			    &save_ire->ire_max_frag,
8421 			    save_ire->ire_nce,		/* src nce */
8422 			    dst_ill->ill_rq,		/* recv-from queue */
8423 			    dst_ill->ill_wq,		/* send-to queue */
8424 			    IRE_CACHE,			/* IRE type */
8425 			    src_ipif,
8426 			    (sire != NULL) ?
8427 			    sire->ire_mask : 0, 	/* Parent mask */
8428 			    (sire != NULL) ?
8429 			    sire->ire_phandle : 0,	/* Parent handle */
8430 			    ipif_ire->ire_ihandle,	/* Interface handle */
8431 			    (sire != NULL) ? (sire->ire_flags &
8432 			    (RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8433 			    (sire != NULL) ?
8434 			    &(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8435 			    NULL,
8436 			    gcgrp,
8437 			    ipst);
8438 
8439 			if (ire == NULL) {
8440 				if (gcgrp != NULL) {
8441 					GCGRP_REFRELE(gcgrp);
8442 					gcgrp = NULL;
8443 				}
8444 				ire_refrele(ipif_ire);
8445 				ire_refrele(save_ire);
8446 				break;
8447 			}
8448 
8449 			/* reference now held by IRE */
8450 			gcgrp = NULL;
8451 
8452 			ire->ire_marks |= ire_marks;
8453 
8454 			/*
8455 			 * Prevent sire and ipif_ire from getting deleted.
8456 			 * The newly created ire is tied to both of them via
8457 			 * the phandle and ihandle respectively.
8458 			 */
8459 			if (sire != NULL) {
8460 				IRB_REFHOLD(sire->ire_bucket);
8461 				/* Has it been removed already ? */
8462 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8463 					IRB_REFRELE(sire->ire_bucket);
8464 					ire_refrele(ipif_ire);
8465 					ire_refrele(save_ire);
8466 					break;
8467 				}
8468 			}
8469 
8470 			IRB_REFHOLD(ipif_ire->ire_bucket);
8471 			/* Has it been removed already ? */
8472 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8473 				IRB_REFRELE(ipif_ire->ire_bucket);
8474 				if (sire != NULL)
8475 					IRB_REFRELE(sire->ire_bucket);
8476 				ire_refrele(ipif_ire);
8477 				ire_refrele(save_ire);
8478 				break;
8479 			}
8480 
8481 			xmit_mp = first_mp;
8482 			/*
8483 			 * In the case of multirouting, a copy
8484 			 * of the packet is done before its sending.
8485 			 * The copy is used to attempt another
8486 			 * route resolution, in a next loop.
8487 			 */
8488 			if (ire->ire_flags & RTF_MULTIRT) {
8489 				copy_mp = copymsg(first_mp);
8490 				if (copy_mp != NULL) {
8491 					xmit_mp = copy_mp;
8492 					MULTIRT_DEBUG_TAG(first_mp);
8493 				}
8494 			}
8495 			ire_add_then_send(q, ire, xmit_mp);
8496 			ire_refrele(save_ire);
8497 
8498 			/* Assert that sire is not deleted yet. */
8499 			if (sire != NULL) {
8500 				ASSERT(sire->ire_ptpn != NULL);
8501 				IRB_REFRELE(sire->ire_bucket);
8502 			}
8503 
8504 			/* Assert that ipif_ire is not deleted yet. */
8505 			ASSERT(ipif_ire->ire_ptpn != NULL);
8506 			IRB_REFRELE(ipif_ire->ire_bucket);
8507 			ire_refrele(ipif_ire);
8508 
8509 			/*
8510 			 * If copy_mp is not NULL, multirouting was
8511 			 * requested. We loop to initiate a next
8512 			 * route resolution attempt, starting from sire.
8513 			 */
8514 			if (copy_mp != NULL) {
8515 				/*
8516 				 * Search for the next unresolved
8517 				 * multirt route.
8518 				 */
8519 				copy_mp = NULL;
8520 				ipif_ire = NULL;
8521 				ire = NULL;
8522 				multirt_resolve_next = B_TRUE;
8523 				continue;
8524 			}
8525 			if (sire != NULL)
8526 				ire_refrele(sire);
8527 			ipif_refrele(src_ipif);
8528 			ill_refrele(dst_ill);
8529 			return;
8530 		}
8531 		case IRE_IF_NORESOLVER: {
8532 
8533 			if (dst_ill->ill_phys_addr_length != IP_ADDR_LEN &&
8534 			    dst_ill->ill_resolver_mp == NULL) {
8535 				ip1dbg(("ip_newroute: dst_ill %p "
8536 				    "for IRE_IF_NORESOLVER ire %p has "
8537 				    "no ill_resolver_mp\n",
8538 				    (void *)dst_ill, (void *)ire));
8539 				break;
8540 			}
8541 
8542 			/*
8543 			 * TSol note: We are creating the ire cache for the
8544 			 * destination 'dst'. If 'dst' is offlink, going
8545 			 * through the first hop 'gw', the security attributes
8546 			 * of 'dst' must be set to point to the gateway
8547 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8548 			 * is possible that 'dst' is a potential gateway that is
8549 			 * referenced by some route that has some security
8550 			 * attributes. Thus in the former case, we need to do a
8551 			 * gcgrp_lookup of 'gw' while in the latter case we
8552 			 * need to do gcgrp_lookup of 'dst' itself.
8553 			 */
8554 			ga.ga_af = AF_INET;
8555 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8556 			    &ga.ga_addr);
8557 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8558 
8559 			ire = ire_create(
8560 			    (uchar_t *)&dst,		/* dest address */
8561 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8562 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8563 			    (uchar_t *)&gw,		/* gateway address */
8564 			    &save_ire->ire_max_frag,
8565 			    NULL,			/* no src nce */
8566 			    dst_ill->ill_rq,		/* recv-from queue */
8567 			    dst_ill->ill_wq,		/* send-to queue */
8568 			    IRE_CACHE,
8569 			    src_ipif,
8570 			    save_ire->ire_mask,		/* Parent mask */
8571 			    (sire != NULL) ?		/* Parent handle */
8572 			    sire->ire_phandle : 0,
8573 			    save_ire->ire_ihandle,	/* Interface handle */
8574 			    (sire != NULL) ? sire->ire_flags &
8575 			    (RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8576 			    &(save_ire->ire_uinfo),
8577 			    NULL,
8578 			    gcgrp,
8579 			    ipst);
8580 
8581 			if (ire == NULL) {
8582 				if (gcgrp != NULL) {
8583 					GCGRP_REFRELE(gcgrp);
8584 					gcgrp = NULL;
8585 				}
8586 				ire_refrele(save_ire);
8587 				break;
8588 			}
8589 
8590 			/* reference now held by IRE */
8591 			gcgrp = NULL;
8592 
8593 			ire->ire_marks |= ire_marks;
8594 
8595 			/* Prevent save_ire from getting deleted */
8596 			IRB_REFHOLD(save_ire->ire_bucket);
8597 			/* Has it been removed already ? */
8598 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8599 				IRB_REFRELE(save_ire->ire_bucket);
8600 				ire_refrele(save_ire);
8601 				break;
8602 			}
8603 
8604 			/*
8605 			 * In the case of multirouting, a copy
8606 			 * of the packet is made before it is sent.
8607 			 * The copy is used in the next
8608 			 * loop to attempt another resolution.
8609 			 */
8610 			xmit_mp = first_mp;
8611 			if ((sire != NULL) &&
8612 			    (sire->ire_flags & RTF_MULTIRT)) {
8613 				copy_mp = copymsg(first_mp);
8614 				if (copy_mp != NULL) {
8615 					xmit_mp = copy_mp;
8616 					MULTIRT_DEBUG_TAG(first_mp);
8617 				}
8618 			}
8619 			ire_add_then_send(q, ire, xmit_mp);
8620 
8621 			/* Assert that it is not deleted yet. */
8622 			ASSERT(save_ire->ire_ptpn != NULL);
8623 			IRB_REFRELE(save_ire->ire_bucket);
8624 			ire_refrele(save_ire);
8625 
8626 			if (copy_mp != NULL) {
8627 				/*
8628 				 * If we found a (no)resolver, we ignore any
8629 				 * trailing top priority IRE_CACHE in further
8630 				 * loops. This ensures that we do not omit any
8631 				 * (no)resolver.
8632 				 * This IRE_CACHE, if any, will be processed
8633 				 * by another thread entering ip_newroute().
8634 				 * IRE_CACHE entries, if any, will be processed
8635 				 * by another thread entering ip_newroute(),
8636 				 * (upon resolver response, for instance).
8637 				 * This aims to force parallel multirt
8638 				 * resolutions as soon as a packet must be sent.
8639 				 * In the best case, after the tx of only one
8640 				 * packet, all reachable routes are resolved.
8641 				 * Otherwise, the resolution of all RTF_MULTIRT
8642 				 * routes would require several emissions.
8643 				 */
8644 				multirt_flags &= ~MULTIRT_CACHEGW;
8645 
8646 				/*
8647 				 * Search for the next unresolved multirt
8648 				 * route.
8649 				 */
8650 				copy_mp = NULL;
8651 				save_ire = NULL;
8652 				ire = NULL;
8653 				multirt_resolve_next = B_TRUE;
8654 				continue;
8655 			}
8656 
8657 			/*
8658 			 * Don't need sire anymore
8659 			 */
8660 			if (sire != NULL)
8661 				ire_refrele(sire);
8662 
8663 			ipif_refrele(src_ipif);
8664 			ill_refrele(dst_ill);
8665 			return;
8666 		}
8667 		case IRE_IF_RESOLVER:
8668 			/*
8669 			 * We can't build an IRE_CACHE yet, but at least we
8670 			 * found a resolver that can help.
8671 			 */
8672 			res_mp = dst_ill->ill_resolver_mp;
8673 			if (!OK_RESOLVER_MP(res_mp))
8674 				break;
8675 
8676 			/*
8677 			 * To be at this point in the code with a non-zero gw
8678 			 * means that dst is reachable through a gateway that
8679 			 * we have never resolved.  By changing dst to the gw
8680 			 * addr we resolve the gateway first.
8681 			 * When ire_add_then_send() tries to put the IP dg
8682 			 * to dst, it will reenter ip_newroute() at which
8683 			 * time we will find the IRE_CACHE for the gw and
8684 			 * create another IRE_CACHE in case IRE_CACHE above.
8685 			 */
8686 			if (gw != INADDR_ANY) {
8687 				/*
8688 				 * The source ipif that was determined above was
8689 				 * relative to the destination address, not the
8690 				 * gateway's. If src_ipif was not taken out of
8691 				 * the IRE_IF_RESOLVER entry, we'll need to call
8692 				 * ipif_select_source() again.
8693 				 */
8694 				if (src_ipif != ire->ire_ipif) {
8695 					ipif_refrele(src_ipif);
8696 					src_ipif = ipif_select_source(dst_ill,
8697 					    gw, zoneid);
8698 					if (src_ipif == NULL) {
8699 						if (ip_debug > 2) {
8700 							pr_addr_dbg(
8701 							    "ip_newroute: no "
8702 							    "src for gw %s ",
8703 							    AF_INET, &gw);
8704 							printf("through "
8705 							    "interface %s\n",
8706 							    dst_ill->ill_name);
8707 						}
8708 						goto icmp_err_ret;
8709 					}
8710 				}
8711 				save_dst = dst;
8712 				dst = gw;
8713 				gw = INADDR_ANY;
8714 			}
8715 
8716 			/*
8717 			 * We obtain a partial IRE_CACHE which we will pass
8718 			 * along with the resolver query.  When the response
8719 			 * comes back it will be there ready for us to add.
8720 			 * The ire_max_frag is atomically set under the
8721 			 * irebucket lock in ire_add_v[46].
8722 			 */
8723 
8724 			ire = ire_create_mp(
8725 			    (uchar_t *)&dst,		/* dest address */
8726 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8727 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8728 			    (uchar_t *)&gw,		/* gateway address */
8729 			    NULL,			/* ire_max_frag */
8730 			    NULL,			/* no src nce */
8731 			    dst_ill->ill_rq,		/* recv-from queue */
8732 			    dst_ill->ill_wq,		/* send-to queue */
8733 			    IRE_CACHE,
8734 			    src_ipif,			/* Interface ipif */
8735 			    save_ire->ire_mask,		/* Parent mask */
8736 			    0,
8737 			    save_ire->ire_ihandle,	/* Interface handle */
8738 			    0,				/* flags if any */
8739 			    &(save_ire->ire_uinfo),
8740 			    NULL,
8741 			    NULL,
8742 			    ipst);
8743 
8744 			if (ire == NULL) {
8745 				ire_refrele(save_ire);
8746 				break;
8747 			}
8748 
8749 			if ((sire != NULL) &&
8750 			    (sire->ire_flags & RTF_MULTIRT)) {
8751 				copy_mp = copymsg(first_mp);
8752 				if (copy_mp != NULL)
8753 					MULTIRT_DEBUG_TAG(copy_mp);
8754 			}
8755 
8756 			ire->ire_marks |= ire_marks;
8757 
8758 			/*
8759 			 * Construct message chain for the resolver
8760 			 * of the form:
8761 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8762 			 * Packet could contain a IPSEC_OUT mp.
8763 			 *
8764 			 * NOTE : ire will be added later when the response
8765 			 * comes back from ARP. If the response does not
8766 			 * come back, ARP frees the packet. For this reason,
8767 			 * we can't REFHOLD the bucket of save_ire to prevent
8768 			 * deletions. We may not be able to REFRELE the bucket
8769 			 * if the response never comes back. Thus, before
8770 			 * adding the ire, ire_add_v4 will make sure that the
8771 			 * interface route does not get deleted. This is the
8772 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8773 			 * where we can always prevent deletions because of
8774 			 * the synchronous nature of adding IRES i.e
8775 			 * ire_add_then_send is called after creating the IRE.
8776 			 */
8777 			ASSERT(ire->ire_mp != NULL);
8778 			ire->ire_mp->b_cont = first_mp;
8779 			/* Have saved_mp handy, for cleanup if canput fails */
8780 			saved_mp = mp;
8781 			mp = copyb(res_mp);
8782 			if (mp == NULL) {
8783 				/* Prepare for cleanup */
8784 				mp = saved_mp; /* pkt */
8785 				ire_delete(ire); /* ire_mp */
8786 				ire = NULL;
8787 				ire_refrele(save_ire);
8788 				if (copy_mp != NULL) {
8789 					MULTIRT_DEBUG_UNTAG(copy_mp);
8790 					freemsg(copy_mp);
8791 					copy_mp = NULL;
8792 				}
8793 				break;
8794 			}
8795 			linkb(mp, ire->ire_mp);
8796 
8797 			/*
8798 			 * Fill in the source and dest addrs for the resolver.
8799 			 * NOTE: this depends on memory layouts imposed by
8800 			 * ill_init().
8801 			 */
8802 			areq = (areq_t *)mp->b_rptr;
8803 			addrp = (ipaddr_t *)((char *)areq +
8804 			    areq->areq_sender_addr_offset);
8805 			if (do_attach_ill) {
8806 				/*
8807 				 * This is bind to no failover case.
8808 				 * arp packet also must go out on attach_ill.
8809 				 */
8810 				ASSERT(ipha->ipha_src != NULL);
8811 				*addrp = ipha->ipha_src;
8812 			} else {
8813 				*addrp = save_ire->ire_src_addr;
8814 			}
8815 
8816 			ire_refrele(save_ire);
8817 			addrp = (ipaddr_t *)((char *)areq +
8818 			    areq->areq_target_addr_offset);
8819 			*addrp = dst;
8820 			/* Up to the resolver. */
8821 			if (canputnext(dst_ill->ill_rq) &&
8822 			    !(dst_ill->ill_arp_closing)) {
8823 				putnext(dst_ill->ill_rq, mp);
8824 				ire = NULL;
8825 				if (copy_mp != NULL) {
8826 					/*
8827 					 * If we found a resolver, we ignore
8828 					 * any trailing top priority IRE_CACHE
8829 					 * in the further loops. This ensures
8830 					 * that we do not omit any resolver.
8831 					 * IRE_CACHE entries, if any, will be
8832 					 * processed next time we enter
8833 					 * ip_newroute().
8834 					 */
8835 					multirt_flags &= ~MULTIRT_CACHEGW;
8836 					/*
8837 					 * Search for the next unresolved
8838 					 * multirt route.
8839 					 */
8840 					first_mp = copy_mp;
8841 					copy_mp = NULL;
8842 					/* Prepare the next resolution loop. */
8843 					mp = first_mp;
8844 					EXTRACT_PKT_MP(mp, first_mp,
8845 					    mctl_present);
8846 					if (mctl_present)
8847 						io = (ipsec_out_t *)
8848 						    first_mp->b_rptr;
8849 					ipha = (ipha_t *)mp->b_rptr;
8850 
8851 					ASSERT(sire != NULL);
8852 
8853 					dst = save_dst;
8854 					multirt_resolve_next = B_TRUE;
8855 					continue;
8856 				}
8857 
8858 				if (sire != NULL)
8859 					ire_refrele(sire);
8860 
8861 				/*
8862 				 * The response will come back in ip_wput
8863 				 * with db_type IRE_DB_TYPE.
8864 				 */
8865 				ipif_refrele(src_ipif);
8866 				ill_refrele(dst_ill);
8867 				return;
8868 			} else {
8869 				/* Prepare for cleanup */
8870 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8871 				    mp);
8872 				mp->b_cont = NULL;
8873 				freeb(mp); /* areq */
8874 				/*
8875 				 * this is an ire that is not added to the
8876 				 * cache. ire_freemblk will handle the release
8877 				 * of any resources associated with the ire.
8878 				 */
8879 				ire_delete(ire); /* ire_mp */
8880 				mp = saved_mp; /* pkt */
8881 				ire = NULL;
8882 				if (copy_mp != NULL) {
8883 					MULTIRT_DEBUG_UNTAG(copy_mp);
8884 					freemsg(copy_mp);
8885 					copy_mp = NULL;
8886 				}
8887 				break;
8888 			}
8889 		default:
8890 			break;
8891 		}
8892 	} while (multirt_resolve_next);
8893 
8894 	ip1dbg(("ip_newroute: dropped\n"));
8895 	/* Did this packet originate externally? */
8896 	if (mp->b_prev) {
8897 		mp->b_next = NULL;
8898 		mp->b_prev = NULL;
8899 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
8900 	} else {
8901 		if (dst_ill != NULL) {
8902 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
8903 		} else {
8904 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
8905 		}
8906 	}
8907 	ASSERT(copy_mp == NULL);
8908 	MULTIRT_DEBUG_UNTAG(first_mp);
8909 	freemsg(first_mp);
8910 	if (ire != NULL)
8911 		ire_refrele(ire);
8912 	if (sire != NULL)
8913 		ire_refrele(sire);
8914 	if (src_ipif != NULL)
8915 		ipif_refrele(src_ipif);
8916 	if (dst_ill != NULL)
8917 		ill_refrele(dst_ill);
8918 	return;
8919 
8920 icmp_err_ret:
8921 	ip1dbg(("ip_newroute: no route\n"));
8922 	if (src_ipif != NULL)
8923 		ipif_refrele(src_ipif);
8924 	if (dst_ill != NULL)
8925 		ill_refrele(dst_ill);
8926 	if (sire != NULL)
8927 		ire_refrele(sire);
8928 	/* Did this packet originate externally? */
8929 	if (mp->b_prev) {
8930 		mp->b_next = NULL;
8931 		mp->b_prev = NULL;
8932 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
8933 		q = WR(q);
8934 	} else {
8935 		/*
8936 		 * There is no outgoing ill, so just increment the
8937 		 * system MIB.
8938 		 */
8939 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
8940 		/*
8941 		 * Since ip_wput() isn't close to finished, we fill
8942 		 * in enough of the header for credible error reporting.
8943 		 */
8944 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
8945 			/* Failed */
8946 			MULTIRT_DEBUG_UNTAG(first_mp);
8947 			freemsg(first_mp);
8948 			if (ire != NULL)
8949 				ire_refrele(ire);
8950 			return;
8951 		}
8952 	}
8953 
8954 	/*
8955 	 * At this point we will have ire only if RTF_BLACKHOLE
8956 	 * or RTF_REJECT flags are set on the IRE. It will not
8957 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8958 	 */
8959 	if (ire != NULL) {
8960 		if (ire->ire_flags & RTF_BLACKHOLE) {
8961 			ire_refrele(ire);
8962 			MULTIRT_DEBUG_UNTAG(first_mp);
8963 			freemsg(first_mp);
8964 			return;
8965 		}
8966 		ire_refrele(ire);
8967 	}
8968 	if (ip_source_routed(ipha, ipst)) {
8969 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
8970 		    zoneid, ipst);
8971 		return;
8972 	}
8973 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
8974 }
8975 
8976 ip_opt_info_t zero_info;
8977 
8978 /*
8979  * IPv4 -
8980  * ip_newroute_ipif is called by ip_wput_multicast and
8981  * ip_rput_forward_multicast whenever we need to send
8982  * out a packet to a destination address for which we do not have specific
8983  * routing information. It is used when the packet will be sent out
8984  * on a specific interface. It is also called by ip_wput() when IP_BOUND_IF
8985  * socket option is set or icmp error message wants to go out on a particular
8986  * interface for a unicast packet.
8987  *
8988  * In most cases, the destination address is resolved thanks to the ipif
8989  * intrinsic resolver. However, there are some cases where the call to
8990  * ip_newroute_ipif must take into account the potential presence of
8991  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
8992  * that uses the interface. This is specified through flags,
8993  * which can be a combination of:
8994  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
8995  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
8996  *   and flags. Additionally, the packet source address has to be set to
8997  *   the specified address. The caller is thus expected to set this flag
8998  *   if the packet has no specific source address yet.
8999  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
9000  *   flag, the resulting ire will inherit the flag. All unresolved routes
9001  *   to the destination must be explored in the same call to
9002  *   ip_newroute_ipif().
9003  */
9004 static void
9005 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
9006     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
9007 {
9008 	areq_t	*areq;
9009 	ire_t	*ire = NULL;
9010 	mblk_t	*res_mp;
9011 	ipaddr_t *addrp;
9012 	mblk_t *first_mp;
9013 	ire_t	*save_ire = NULL;
9014 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
9015 	ipif_t	*src_ipif = NULL;
9016 	ushort_t ire_marks = 0;
9017 	ill_t	*dst_ill = NULL;
9018 	boolean_t mctl_present;
9019 	ipsec_out_t *io;
9020 	ipha_t *ipha;
9021 	int	ihandle = 0;
9022 	mblk_t	*saved_mp;
9023 	ire_t   *fire = NULL;
9024 	mblk_t  *copy_mp = NULL;
9025 	boolean_t multirt_resolve_next;
9026 	boolean_t unspec_src;
9027 	ipaddr_t ipha_dst;
9028 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
9029 
9030 	/*
9031 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
9032 	 * here for uniformity
9033 	 */
9034 	ipif_refhold(ipif);
9035 
9036 	/*
9037 	 * This loop is run only once in most cases.
9038 	 * We loop to resolve further routes only when the destination
9039 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
9040 	 */
9041 	do {
9042 		if (dst_ill != NULL) {
9043 			ill_refrele(dst_ill);
9044 			dst_ill = NULL;
9045 		}
9046 		if (src_ipif != NULL) {
9047 			ipif_refrele(src_ipif);
9048 			src_ipif = NULL;
9049 		}
9050 		multirt_resolve_next = B_FALSE;
9051 
9052 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9053 		    ipif->ipif_ill->ill_name));
9054 
9055 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
9056 		if (mctl_present)
9057 			io = (ipsec_out_t *)first_mp->b_rptr;
9058 
9059 		ipha = (ipha_t *)mp->b_rptr;
9060 
9061 		/*
9062 		 * Save the packet destination address, we may need it after
9063 		 * the packet has been consumed.
9064 		 */
9065 		ipha_dst = ipha->ipha_dst;
9066 
9067 		/*
9068 		 * If the interface is a pt-pt interface we look for an
9069 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9070 		 * local_address and the pt-pt destination address. Otherwise
9071 		 * we just match the local address.
9072 		 * NOTE: dst could be different than ipha->ipha_dst in case
9073 		 * of sending igmp multicast packets over a point-to-point
9074 		 * connection.
9075 		 * Thus we must be careful enough to check ipha_dst to be a
9076 		 * multicast address, otherwise it will take xmit_if path for
9077 		 * multicast packets resulting into kernel stack overflow by
9078 		 * repeated calls to ip_newroute_ipif from ire_send().
9079 		 */
9080 		if (CLASSD(ipha_dst) &&
9081 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9082 			goto err_ret;
9083 		}
9084 
9085 		/*
9086 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9087 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9088 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9089 		 * propagate its flags to the new ire.
9090 		 */
9091 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9092 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9093 			ip2dbg(("ip_newroute_ipif: "
9094 			    "ipif_lookup_multi_ire("
9095 			    "ipif %p, dst %08x) = fire %p\n",
9096 			    (void *)ipif, ntohl(dst), (void *)fire));
9097 		}
9098 
9099 		if (mctl_present && io->ipsec_out_attach_if) {
9100 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
9101 			    io->ipsec_out_ill_index, B_FALSE, ipst);
9102 
9103 			/* Failure case frees things for us. */
9104 			if (attach_ill == NULL) {
9105 				ipif_refrele(ipif);
9106 				if (fire != NULL)
9107 					ire_refrele(fire);
9108 				return;
9109 			}
9110 
9111 			/*
9112 			 * Check if we need an ire that will not be
9113 			 * looked up by anybody else i.e. HIDDEN.
9114 			 */
9115 			if (ill_is_probeonly(attach_ill)) {
9116 				ire_marks = IRE_MARK_HIDDEN;
9117 			}
9118 			/*
9119 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
9120 			 * case.
9121 			 */
9122 			dst_ill = ipif->ipif_ill;
9123 			/* attach_ill has been refheld by ip_grab_attach_ill */
9124 			ASSERT(dst_ill == attach_ill);
9125 		} else {
9126 			/*
9127 			 * If the interface belongs to an interface group,
9128 			 * make sure the next possible interface in the group
9129 			 * is used.  This encourages load spreading among
9130 			 * peers in an interface group.
9131 			 * Note: load spreading is disabled for RTF_MULTIRT
9132 			 * routes.
9133 			 */
9134 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9135 			    (fire->ire_flags & RTF_MULTIRT)) {
9136 				/*
9137 				 * Don't perform outbound load spreading
9138 				 * in the case of an RTF_MULTIRT issued route,
9139 				 * we actually typically want to replicate
9140 				 * outgoing packets through particular
9141 				 * interfaces.
9142 				 */
9143 				dst_ill = ipif->ipif_ill;
9144 				ill_refhold(dst_ill);
9145 			} else {
9146 				dst_ill = ip_newroute_get_dst_ill(
9147 				    ipif->ipif_ill);
9148 			}
9149 			if (dst_ill == NULL) {
9150 				if (ip_debug > 2) {
9151 					pr_addr_dbg("ip_newroute_ipif: "
9152 					    "no dst ill for dst %s\n",
9153 					    AF_INET, &dst);
9154 				}
9155 				goto err_ret;
9156 			}
9157 		}
9158 
9159 		/*
9160 		 * Pick a source address preferring non-deprecated ones.
9161 		 * Unlike ip_newroute, we don't do any source address
9162 		 * selection here since for multicast it really does not help
9163 		 * in inbound load spreading as in the unicast case.
9164 		 */
9165 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9166 		    (fire->ire_flags & RTF_SETSRC)) {
9167 			/*
9168 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9169 			 * on that interface. This ire has RTF_SETSRC flag, so
9170 			 * the source address of the packet must be changed.
9171 			 * Check that the ipif matching the requested source
9172 			 * address still exists.
9173 			 */
9174 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9175 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9176 		}
9177 
9178 		unspec_src = (connp != NULL && connp->conn_unspec_src);
9179 
9180 		if (((!ipif->ipif_isv6 && ipif->ipif_lcl_addr == INADDR_ANY) ||
9181 		    (ipif->ipif_flags & (IPIF_DEPRECATED|IPIF_UP)) != IPIF_UP ||
9182 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9183 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9184 		    (src_ipif == NULL) &&
9185 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
9186 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9187 			if (src_ipif == NULL) {
9188 				if (ip_debug > 2) {
9189 					/* ip1dbg */
9190 					pr_addr_dbg("ip_newroute_ipif: "
9191 					    "no src for dst %s",
9192 					    AF_INET, &dst);
9193 				}
9194 				ip1dbg((" through interface %s\n",
9195 				    dst_ill->ill_name));
9196 				goto err_ret;
9197 			}
9198 			ipif_refrele(ipif);
9199 			ipif = src_ipif;
9200 			ipif_refhold(ipif);
9201 		}
9202 		if (src_ipif == NULL) {
9203 			src_ipif = ipif;
9204 			ipif_refhold(src_ipif);
9205 		}
9206 
9207 		/*
9208 		 * Assign a source address while we have the conn.
9209 		 * We can't have ip_wput_ire pick a source address when the
9210 		 * packet returns from arp since conn_unspec_src might be set
9211 		 * and we lose the conn when going through arp.
9212 		 */
9213 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
9214 			ipha->ipha_src = src_ipif->ipif_src_addr;
9215 
9216 		/*
9217 		 * In the case of IP_BOUND_IF and IP_PKTINFO, it is possible
9218 		 * that the outgoing interface does not have an interface ire.
9219 		 */
9220 		if (CLASSD(ipha_dst) && (connp == NULL ||
9221 		    connp->conn_outgoing_ill == NULL) &&
9222 		    infop->ip_opt_ill_index == 0) {
9223 			/* ipif_to_ire returns an held ire */
9224 			ire = ipif_to_ire(ipif);
9225 			if (ire == NULL)
9226 				goto err_ret;
9227 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9228 				goto err_ret;
9229 			/*
9230 			 * ihandle is needed when the ire is added to
9231 			 * cache table.
9232 			 */
9233 			save_ire = ire;
9234 			ihandle = save_ire->ire_ihandle;
9235 
9236 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9237 			    "flags %04x\n",
9238 			    (void *)ire, (void *)ipif, flags));
9239 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9240 			    (fire->ire_flags & RTF_MULTIRT)) {
9241 				/*
9242 				 * As requested by flags, an IRE_OFFSUBNET was
9243 				 * looked up on that interface. This ire has
9244 				 * RTF_MULTIRT flag, so the resolution loop will
9245 				 * be re-entered to resolve additional routes on
9246 				 * other interfaces. For that purpose, a copy of
9247 				 * the packet is performed at this point.
9248 				 */
9249 				fire->ire_last_used_time = lbolt;
9250 				copy_mp = copymsg(first_mp);
9251 				if (copy_mp) {
9252 					MULTIRT_DEBUG_TAG(copy_mp);
9253 				}
9254 			}
9255 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9256 			    (fire->ire_flags & RTF_SETSRC)) {
9257 				/*
9258 				 * As requested by flags, an IRE_OFFSUBET was
9259 				 * looked up on that interface. This ire has
9260 				 * RTF_SETSRC flag, so the source address of the
9261 				 * packet must be changed.
9262 				 */
9263 				ipha->ipha_src = fire->ire_src_addr;
9264 			}
9265 		} else {
9266 			ASSERT((connp == NULL) ||
9267 			    (connp->conn_outgoing_ill != NULL) ||
9268 			    (connp->conn_dontroute) ||
9269 			    infop->ip_opt_ill_index != 0);
9270 			/*
9271 			 * The only ways we can come here are:
9272 			 * 1) IP_BOUND_IF socket option is set
9273 			 * 2) SO_DONTROUTE socket option is set
9274 			 * 3) IP_PKTINFO option is passed in as ancillary data.
9275 			 * In all cases, the new ire will not be added
9276 			 * into cache table.
9277 			 */
9278 			ire_marks |= IRE_MARK_NOADD;
9279 		}
9280 
9281 		switch (ipif->ipif_net_type) {
9282 		case IRE_IF_NORESOLVER: {
9283 			/* We have what we need to build an IRE_CACHE. */
9284 
9285 			if ((dst_ill->ill_phys_addr_length != IP_ADDR_LEN) &&
9286 			    (dst_ill->ill_resolver_mp == NULL)) {
9287 				ip1dbg(("ip_newroute_ipif: dst_ill %p "
9288 				    "for IRE_IF_NORESOLVER ire %p has "
9289 				    "no ill_resolver_mp\n",
9290 				    (void *)dst_ill, (void *)ire));
9291 				break;
9292 			}
9293 
9294 			/*
9295 			 * The new ire inherits the IRE_OFFSUBNET flags
9296 			 * and source address, if this was requested.
9297 			 */
9298 			ire = ire_create(
9299 			    (uchar_t *)&dst,		/* dest address */
9300 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9301 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9302 			    NULL,			/* gateway address */
9303 			    &ipif->ipif_mtu,
9304 			    NULL,			/* no src nce */
9305 			    dst_ill->ill_rq,		/* recv-from queue */
9306 			    dst_ill->ill_wq,		/* send-to queue */
9307 			    IRE_CACHE,
9308 			    src_ipif,
9309 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9310 			    (fire != NULL) ?		/* Parent handle */
9311 			    fire->ire_phandle : 0,
9312 			    ihandle,			/* Interface handle */
9313 			    (fire != NULL) ?
9314 			    (fire->ire_flags &
9315 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9316 			    (save_ire == NULL ? &ire_uinfo_null :
9317 			    &save_ire->ire_uinfo),
9318 			    NULL,
9319 			    NULL,
9320 			    ipst);
9321 
9322 			if (ire == NULL) {
9323 				if (save_ire != NULL)
9324 					ire_refrele(save_ire);
9325 				break;
9326 			}
9327 
9328 			ire->ire_marks |= ire_marks;
9329 
9330 			/*
9331 			 * If IRE_MARK_NOADD is set then we need to convert
9332 			 * the max_fragp to a useable value now. This is
9333 			 * normally done in ire_add_v[46]. We also need to
9334 			 * associate the ire with an nce (normally would be
9335 			 * done in ip_wput_nondata()).
9336 			 *
9337 			 * Note that IRE_MARK_NOADD packets created here
9338 			 * do not have a non-null ire_mp pointer. The null
9339 			 * value of ire_bucket indicates that they were
9340 			 * never added.
9341 			 */
9342 			if (ire->ire_marks & IRE_MARK_NOADD) {
9343 				uint_t  max_frag;
9344 
9345 				max_frag = *ire->ire_max_fragp;
9346 				ire->ire_max_fragp = NULL;
9347 				ire->ire_max_frag = max_frag;
9348 
9349 				if ((ire->ire_nce = ndp_lookup_v4(
9350 				    ire_to_ill(ire),
9351 				    (ire->ire_gateway_addr != INADDR_ANY ?
9352 				    &ire->ire_gateway_addr : &ire->ire_addr),
9353 				    B_FALSE)) == NULL) {
9354 					if (save_ire != NULL)
9355 						ire_refrele(save_ire);
9356 					break;
9357 				}
9358 				ASSERT(ire->ire_nce->nce_state ==
9359 				    ND_REACHABLE);
9360 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9361 			}
9362 
9363 			/* Prevent save_ire from getting deleted */
9364 			if (save_ire != NULL) {
9365 				IRB_REFHOLD(save_ire->ire_bucket);
9366 				/* Has it been removed already ? */
9367 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9368 					IRB_REFRELE(save_ire->ire_bucket);
9369 					ire_refrele(save_ire);
9370 					break;
9371 				}
9372 			}
9373 
9374 			ire_add_then_send(q, ire, first_mp);
9375 
9376 			/* Assert that save_ire is not deleted yet. */
9377 			if (save_ire != NULL) {
9378 				ASSERT(save_ire->ire_ptpn != NULL);
9379 				IRB_REFRELE(save_ire->ire_bucket);
9380 				ire_refrele(save_ire);
9381 				save_ire = NULL;
9382 			}
9383 			if (fire != NULL) {
9384 				ire_refrele(fire);
9385 				fire = NULL;
9386 			}
9387 
9388 			/*
9389 			 * the resolution loop is re-entered if this
9390 			 * was requested through flags and if we
9391 			 * actually are in a multirouting case.
9392 			 */
9393 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9394 				boolean_t need_resolve =
9395 				    ire_multirt_need_resolve(ipha_dst,
9396 				    MBLK_GETLABEL(copy_mp), ipst);
9397 				if (!need_resolve) {
9398 					MULTIRT_DEBUG_UNTAG(copy_mp);
9399 					freemsg(copy_mp);
9400 					copy_mp = NULL;
9401 				} else {
9402 					/*
9403 					 * ipif_lookup_group() calls
9404 					 * ire_lookup_multi() that uses
9405 					 * ire_ftable_lookup() to find
9406 					 * an IRE_INTERFACE for the group.
9407 					 * In the multirt case,
9408 					 * ire_lookup_multi() then invokes
9409 					 * ire_multirt_lookup() to find
9410 					 * the next resolvable ire.
9411 					 * As a result, we obtain an new
9412 					 * interface, derived from the
9413 					 * next ire.
9414 					 */
9415 					ipif_refrele(ipif);
9416 					ipif = ipif_lookup_group(ipha_dst,
9417 					    zoneid, ipst);
9418 					ip2dbg(("ip_newroute_ipif: "
9419 					    "multirt dst %08x, ipif %p\n",
9420 					    htonl(dst), (void *)ipif));
9421 					if (ipif != NULL) {
9422 						mp = copy_mp;
9423 						copy_mp = NULL;
9424 						multirt_resolve_next = B_TRUE;
9425 						continue;
9426 					} else {
9427 						freemsg(copy_mp);
9428 					}
9429 				}
9430 			}
9431 			if (ipif != NULL)
9432 				ipif_refrele(ipif);
9433 			ill_refrele(dst_ill);
9434 			ipif_refrele(src_ipif);
9435 			return;
9436 		}
9437 		case IRE_IF_RESOLVER:
9438 			/*
9439 			 * We can't build an IRE_CACHE yet, but at least
9440 			 * we found a resolver that can help.
9441 			 */
9442 			res_mp = dst_ill->ill_resolver_mp;
9443 			if (!OK_RESOLVER_MP(res_mp))
9444 				break;
9445 
9446 			/*
9447 			 * We obtain a partial IRE_CACHE which we will pass
9448 			 * along with the resolver query.  When the response
9449 			 * comes back it will be there ready for us to add.
9450 			 * The new ire inherits the IRE_OFFSUBNET flags
9451 			 * and source address, if this was requested.
9452 			 * The ire_max_frag is atomically set under the
9453 			 * irebucket lock in ire_add_v[46]. Only in the
9454 			 * case of IRE_MARK_NOADD, we set it here itself.
9455 			 */
9456 			ire = ire_create_mp(
9457 			    (uchar_t *)&dst,		/* dest address */
9458 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9459 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9460 			    NULL,			/* gateway address */
9461 			    (ire_marks & IRE_MARK_NOADD) ?
9462 			    ipif->ipif_mtu : 0,		/* max_frag */
9463 			    NULL,			/* no src nce */
9464 			    dst_ill->ill_rq,		/* recv-from queue */
9465 			    dst_ill->ill_wq,		/* send-to queue */
9466 			    IRE_CACHE,
9467 			    src_ipif,
9468 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9469 			    (fire != NULL) ?		/* Parent handle */
9470 			    fire->ire_phandle : 0,
9471 			    ihandle,			/* Interface handle */
9472 			    (fire != NULL) ?		/* flags if any */
9473 			    (fire->ire_flags &
9474 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9475 			    (save_ire == NULL ? &ire_uinfo_null :
9476 			    &save_ire->ire_uinfo),
9477 			    NULL,
9478 			    NULL,
9479 			    ipst);
9480 
9481 			if (save_ire != NULL) {
9482 				ire_refrele(save_ire);
9483 				save_ire = NULL;
9484 			}
9485 			if (ire == NULL)
9486 				break;
9487 
9488 			ire->ire_marks |= ire_marks;
9489 			/*
9490 			 * Construct message chain for the resolver of the
9491 			 * form:
9492 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9493 			 *
9494 			 * NOTE : ire will be added later when the response
9495 			 * comes back from ARP. If the response does not
9496 			 * come back, ARP frees the packet. For this reason,
9497 			 * we can't REFHOLD the bucket of save_ire to prevent
9498 			 * deletions. We may not be able to REFRELE the
9499 			 * bucket if the response never comes back.
9500 			 * Thus, before adding the ire, ire_add_v4 will make
9501 			 * sure that the interface route does not get deleted.
9502 			 * This is the only case unlike ip_newroute_v6,
9503 			 * ip_newroute_ipif_v6 where we can always prevent
9504 			 * deletions because ire_add_then_send is called after
9505 			 * creating the IRE.
9506 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9507 			 * does not add this IRE into the IRE CACHE.
9508 			 */
9509 			ASSERT(ire->ire_mp != NULL);
9510 			ire->ire_mp->b_cont = first_mp;
9511 			/* Have saved_mp handy, for cleanup if canput fails */
9512 			saved_mp = mp;
9513 			mp = copyb(res_mp);
9514 			if (mp == NULL) {
9515 				/* Prepare for cleanup */
9516 				mp = saved_mp; /* pkt */
9517 				ire_delete(ire); /* ire_mp */
9518 				ire = NULL;
9519 				if (copy_mp != NULL) {
9520 					MULTIRT_DEBUG_UNTAG(copy_mp);
9521 					freemsg(copy_mp);
9522 					copy_mp = NULL;
9523 				}
9524 				break;
9525 			}
9526 			linkb(mp, ire->ire_mp);
9527 
9528 			/*
9529 			 * Fill in the source and dest addrs for the resolver.
9530 			 * NOTE: this depends on memory layouts imposed by
9531 			 * ill_init().
9532 			 */
9533 			areq = (areq_t *)mp->b_rptr;
9534 			addrp = (ipaddr_t *)((char *)areq +
9535 			    areq->areq_sender_addr_offset);
9536 			*addrp = ire->ire_src_addr;
9537 			addrp = (ipaddr_t *)((char *)areq +
9538 			    areq->areq_target_addr_offset);
9539 			*addrp = dst;
9540 			/* Up to the resolver. */
9541 			if (canputnext(dst_ill->ill_rq) &&
9542 			    !(dst_ill->ill_arp_closing)) {
9543 				putnext(dst_ill->ill_rq, mp);
9544 				/*
9545 				 * The response will come back in ip_wput
9546 				 * with db_type IRE_DB_TYPE.
9547 				 */
9548 			} else {
9549 				mp->b_cont = NULL;
9550 				freeb(mp); /* areq */
9551 				ire_delete(ire); /* ire_mp */
9552 				saved_mp->b_next = NULL;
9553 				saved_mp->b_prev = NULL;
9554 				freemsg(first_mp); /* pkt */
9555 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9556 			}
9557 
9558 			if (fire != NULL) {
9559 				ire_refrele(fire);
9560 				fire = NULL;
9561 			}
9562 
9563 
9564 			/*
9565 			 * The resolution loop is re-entered if this was
9566 			 * requested through flags and we actually are
9567 			 * in a multirouting case.
9568 			 */
9569 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9570 				boolean_t need_resolve =
9571 				    ire_multirt_need_resolve(ipha_dst,
9572 				    MBLK_GETLABEL(copy_mp), ipst);
9573 				if (!need_resolve) {
9574 					MULTIRT_DEBUG_UNTAG(copy_mp);
9575 					freemsg(copy_mp);
9576 					copy_mp = NULL;
9577 				} else {
9578 					/*
9579 					 * ipif_lookup_group() calls
9580 					 * ire_lookup_multi() that uses
9581 					 * ire_ftable_lookup() to find
9582 					 * an IRE_INTERFACE for the group.
9583 					 * In the multirt case,
9584 					 * ire_lookup_multi() then invokes
9585 					 * ire_multirt_lookup() to find
9586 					 * the next resolvable ire.
9587 					 * As a result, we obtain an new
9588 					 * interface, derived from the
9589 					 * next ire.
9590 					 */
9591 					ipif_refrele(ipif);
9592 					ipif = ipif_lookup_group(ipha_dst,
9593 					    zoneid, ipst);
9594 					if (ipif != NULL) {
9595 						mp = copy_mp;
9596 						copy_mp = NULL;
9597 						multirt_resolve_next = B_TRUE;
9598 						continue;
9599 					} else {
9600 						freemsg(copy_mp);
9601 					}
9602 				}
9603 			}
9604 			if (ipif != NULL)
9605 				ipif_refrele(ipif);
9606 			ill_refrele(dst_ill);
9607 			ipif_refrele(src_ipif);
9608 			return;
9609 		default:
9610 			break;
9611 		}
9612 	} while (multirt_resolve_next);
9613 
9614 err_ret:
9615 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9616 	if (fire != NULL)
9617 		ire_refrele(fire);
9618 	ipif_refrele(ipif);
9619 	/* Did this packet originate externally? */
9620 	if (dst_ill != NULL)
9621 		ill_refrele(dst_ill);
9622 	if (src_ipif != NULL)
9623 		ipif_refrele(src_ipif);
9624 	if (mp->b_prev || mp->b_next) {
9625 		mp->b_next = NULL;
9626 		mp->b_prev = NULL;
9627 	} else {
9628 		/*
9629 		 * Since ip_wput() isn't close to finished, we fill
9630 		 * in enough of the header for credible error reporting.
9631 		 */
9632 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9633 			/* Failed */
9634 			freemsg(first_mp);
9635 			if (ire != NULL)
9636 				ire_refrele(ire);
9637 			return;
9638 		}
9639 	}
9640 	/*
9641 	 * At this point we will have ire only if RTF_BLACKHOLE
9642 	 * or RTF_REJECT flags are set on the IRE. It will not
9643 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9644 	 */
9645 	if (ire != NULL) {
9646 		if (ire->ire_flags & RTF_BLACKHOLE) {
9647 			ire_refrele(ire);
9648 			freemsg(first_mp);
9649 			return;
9650 		}
9651 		ire_refrele(ire);
9652 	}
9653 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9654 }
9655 
9656 /* Name/Value Table Lookup Routine */
9657 char *
9658 ip_nv_lookup(nv_t *nv, int value)
9659 {
9660 	if (!nv)
9661 		return (NULL);
9662 	for (; nv->nv_name; nv++) {
9663 		if (nv->nv_value == value)
9664 			return (nv->nv_name);
9665 	}
9666 	return ("unknown");
9667 }
9668 
9669 /*
9670  * This is a module open, i.e. this is a control stream for access
9671  * to a DLPI device.  We allocate an ill_t as the instance data in
9672  * this case.
9673  */
9674 int
9675 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9676 {
9677 	ill_t	*ill;
9678 	int	err;
9679 	zoneid_t zoneid;
9680 	netstack_t *ns;
9681 	ip_stack_t *ipst;
9682 
9683 	/*
9684 	 * Prevent unprivileged processes from pushing IP so that
9685 	 * they can't send raw IP.
9686 	 */
9687 	if (secpolicy_net_rawaccess(credp) != 0)
9688 		return (EPERM);
9689 
9690 	ns = netstack_find_by_cred(credp);
9691 	ASSERT(ns != NULL);
9692 	ipst = ns->netstack_ip;
9693 	ASSERT(ipst != NULL);
9694 
9695 	/*
9696 	 * For exclusive stacks we set the zoneid to zero
9697 	 * to make IP operate as if in the global zone.
9698 	 */
9699 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9700 		zoneid = GLOBAL_ZONEID;
9701 	else
9702 		zoneid = crgetzoneid(credp);
9703 
9704 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9705 	q->q_ptr = WR(q)->q_ptr = ill;
9706 	ill->ill_ipst = ipst;
9707 	ill->ill_zoneid = zoneid;
9708 
9709 	/*
9710 	 * ill_init initializes the ill fields and then sends down
9711 	 * down a DL_INFO_REQ after calling qprocson.
9712 	 */
9713 	err = ill_init(q, ill);
9714 	if (err != 0) {
9715 		mi_free(ill);
9716 		netstack_rele(ipst->ips_netstack);
9717 		q->q_ptr = NULL;
9718 		WR(q)->q_ptr = NULL;
9719 		return (err);
9720 	}
9721 
9722 	/* ill_init initializes the ipsq marking this thread as writer */
9723 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
9724 	/* Wait for the DL_INFO_ACK */
9725 	mutex_enter(&ill->ill_lock);
9726 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9727 		/*
9728 		 * Return value of 0 indicates a pending signal.
9729 		 */
9730 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9731 		if (err == 0) {
9732 			mutex_exit(&ill->ill_lock);
9733 			(void) ip_close(q, 0);
9734 			return (EINTR);
9735 		}
9736 	}
9737 	mutex_exit(&ill->ill_lock);
9738 
9739 	/*
9740 	 * ip_rput_other could have set an error  in ill_error on
9741 	 * receipt of M_ERROR.
9742 	 */
9743 
9744 	err = ill->ill_error;
9745 	if (err != 0) {
9746 		(void) ip_close(q, 0);
9747 		return (err);
9748 	}
9749 
9750 	ill->ill_credp = credp;
9751 	crhold(credp);
9752 
9753 	mutex_enter(&ipst->ips_ip_mi_lock);
9754 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
9755 	    credp);
9756 	mutex_exit(&ipst->ips_ip_mi_lock);
9757 	if (err) {
9758 		(void) ip_close(q, 0);
9759 		return (err);
9760 	}
9761 	return (0);
9762 }
9763 
9764 /* For /dev/ip aka AF_INET open */
9765 int
9766 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9767 {
9768 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
9769 }
9770 
9771 /* For /dev/ip6 aka AF_INET6 open */
9772 int
9773 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9774 {
9775 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
9776 }
9777 
9778 /* IP open routine. */
9779 int
9780 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9781     boolean_t isv6)
9782 {
9783 	conn_t 		*connp;
9784 	major_t		maj;
9785 	zoneid_t	zoneid;
9786 	netstack_t	*ns;
9787 	ip_stack_t	*ipst;
9788 
9789 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9790 
9791 	/* Allow reopen. */
9792 	if (q->q_ptr != NULL)
9793 		return (0);
9794 
9795 	if (sflag & MODOPEN) {
9796 		/* This is a module open */
9797 		return (ip_modopen(q, devp, flag, sflag, credp));
9798 	}
9799 
9800 	ns = netstack_find_by_cred(credp);
9801 	ASSERT(ns != NULL);
9802 	ipst = ns->netstack_ip;
9803 	ASSERT(ipst != NULL);
9804 
9805 	/*
9806 	 * For exclusive stacks we set the zoneid to zero
9807 	 * to make IP operate as if in the global zone.
9808 	 */
9809 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9810 		zoneid = GLOBAL_ZONEID;
9811 	else
9812 		zoneid = crgetzoneid(credp);
9813 
9814 	/*
9815 	 * We are opening as a device. This is an IP client stream, and we
9816 	 * allocate an conn_t as the instance data.
9817 	 */
9818 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
9819 
9820 	/*
9821 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
9822 	 * done by netstack_find_by_cred()
9823 	 */
9824 	netstack_rele(ipst->ips_netstack);
9825 
9826 	connp->conn_zoneid = zoneid;
9827 
9828 	connp->conn_upq = q;
9829 	q->q_ptr = WR(q)->q_ptr = connp;
9830 
9831 	if (flag & SO_SOCKSTR)
9832 		connp->conn_flags |= IPCL_SOCKET;
9833 
9834 	/* Minor tells us which /dev entry was opened */
9835 	if (isv6) {
9836 		connp->conn_flags |= IPCL_ISV6;
9837 		connp->conn_af_isv6 = B_TRUE;
9838 		ip_setpktversion(connp, isv6, B_FALSE, ipst);
9839 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9840 	} else {
9841 		connp->conn_af_isv6 = B_FALSE;
9842 		connp->conn_pkt_isv6 = B_FALSE;
9843 	}
9844 
9845 	if ((connp->conn_dev = inet_minor_alloc(ip_minor_arena)) == 0) {
9846 		/* CONN_DEC_REF takes care of netstack_rele() */
9847 		q->q_ptr = WR(q)->q_ptr = NULL;
9848 		CONN_DEC_REF(connp);
9849 		return (EBUSY);
9850 	}
9851 
9852 	maj = getemajor(*devp);
9853 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9854 
9855 	/*
9856 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9857 	 */
9858 	connp->conn_cred = credp;
9859 
9860 	/*
9861 	 * Handle IP_RTS_REQUEST and other ioctls which use conn_recv
9862 	 */
9863 	connp->conn_recv = ip_conn_input;
9864 
9865 	crhold(connp->conn_cred);
9866 
9867 	/*
9868 	 * If the caller has the process-wide flag set, then default to MAC
9869 	 * exempt mode.  This allows read-down to unlabeled hosts.
9870 	 */
9871 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9872 		connp->conn_mac_exempt = B_TRUE;
9873 
9874 	connp->conn_rq = q;
9875 	connp->conn_wq = WR(q);
9876 
9877 	/* Non-zero default values */
9878 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9879 
9880 	/*
9881 	 * Make the conn globally visible to walkers
9882 	 */
9883 	ASSERT(connp->conn_ref == 1);
9884 	mutex_enter(&connp->conn_lock);
9885 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9886 	mutex_exit(&connp->conn_lock);
9887 
9888 	qprocson(q);
9889 
9890 	return (0);
9891 }
9892 
9893 /*
9894  * Change the output format (IPv4 vs. IPv6) for a conn_t.
9895  * Note that there is no race since either ip_output function works - it
9896  * is just an optimization to enter the best ip_output routine directly.
9897  */
9898 void
9899 ip_setpktversion(conn_t *connp, boolean_t isv6, boolean_t bump_mib,
9900     ip_stack_t *ipst)
9901 {
9902 	if (isv6)  {
9903 		if (bump_mib) {
9904 			BUMP_MIB(&ipst->ips_ip6_mib,
9905 			    ipIfStatsOutSwitchIPVersion);
9906 		}
9907 		connp->conn_send = ip_output_v6;
9908 		connp->conn_pkt_isv6 = B_TRUE;
9909 	} else {
9910 		if (bump_mib) {
9911 			BUMP_MIB(&ipst->ips_ip_mib,
9912 			    ipIfStatsOutSwitchIPVersion);
9913 		}
9914 		connp->conn_send = ip_output;
9915 		connp->conn_pkt_isv6 = B_FALSE;
9916 	}
9917 
9918 }
9919 
9920 /*
9921  * See if IPsec needs loading because of the options in mp.
9922  */
9923 static boolean_t
9924 ipsec_opt_present(mblk_t *mp)
9925 {
9926 	uint8_t *optcp, *next_optcp, *opt_endcp;
9927 	struct opthdr *opt;
9928 	struct T_opthdr *topt;
9929 	int opthdr_len;
9930 	t_uscalar_t optname, optlevel;
9931 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9932 	ipsec_req_t *ipsr;
9933 
9934 	/*
9935 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9936 	 * return TRUE.
9937 	 */
9938 
9939 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9940 	opt_endcp = optcp + tor->OPT_length;
9941 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9942 		opthdr_len = sizeof (struct T_opthdr);
9943 	} else {		/* O_OPTMGMT_REQ */
9944 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9945 		opthdr_len = sizeof (struct opthdr);
9946 	}
9947 	for (; optcp < opt_endcp; optcp = next_optcp) {
9948 		if (optcp + opthdr_len > opt_endcp)
9949 			return (B_FALSE);	/* Not enough option header. */
9950 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9951 			topt = (struct T_opthdr *)optcp;
9952 			optlevel = topt->level;
9953 			optname = topt->name;
9954 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9955 		} else {
9956 			opt = (struct opthdr *)optcp;
9957 			optlevel = opt->level;
9958 			optname = opt->name;
9959 			next_optcp = optcp + opthdr_len +
9960 			    _TPI_ALIGN_OPT(opt->len);
9961 		}
9962 		if ((next_optcp < optcp) || /* wraparound pointer space */
9963 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9964 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9965 			return (B_FALSE); /* bad option buffer */
9966 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9967 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9968 			/*
9969 			 * Check to see if it's an all-bypass or all-zeroes
9970 			 * IPsec request.  Don't bother loading IPsec if
9971 			 * the socket doesn't want to use it.  (A good example
9972 			 * is a bypass request.)
9973 			 *
9974 			 * Basically, if any of the non-NEVER bits are set,
9975 			 * load IPsec.
9976 			 */
9977 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
9978 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
9979 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
9980 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
9981 			    != 0)
9982 				return (B_TRUE);
9983 		}
9984 	}
9985 	return (B_FALSE);
9986 }
9987 
9988 /*
9989  * If conn is is waiting for ipsec to finish loading, kick it.
9990  */
9991 /* ARGSUSED */
9992 static void
9993 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
9994 {
9995 	t_scalar_t	optreq_prim;
9996 	mblk_t		*mp;
9997 	cred_t		*cr;
9998 	int		err = 0;
9999 
10000 	/*
10001 	 * This function is called, after ipsec loading is complete.
10002 	 * Since IP checks exclusively and atomically (i.e it prevents
10003 	 * ipsec load from completing until ip_optcom_req completes)
10004 	 * whether ipsec load is complete, there cannot be a race with IP
10005 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
10006 	 */
10007 	mutex_enter(&connp->conn_lock);
10008 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
10009 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
10010 		mp = connp->conn_ipsec_opt_mp;
10011 		connp->conn_ipsec_opt_mp = NULL;
10012 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
10013 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
10014 		mutex_exit(&connp->conn_lock);
10015 
10016 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
10017 
10018 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
10019 		if (optreq_prim == T_OPTMGMT_REQ) {
10020 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10021 			    &ip_opt_obj, B_FALSE);
10022 		} else {
10023 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
10024 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10025 			    &ip_opt_obj, B_FALSE);
10026 		}
10027 		if (err != EINPROGRESS)
10028 			CONN_OPER_PENDING_DONE(connp);
10029 		return;
10030 	}
10031 	mutex_exit(&connp->conn_lock);
10032 }
10033 
10034 /*
10035  * Called from the ipsec_loader thread, outside any perimeter, to tell
10036  * ip qenable any of the queues waiting for the ipsec loader to
10037  * complete.
10038  */
10039 void
10040 ip_ipsec_load_complete(ipsec_stack_t *ipss)
10041 {
10042 	netstack_t *ns = ipss->ipsec_netstack;
10043 
10044 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
10045 }
10046 
10047 /*
10048  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10049  * determines the grp on which it has to become exclusive, queues the mp
10050  * and sq draining restarts the optmgmt
10051  */
10052 static boolean_t
10053 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10054 {
10055 	conn_t *connp = Q_TO_CONN(q);
10056 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
10057 
10058 	/*
10059 	 * Take IPsec requests and treat them special.
10060 	 */
10061 	if (ipsec_opt_present(mp)) {
10062 		/* First check if IPsec is loaded. */
10063 		mutex_enter(&ipss->ipsec_loader_lock);
10064 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
10065 			mutex_exit(&ipss->ipsec_loader_lock);
10066 			return (B_FALSE);
10067 		}
10068 		mutex_enter(&connp->conn_lock);
10069 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10070 
10071 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10072 		connp->conn_ipsec_opt_mp = mp;
10073 		mutex_exit(&connp->conn_lock);
10074 		mutex_exit(&ipss->ipsec_loader_lock);
10075 
10076 		ipsec_loader_loadnow(ipss);
10077 		return (B_TRUE);
10078 	}
10079 	return (B_FALSE);
10080 }
10081 
10082 /*
10083  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10084  * all of them are copied to the conn_t. If the req is "zero", the policy is
10085  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10086  * fields.
10087  * We keep only the latest setting of the policy and thus policy setting
10088  * is not incremental/cumulative.
10089  *
10090  * Requests to set policies with multiple alternative actions will
10091  * go through a different API.
10092  */
10093 int
10094 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10095 {
10096 	uint_t ah_req = 0;
10097 	uint_t esp_req = 0;
10098 	uint_t se_req = 0;
10099 	ipsec_selkey_t sel;
10100 	ipsec_act_t *actp = NULL;
10101 	uint_t nact;
10102 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
10103 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
10104 	ipsec_policy_root_t *pr;
10105 	ipsec_policy_head_t *ph;
10106 	int fam;
10107 	boolean_t is_pol_reset;
10108 	int error = 0;
10109 	netstack_t	*ns = connp->conn_netstack;
10110 	ip_stack_t	*ipst = ns->netstack_ip;
10111 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10112 
10113 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10114 
10115 	/*
10116 	 * The IP_SEC_OPT option does not allow variable length parameters,
10117 	 * hence a request cannot be NULL.
10118 	 */
10119 	if (req == NULL)
10120 		return (EINVAL);
10121 
10122 	ah_req = req->ipsr_ah_req;
10123 	esp_req = req->ipsr_esp_req;
10124 	se_req = req->ipsr_self_encap_req;
10125 
10126 	/*
10127 	 * Are we dealing with a request to reset the policy (i.e.
10128 	 * zero requests).
10129 	 */
10130 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10131 	    (esp_req & REQ_MASK) == 0 &&
10132 	    (se_req & REQ_MASK) == 0);
10133 
10134 	if (!is_pol_reset) {
10135 		/*
10136 		 * If we couldn't load IPsec, fail with "protocol
10137 		 * not supported".
10138 		 * IPsec may not have been loaded for a request with zero
10139 		 * policies, so we don't fail in this case.
10140 		 */
10141 		mutex_enter(&ipss->ipsec_loader_lock);
10142 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10143 			mutex_exit(&ipss->ipsec_loader_lock);
10144 			return (EPROTONOSUPPORT);
10145 		}
10146 		mutex_exit(&ipss->ipsec_loader_lock);
10147 
10148 		/*
10149 		 * Test for valid requests. Invalid algorithms
10150 		 * need to be tested by IPsec code because new
10151 		 * algorithms can be added dynamically.
10152 		 */
10153 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10154 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10155 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10156 			return (EINVAL);
10157 		}
10158 
10159 		/*
10160 		 * Only privileged users can issue these
10161 		 * requests.
10162 		 */
10163 		if (((ah_req & IPSEC_PREF_NEVER) ||
10164 		    (esp_req & IPSEC_PREF_NEVER) ||
10165 		    (se_req & IPSEC_PREF_NEVER)) &&
10166 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10167 			return (EPERM);
10168 		}
10169 
10170 		/*
10171 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10172 		 * are mutually exclusive.
10173 		 */
10174 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10175 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10176 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10177 			/* Both of them are set */
10178 			return (EINVAL);
10179 		}
10180 	}
10181 
10182 	mutex_enter(&connp->conn_lock);
10183 
10184 	/*
10185 	 * If we have already cached policies in ip_bind_connected*(), don't
10186 	 * let them change now. We cache policies for connections
10187 	 * whose src,dst [addr, port] is known.
10188 	 */
10189 	if (connp->conn_policy_cached) {
10190 		mutex_exit(&connp->conn_lock);
10191 		return (EINVAL);
10192 	}
10193 
10194 	/*
10195 	 * We have a zero policies, reset the connection policy if already
10196 	 * set. This will cause the connection to inherit the
10197 	 * global policy, if any.
10198 	 */
10199 	if (is_pol_reset) {
10200 		if (connp->conn_policy != NULL) {
10201 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10202 			connp->conn_policy = NULL;
10203 		}
10204 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10205 		connp->conn_in_enforce_policy = B_FALSE;
10206 		connp->conn_out_enforce_policy = B_FALSE;
10207 		mutex_exit(&connp->conn_lock);
10208 		return (0);
10209 	}
10210 
10211 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10212 	    ipst->ips_netstack);
10213 	if (ph == NULL)
10214 		goto enomem;
10215 
10216 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10217 	if (actp == NULL)
10218 		goto enomem;
10219 
10220 	/*
10221 	 * Always allocate IPv4 policy entries, since they can also
10222 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10223 	 */
10224 	bzero(&sel, sizeof (sel));
10225 	sel.ipsl_valid = IPSL_IPV4;
10226 
10227 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10228 	    ipst->ips_netstack);
10229 	if (pin4 == NULL)
10230 		goto enomem;
10231 
10232 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10233 	    ipst->ips_netstack);
10234 	if (pout4 == NULL)
10235 		goto enomem;
10236 
10237 	if (connp->conn_af_isv6) {
10238 		/*
10239 		 * We're looking at a v6 socket, also allocate the
10240 		 * v6-specific entries...
10241 		 */
10242 		sel.ipsl_valid = IPSL_IPV6;
10243 		pin6 = ipsec_policy_create(&sel, actp, nact,
10244 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10245 		if (pin6 == NULL)
10246 			goto enomem;
10247 
10248 		pout6 = ipsec_policy_create(&sel, actp, nact,
10249 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10250 		if (pout6 == NULL)
10251 			goto enomem;
10252 
10253 		/*
10254 		 * .. and file them away in the right place.
10255 		 */
10256 		fam = IPSEC_AF_V6;
10257 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10258 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10259 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10260 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10261 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10262 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10263 	}
10264 
10265 	ipsec_actvec_free(actp, nact);
10266 
10267 	/*
10268 	 * File the v4 policies.
10269 	 */
10270 	fam = IPSEC_AF_V4;
10271 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10272 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10273 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10274 
10275 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10276 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10277 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10278 
10279 	/*
10280 	 * If the requests need security, set enforce_policy.
10281 	 * If the requests are IPSEC_PREF_NEVER, one should
10282 	 * still set conn_out_enforce_policy so that an ipsec_out
10283 	 * gets attached in ip_wput. This is needed so that
10284 	 * for connections that we don't cache policy in ip_bind,
10285 	 * if global policy matches in ip_wput_attach_policy, we
10286 	 * don't wrongly inherit global policy. Similarly, we need
10287 	 * to set conn_in_enforce_policy also so that we don't verify
10288 	 * policy wrongly.
10289 	 */
10290 	if ((ah_req & REQ_MASK) != 0 ||
10291 	    (esp_req & REQ_MASK) != 0 ||
10292 	    (se_req & REQ_MASK) != 0) {
10293 		connp->conn_in_enforce_policy = B_TRUE;
10294 		connp->conn_out_enforce_policy = B_TRUE;
10295 		connp->conn_flags |= IPCL_CHECK_POLICY;
10296 	}
10297 
10298 	mutex_exit(&connp->conn_lock);
10299 	return (error);
10300 #undef REQ_MASK
10301 
10302 	/*
10303 	 * Common memory-allocation-failure exit path.
10304 	 */
10305 enomem:
10306 	mutex_exit(&connp->conn_lock);
10307 	if (actp != NULL)
10308 		ipsec_actvec_free(actp, nact);
10309 	if (pin4 != NULL)
10310 		IPPOL_REFRELE(pin4, ipst->ips_netstack);
10311 	if (pout4 != NULL)
10312 		IPPOL_REFRELE(pout4, ipst->ips_netstack);
10313 	if (pin6 != NULL)
10314 		IPPOL_REFRELE(pin6, ipst->ips_netstack);
10315 	if (pout6 != NULL)
10316 		IPPOL_REFRELE(pout6, ipst->ips_netstack);
10317 	return (ENOMEM);
10318 }
10319 
10320 /*
10321  * Only for options that pass in an IP addr. Currently only V4 options
10322  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10323  * So this function assumes level is IPPROTO_IP
10324  */
10325 int
10326 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10327     mblk_t *first_mp)
10328 {
10329 	ipif_t *ipif = NULL;
10330 	int error;
10331 	ill_t *ill;
10332 	int zoneid;
10333 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10334 
10335 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10336 
10337 	if (addr != INADDR_ANY || checkonly) {
10338 		ASSERT(connp != NULL);
10339 		zoneid = IPCL_ZONEID(connp);
10340 		if (option == IP_NEXTHOP) {
10341 			ipif = ipif_lookup_onlink_addr(addr,
10342 			    connp->conn_zoneid, ipst);
10343 		} else {
10344 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10345 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10346 			    &error, ipst);
10347 		}
10348 		if (ipif == NULL) {
10349 			if (error == EINPROGRESS)
10350 				return (error);
10351 			else if ((option == IP_MULTICAST_IF) ||
10352 			    (option == IP_NEXTHOP))
10353 				return (EHOSTUNREACH);
10354 			else
10355 				return (EINVAL);
10356 		} else if (checkonly) {
10357 			if (option == IP_MULTICAST_IF) {
10358 				ill = ipif->ipif_ill;
10359 				/* not supported by the virtual network iface */
10360 				if (IS_VNI(ill)) {
10361 					ipif_refrele(ipif);
10362 					return (EINVAL);
10363 				}
10364 			}
10365 			ipif_refrele(ipif);
10366 			return (0);
10367 		}
10368 		ill = ipif->ipif_ill;
10369 		mutex_enter(&connp->conn_lock);
10370 		mutex_enter(&ill->ill_lock);
10371 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10372 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10373 			mutex_exit(&ill->ill_lock);
10374 			mutex_exit(&connp->conn_lock);
10375 			ipif_refrele(ipif);
10376 			return (option == IP_MULTICAST_IF ?
10377 			    EHOSTUNREACH : EINVAL);
10378 		}
10379 	} else {
10380 		mutex_enter(&connp->conn_lock);
10381 	}
10382 
10383 	/* None of the options below are supported on the VNI */
10384 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10385 		mutex_exit(&ill->ill_lock);
10386 		mutex_exit(&connp->conn_lock);
10387 		ipif_refrele(ipif);
10388 		return (EINVAL);
10389 	}
10390 
10391 	switch (option) {
10392 	case IP_DONTFAILOVER_IF:
10393 		/*
10394 		 * This option is used by in.mpathd to ensure
10395 		 * that IPMP probe packets only go out on the
10396 		 * test interfaces. in.mpathd sets this option
10397 		 * on the non-failover interfaces.
10398 		 * For backward compatibility, this option
10399 		 * implicitly sets IP_MULTICAST_IF, as used
10400 		 * be done in bind(), so that ip_wput gets
10401 		 * this ipif to send mcast packets.
10402 		 */
10403 		if (ipif != NULL) {
10404 			ASSERT(addr != INADDR_ANY);
10405 			connp->conn_nofailover_ill = ipif->ipif_ill;
10406 			connp->conn_multicast_ipif = ipif;
10407 		} else {
10408 			ASSERT(addr == INADDR_ANY);
10409 			connp->conn_nofailover_ill = NULL;
10410 			connp->conn_multicast_ipif = NULL;
10411 		}
10412 		break;
10413 
10414 	case IP_MULTICAST_IF:
10415 		connp->conn_multicast_ipif = ipif;
10416 		break;
10417 	case IP_NEXTHOP:
10418 		connp->conn_nexthop_v4 = addr;
10419 		connp->conn_nexthop_set = B_TRUE;
10420 		break;
10421 	}
10422 
10423 	if (ipif != NULL) {
10424 		mutex_exit(&ill->ill_lock);
10425 		mutex_exit(&connp->conn_lock);
10426 		ipif_refrele(ipif);
10427 		return (0);
10428 	}
10429 	mutex_exit(&connp->conn_lock);
10430 	/* We succeded in cleared the option */
10431 	return (0);
10432 }
10433 
10434 /*
10435  * For options that pass in an ifindex specifying the ill. V6 options always
10436  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10437  */
10438 int
10439 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10440     int level, int option, mblk_t *first_mp)
10441 {
10442 	ill_t *ill = NULL;
10443 	int error = 0;
10444 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10445 
10446 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10447 	if (ifindex != 0) {
10448 		ASSERT(connp != NULL);
10449 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10450 		    first_mp, ip_restart_optmgmt, &error, ipst);
10451 		if (ill != NULL) {
10452 			if (checkonly) {
10453 				/* not supported by the virtual network iface */
10454 				if (IS_VNI(ill)) {
10455 					ill_refrele(ill);
10456 					return (EINVAL);
10457 				}
10458 				ill_refrele(ill);
10459 				return (0);
10460 			}
10461 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
10462 			    0, NULL)) {
10463 				ill_refrele(ill);
10464 				ill = NULL;
10465 				mutex_enter(&connp->conn_lock);
10466 				goto setit;
10467 			}
10468 			mutex_enter(&connp->conn_lock);
10469 			mutex_enter(&ill->ill_lock);
10470 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10471 				mutex_exit(&ill->ill_lock);
10472 				mutex_exit(&connp->conn_lock);
10473 				ill_refrele(ill);
10474 				ill = NULL;
10475 				mutex_enter(&connp->conn_lock);
10476 			}
10477 			goto setit;
10478 		} else if (error == EINPROGRESS) {
10479 			return (error);
10480 		} else {
10481 			error = 0;
10482 		}
10483 	}
10484 	mutex_enter(&connp->conn_lock);
10485 setit:
10486 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10487 
10488 	/*
10489 	 * The options below assume that the ILL (if any) transmits and/or
10490 	 * receives traffic. Neither of which is true for the virtual network
10491 	 * interface, so fail setting these on a VNI.
10492 	 */
10493 	if (IS_VNI(ill)) {
10494 		ASSERT(ill != NULL);
10495 		mutex_exit(&ill->ill_lock);
10496 		mutex_exit(&connp->conn_lock);
10497 		ill_refrele(ill);
10498 		return (EINVAL);
10499 	}
10500 
10501 	if (level == IPPROTO_IP) {
10502 		switch (option) {
10503 		case IP_BOUND_IF:
10504 			connp->conn_incoming_ill = ill;
10505 			connp->conn_outgoing_ill = ill;
10506 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10507 			    0 : ifindex;
10508 			break;
10509 
10510 		case IP_MULTICAST_IF:
10511 			/*
10512 			 * This option is an internal special. The socket
10513 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10514 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10515 			 * specifies an ifindex and we try first on V6 ill's.
10516 			 * If we don't find one, we they try using on v4 ill's
10517 			 * intenally and we come here.
10518 			 */
10519 			if (!checkonly && ill != NULL) {
10520 				ipif_t	*ipif;
10521 				ipif = ill->ill_ipif;
10522 
10523 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10524 					mutex_exit(&ill->ill_lock);
10525 					mutex_exit(&connp->conn_lock);
10526 					ill_refrele(ill);
10527 					ill = NULL;
10528 					mutex_enter(&connp->conn_lock);
10529 				} else {
10530 					connp->conn_multicast_ipif = ipif;
10531 				}
10532 			}
10533 			break;
10534 
10535 		case IP_DHCPINIT_IF:
10536 			if (connp->conn_dhcpinit_ill != NULL) {
10537 				/*
10538 				 * We've locked the conn so conn_cleanup_ill()
10539 				 * cannot clear conn_dhcpinit_ill -- so it's
10540 				 * safe to access the ill.
10541 				 */
10542 				ill_t *oill = connp->conn_dhcpinit_ill;
10543 
10544 				ASSERT(oill->ill_dhcpinit != 0);
10545 				atomic_dec_32(&oill->ill_dhcpinit);
10546 				connp->conn_dhcpinit_ill = NULL;
10547 			}
10548 
10549 			if (ill != NULL) {
10550 				connp->conn_dhcpinit_ill = ill;
10551 				atomic_inc_32(&ill->ill_dhcpinit);
10552 			}
10553 			break;
10554 		}
10555 	} else {
10556 		switch (option) {
10557 		case IPV6_BOUND_IF:
10558 			connp->conn_incoming_ill = ill;
10559 			connp->conn_outgoing_ill = ill;
10560 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10561 			    0 : ifindex;
10562 			break;
10563 
10564 		case IPV6_BOUND_PIF:
10565 			/*
10566 			 * Limit all transmit to this ill.
10567 			 * Unlike IPV6_BOUND_IF, using this option
10568 			 * prevents load spreading and failover from
10569 			 * happening when the interface is part of the
10570 			 * group. That's why we don't need to remember
10571 			 * the ifindex in orig_bound_ifindex as in
10572 			 * IPV6_BOUND_IF.
10573 			 */
10574 			connp->conn_outgoing_pill = ill;
10575 			break;
10576 
10577 		case IPV6_DONTFAILOVER_IF:
10578 			/*
10579 			 * This option is used by in.mpathd to ensure
10580 			 * that IPMP probe packets only go out on the
10581 			 * test interfaces. in.mpathd sets this option
10582 			 * on the non-failover interfaces.
10583 			 */
10584 			connp->conn_nofailover_ill = ill;
10585 			/*
10586 			 * For backward compatibility, this option
10587 			 * implicitly sets ip_multicast_ill as used in
10588 			 * IPV6_MULTICAST_IF so that ip_wput gets
10589 			 * this ill to send mcast packets.
10590 			 */
10591 			connp->conn_multicast_ill = ill;
10592 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
10593 			    0 : ifindex;
10594 			break;
10595 
10596 		case IPV6_MULTICAST_IF:
10597 			/*
10598 			 * Set conn_multicast_ill to be the IPv6 ill.
10599 			 * Set conn_multicast_ipif to be an IPv4 ipif
10600 			 * for ifindex to make IPv4 mapped addresses
10601 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10602 			 * Even if no IPv6 ill exists for the ifindex
10603 			 * we need to check for an IPv4 ifindex in order
10604 			 * for this to work with mapped addresses. In that
10605 			 * case only set conn_multicast_ipif.
10606 			 */
10607 			if (!checkonly) {
10608 				if (ifindex == 0) {
10609 					connp->conn_multicast_ill = NULL;
10610 					connp->conn_orig_multicast_ifindex = 0;
10611 					connp->conn_multicast_ipif = NULL;
10612 				} else if (ill != NULL) {
10613 					connp->conn_multicast_ill = ill;
10614 					connp->conn_orig_multicast_ifindex =
10615 					    ifindex;
10616 				}
10617 			}
10618 			break;
10619 		}
10620 	}
10621 
10622 	if (ill != NULL) {
10623 		mutex_exit(&ill->ill_lock);
10624 		mutex_exit(&connp->conn_lock);
10625 		ill_refrele(ill);
10626 		return (0);
10627 	}
10628 	mutex_exit(&connp->conn_lock);
10629 	/*
10630 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10631 	 * locate the ill and could not set the option (ifindex != 0)
10632 	 */
10633 	return (ifindex == 0 ? 0 : EINVAL);
10634 }
10635 
10636 /* This routine sets socket options. */
10637 /* ARGSUSED */
10638 int
10639 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10640     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10641     void *dummy, cred_t *cr, mblk_t *first_mp)
10642 {
10643 	int		*i1 = (int *)invalp;
10644 	conn_t		*connp = Q_TO_CONN(q);
10645 	int		error = 0;
10646 	boolean_t	checkonly;
10647 	ire_t		*ire;
10648 	boolean_t	found;
10649 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10650 
10651 	switch (optset_context) {
10652 
10653 	case SETFN_OPTCOM_CHECKONLY:
10654 		checkonly = B_TRUE;
10655 		/*
10656 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10657 		 * inlen != 0 implies value supplied and
10658 		 * 	we have to "pretend" to set it.
10659 		 * inlen == 0 implies that there is no
10660 		 * 	value part in T_CHECK request and just validation
10661 		 * done elsewhere should be enough, we just return here.
10662 		 */
10663 		if (inlen == 0) {
10664 			*outlenp = 0;
10665 			return (0);
10666 		}
10667 		break;
10668 	case SETFN_OPTCOM_NEGOTIATE:
10669 	case SETFN_UD_NEGOTIATE:
10670 	case SETFN_CONN_NEGOTIATE:
10671 		checkonly = B_FALSE;
10672 		break;
10673 	default:
10674 		/*
10675 		 * We should never get here
10676 		 */
10677 		*outlenp = 0;
10678 		return (EINVAL);
10679 	}
10680 
10681 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10682 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10683 
10684 	/*
10685 	 * For fixed length options, no sanity check
10686 	 * of passed in length is done. It is assumed *_optcom_req()
10687 	 * routines do the right thing.
10688 	 */
10689 
10690 	switch (level) {
10691 	case SOL_SOCKET:
10692 		/*
10693 		 * conn_lock protects the bitfields, and is used to
10694 		 * set the fields atomically.
10695 		 */
10696 		switch (name) {
10697 		case SO_BROADCAST:
10698 			if (!checkonly) {
10699 				/* TODO: use value someplace? */
10700 				mutex_enter(&connp->conn_lock);
10701 				connp->conn_broadcast = *i1 ? 1 : 0;
10702 				mutex_exit(&connp->conn_lock);
10703 			}
10704 			break;	/* goto sizeof (int) option return */
10705 		case SO_USELOOPBACK:
10706 			if (!checkonly) {
10707 				/* TODO: use value someplace? */
10708 				mutex_enter(&connp->conn_lock);
10709 				connp->conn_loopback = *i1 ? 1 : 0;
10710 				mutex_exit(&connp->conn_lock);
10711 			}
10712 			break;	/* goto sizeof (int) option return */
10713 		case SO_DONTROUTE:
10714 			if (!checkonly) {
10715 				mutex_enter(&connp->conn_lock);
10716 				connp->conn_dontroute = *i1 ? 1 : 0;
10717 				mutex_exit(&connp->conn_lock);
10718 			}
10719 			break;	/* goto sizeof (int) option return */
10720 		case SO_REUSEADDR:
10721 			if (!checkonly) {
10722 				mutex_enter(&connp->conn_lock);
10723 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10724 				mutex_exit(&connp->conn_lock);
10725 			}
10726 			break;	/* goto sizeof (int) option return */
10727 		case SO_PROTOTYPE:
10728 			if (!checkonly) {
10729 				mutex_enter(&connp->conn_lock);
10730 				connp->conn_proto = *i1;
10731 				mutex_exit(&connp->conn_lock);
10732 			}
10733 			break;	/* goto sizeof (int) option return */
10734 		case SO_ALLZONES:
10735 			if (!checkonly) {
10736 				mutex_enter(&connp->conn_lock);
10737 				if (IPCL_IS_BOUND(connp)) {
10738 					mutex_exit(&connp->conn_lock);
10739 					return (EINVAL);
10740 				}
10741 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10742 				mutex_exit(&connp->conn_lock);
10743 			}
10744 			break;	/* goto sizeof (int) option return */
10745 		case SO_ANON_MLP:
10746 			if (!checkonly) {
10747 				mutex_enter(&connp->conn_lock);
10748 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10749 				mutex_exit(&connp->conn_lock);
10750 			}
10751 			break;	/* goto sizeof (int) option return */
10752 		case SO_MAC_EXEMPT:
10753 			if (secpolicy_net_mac_aware(cr) != 0 ||
10754 			    IPCL_IS_BOUND(connp))
10755 				return (EACCES);
10756 			if (!checkonly) {
10757 				mutex_enter(&connp->conn_lock);
10758 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10759 				mutex_exit(&connp->conn_lock);
10760 			}
10761 			break;	/* goto sizeof (int) option return */
10762 		default:
10763 			/*
10764 			 * "soft" error (negative)
10765 			 * option not handled at this level
10766 			 * Note: Do not modify *outlenp
10767 			 */
10768 			return (-EINVAL);
10769 		}
10770 		break;
10771 	case IPPROTO_IP:
10772 		switch (name) {
10773 		case IP_NEXTHOP:
10774 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
10775 				return (EPERM);
10776 			/* FALLTHRU */
10777 		case IP_MULTICAST_IF:
10778 		case IP_DONTFAILOVER_IF: {
10779 			ipaddr_t addr = *i1;
10780 
10781 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10782 			    first_mp);
10783 			if (error != 0)
10784 				return (error);
10785 			break;	/* goto sizeof (int) option return */
10786 		}
10787 
10788 		case IP_MULTICAST_TTL:
10789 			/* Recorded in transport above IP */
10790 			*outvalp = *invalp;
10791 			*outlenp = sizeof (uchar_t);
10792 			return (0);
10793 		case IP_MULTICAST_LOOP:
10794 			if (!checkonly) {
10795 				mutex_enter(&connp->conn_lock);
10796 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10797 				mutex_exit(&connp->conn_lock);
10798 			}
10799 			*outvalp = *invalp;
10800 			*outlenp = sizeof (uchar_t);
10801 			return (0);
10802 		case IP_ADD_MEMBERSHIP:
10803 		case MCAST_JOIN_GROUP:
10804 		case IP_DROP_MEMBERSHIP:
10805 		case MCAST_LEAVE_GROUP: {
10806 			struct ip_mreq *mreqp;
10807 			struct group_req *greqp;
10808 			ire_t *ire;
10809 			boolean_t done = B_FALSE;
10810 			ipaddr_t group, ifaddr;
10811 			struct sockaddr_in *sin;
10812 			uint32_t *ifindexp;
10813 			boolean_t mcast_opt = B_TRUE;
10814 			mcast_record_t fmode;
10815 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10816 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10817 
10818 			switch (name) {
10819 			case IP_ADD_MEMBERSHIP:
10820 				mcast_opt = B_FALSE;
10821 				/* FALLTHRU */
10822 			case MCAST_JOIN_GROUP:
10823 				fmode = MODE_IS_EXCLUDE;
10824 				optfn = ip_opt_add_group;
10825 				break;
10826 
10827 			case IP_DROP_MEMBERSHIP:
10828 				mcast_opt = B_FALSE;
10829 				/* FALLTHRU */
10830 			case MCAST_LEAVE_GROUP:
10831 				fmode = MODE_IS_INCLUDE;
10832 				optfn = ip_opt_delete_group;
10833 				break;
10834 			}
10835 
10836 			if (mcast_opt) {
10837 				greqp = (struct group_req *)i1;
10838 				sin = (struct sockaddr_in *)&greqp->gr_group;
10839 				if (sin->sin_family != AF_INET) {
10840 					*outlenp = 0;
10841 					return (ENOPROTOOPT);
10842 				}
10843 				group = (ipaddr_t)sin->sin_addr.s_addr;
10844 				ifaddr = INADDR_ANY;
10845 				ifindexp = &greqp->gr_interface;
10846 			} else {
10847 				mreqp = (struct ip_mreq *)i1;
10848 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10849 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10850 				ifindexp = NULL;
10851 			}
10852 
10853 			/*
10854 			 * In the multirouting case, we need to replicate
10855 			 * the request on all interfaces that will take part
10856 			 * in replication.  We do so because multirouting is
10857 			 * reflective, thus we will probably receive multi-
10858 			 * casts on those interfaces.
10859 			 * The ip_multirt_apply_membership() succeeds if the
10860 			 * operation succeeds on at least one interface.
10861 			 */
10862 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10863 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10864 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10865 			if (ire != NULL) {
10866 				if (ire->ire_flags & RTF_MULTIRT) {
10867 					error = ip_multirt_apply_membership(
10868 					    optfn, ire, connp, checkonly, group,
10869 					    fmode, INADDR_ANY, first_mp);
10870 					done = B_TRUE;
10871 				}
10872 				ire_refrele(ire);
10873 			}
10874 			if (!done) {
10875 				error = optfn(connp, checkonly, group, ifaddr,
10876 				    ifindexp, fmode, INADDR_ANY, first_mp);
10877 			}
10878 			if (error) {
10879 				/*
10880 				 * EINPROGRESS is a soft error, needs retry
10881 				 * so don't make *outlenp zero.
10882 				 */
10883 				if (error != EINPROGRESS)
10884 					*outlenp = 0;
10885 				return (error);
10886 			}
10887 			/* OK return - copy input buffer into output buffer */
10888 			if (invalp != outvalp) {
10889 				/* don't trust bcopy for identical src/dst */
10890 				bcopy(invalp, outvalp, inlen);
10891 			}
10892 			*outlenp = inlen;
10893 			return (0);
10894 		}
10895 		case IP_BLOCK_SOURCE:
10896 		case IP_UNBLOCK_SOURCE:
10897 		case IP_ADD_SOURCE_MEMBERSHIP:
10898 		case IP_DROP_SOURCE_MEMBERSHIP:
10899 		case MCAST_BLOCK_SOURCE:
10900 		case MCAST_UNBLOCK_SOURCE:
10901 		case MCAST_JOIN_SOURCE_GROUP:
10902 		case MCAST_LEAVE_SOURCE_GROUP: {
10903 			struct ip_mreq_source *imreqp;
10904 			struct group_source_req *gsreqp;
10905 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10906 			uint32_t ifindex = 0;
10907 			mcast_record_t fmode;
10908 			struct sockaddr_in *sin;
10909 			ire_t *ire;
10910 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10911 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10912 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10913 
10914 			switch (name) {
10915 			case IP_BLOCK_SOURCE:
10916 				mcast_opt = B_FALSE;
10917 				/* FALLTHRU */
10918 			case MCAST_BLOCK_SOURCE:
10919 				fmode = MODE_IS_EXCLUDE;
10920 				optfn = ip_opt_add_group;
10921 				break;
10922 
10923 			case IP_UNBLOCK_SOURCE:
10924 				mcast_opt = B_FALSE;
10925 				/* FALLTHRU */
10926 			case MCAST_UNBLOCK_SOURCE:
10927 				fmode = MODE_IS_EXCLUDE;
10928 				optfn = ip_opt_delete_group;
10929 				break;
10930 
10931 			case IP_ADD_SOURCE_MEMBERSHIP:
10932 				mcast_opt = B_FALSE;
10933 				/* FALLTHRU */
10934 			case MCAST_JOIN_SOURCE_GROUP:
10935 				fmode = MODE_IS_INCLUDE;
10936 				optfn = ip_opt_add_group;
10937 				break;
10938 
10939 			case IP_DROP_SOURCE_MEMBERSHIP:
10940 				mcast_opt = B_FALSE;
10941 				/* FALLTHRU */
10942 			case MCAST_LEAVE_SOURCE_GROUP:
10943 				fmode = MODE_IS_INCLUDE;
10944 				optfn = ip_opt_delete_group;
10945 				break;
10946 			}
10947 
10948 			if (mcast_opt) {
10949 				gsreqp = (struct group_source_req *)i1;
10950 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10951 					*outlenp = 0;
10952 					return (ENOPROTOOPT);
10953 				}
10954 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10955 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10956 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10957 				src = (ipaddr_t)sin->sin_addr.s_addr;
10958 				ifindex = gsreqp->gsr_interface;
10959 			} else {
10960 				imreqp = (struct ip_mreq_source *)i1;
10961 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10962 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10963 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10964 			}
10965 
10966 			/*
10967 			 * In the multirouting case, we need to replicate
10968 			 * the request as noted in the mcast cases above.
10969 			 */
10970 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10971 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10972 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10973 			if (ire != NULL) {
10974 				if (ire->ire_flags & RTF_MULTIRT) {
10975 					error = ip_multirt_apply_membership(
10976 					    optfn, ire, connp, checkonly, grp,
10977 					    fmode, src, first_mp);
10978 					done = B_TRUE;
10979 				}
10980 				ire_refrele(ire);
10981 			}
10982 			if (!done) {
10983 				error = optfn(connp, checkonly, grp, ifaddr,
10984 				    &ifindex, fmode, src, first_mp);
10985 			}
10986 			if (error != 0) {
10987 				/*
10988 				 * EINPROGRESS is a soft error, needs retry
10989 				 * so don't make *outlenp zero.
10990 				 */
10991 				if (error != EINPROGRESS)
10992 					*outlenp = 0;
10993 				return (error);
10994 			}
10995 			/* OK return - copy input buffer into output buffer */
10996 			if (invalp != outvalp) {
10997 				bcopy(invalp, outvalp, inlen);
10998 			}
10999 			*outlenp = inlen;
11000 			return (0);
11001 		}
11002 		case IP_SEC_OPT:
11003 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11004 			if (error != 0) {
11005 				*outlenp = 0;
11006 				return (error);
11007 			}
11008 			break;
11009 		case IP_HDRINCL:
11010 		case IP_OPTIONS:
11011 		case T_IP_OPTIONS:
11012 		case IP_TOS:
11013 		case T_IP_TOS:
11014 		case IP_TTL:
11015 		case IP_RECVDSTADDR:
11016 		case IP_RECVOPTS:
11017 			/* OK return - copy input buffer into output buffer */
11018 			if (invalp != outvalp) {
11019 				/* don't trust bcopy for identical src/dst */
11020 				bcopy(invalp, outvalp, inlen);
11021 			}
11022 			*outlenp = inlen;
11023 			return (0);
11024 		case IP_RECVIF:
11025 			/* Retrieve the inbound interface index */
11026 			if (!checkonly) {
11027 				mutex_enter(&connp->conn_lock);
11028 				connp->conn_recvif = *i1 ? 1 : 0;
11029 				mutex_exit(&connp->conn_lock);
11030 			}
11031 			break;	/* goto sizeof (int) option return */
11032 		case IP_RECVPKTINFO:
11033 			if (!checkonly) {
11034 				mutex_enter(&connp->conn_lock);
11035 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11036 				mutex_exit(&connp->conn_lock);
11037 			}
11038 			break;	/* goto sizeof (int) option return */
11039 		case IP_RECVSLLA:
11040 			/* Retrieve the source link layer address */
11041 			if (!checkonly) {
11042 				mutex_enter(&connp->conn_lock);
11043 				connp->conn_recvslla = *i1 ? 1 : 0;
11044 				mutex_exit(&connp->conn_lock);
11045 			}
11046 			break;	/* goto sizeof (int) option return */
11047 		case MRT_INIT:
11048 		case MRT_DONE:
11049 		case MRT_ADD_VIF:
11050 		case MRT_DEL_VIF:
11051 		case MRT_ADD_MFC:
11052 		case MRT_DEL_MFC:
11053 		case MRT_ASSERT:
11054 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
11055 				*outlenp = 0;
11056 				return (error);
11057 			}
11058 			error = ip_mrouter_set((int)name, q, checkonly,
11059 			    (uchar_t *)invalp, inlen, first_mp);
11060 			if (error) {
11061 				*outlenp = 0;
11062 				return (error);
11063 			}
11064 			/* OK return - copy input buffer into output buffer */
11065 			if (invalp != outvalp) {
11066 				/* don't trust bcopy for identical src/dst */
11067 				bcopy(invalp, outvalp, inlen);
11068 			}
11069 			*outlenp = inlen;
11070 			return (0);
11071 		case IP_BOUND_IF:
11072 		case IP_DHCPINIT_IF:
11073 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11074 			    level, name, first_mp);
11075 			if (error != 0)
11076 				return (error);
11077 			break; 		/* goto sizeof (int) option return */
11078 
11079 		case IP_UNSPEC_SRC:
11080 			/* Allow sending with a zero source address */
11081 			if (!checkonly) {
11082 				mutex_enter(&connp->conn_lock);
11083 				connp->conn_unspec_src = *i1 ? 1 : 0;
11084 				mutex_exit(&connp->conn_lock);
11085 			}
11086 			break;	/* goto sizeof (int) option return */
11087 		default:
11088 			/*
11089 			 * "soft" error (negative)
11090 			 * option not handled at this level
11091 			 * Note: Do not modify *outlenp
11092 			 */
11093 			return (-EINVAL);
11094 		}
11095 		break;
11096 	case IPPROTO_IPV6:
11097 		switch (name) {
11098 		case IPV6_BOUND_IF:
11099 		case IPV6_BOUND_PIF:
11100 		case IPV6_DONTFAILOVER_IF:
11101 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11102 			    level, name, first_mp);
11103 			if (error != 0)
11104 				return (error);
11105 			break; 		/* goto sizeof (int) option return */
11106 
11107 		case IPV6_MULTICAST_IF:
11108 			/*
11109 			 * The only possible errors are EINPROGRESS and
11110 			 * EINVAL. EINPROGRESS will be restarted and is not
11111 			 * a hard error. We call this option on both V4 and V6
11112 			 * If both return EINVAL, then this call returns
11113 			 * EINVAL. If at least one of them succeeds we
11114 			 * return success.
11115 			 */
11116 			found = B_FALSE;
11117 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11118 			    level, name, first_mp);
11119 			if (error == EINPROGRESS)
11120 				return (error);
11121 			if (error == 0)
11122 				found = B_TRUE;
11123 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11124 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11125 			if (error == 0)
11126 				found = B_TRUE;
11127 			if (!found)
11128 				return (error);
11129 			break; 		/* goto sizeof (int) option return */
11130 
11131 		case IPV6_MULTICAST_HOPS:
11132 			/* Recorded in transport above IP */
11133 			break;	/* goto sizeof (int) option return */
11134 		case IPV6_MULTICAST_LOOP:
11135 			if (!checkonly) {
11136 				mutex_enter(&connp->conn_lock);
11137 				connp->conn_multicast_loop = *i1;
11138 				mutex_exit(&connp->conn_lock);
11139 			}
11140 			break;	/* goto sizeof (int) option return */
11141 		case IPV6_JOIN_GROUP:
11142 		case MCAST_JOIN_GROUP:
11143 		case IPV6_LEAVE_GROUP:
11144 		case MCAST_LEAVE_GROUP: {
11145 			struct ipv6_mreq *ip_mreqp;
11146 			struct group_req *greqp;
11147 			ire_t *ire;
11148 			boolean_t done = B_FALSE;
11149 			in6_addr_t groupv6;
11150 			uint32_t ifindex;
11151 			boolean_t mcast_opt = B_TRUE;
11152 			mcast_record_t fmode;
11153 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11154 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11155 
11156 			switch (name) {
11157 			case IPV6_JOIN_GROUP:
11158 				mcast_opt = B_FALSE;
11159 				/* FALLTHRU */
11160 			case MCAST_JOIN_GROUP:
11161 				fmode = MODE_IS_EXCLUDE;
11162 				optfn = ip_opt_add_group_v6;
11163 				break;
11164 
11165 			case IPV6_LEAVE_GROUP:
11166 				mcast_opt = B_FALSE;
11167 				/* FALLTHRU */
11168 			case MCAST_LEAVE_GROUP:
11169 				fmode = MODE_IS_INCLUDE;
11170 				optfn = ip_opt_delete_group_v6;
11171 				break;
11172 			}
11173 
11174 			if (mcast_opt) {
11175 				struct sockaddr_in *sin;
11176 				struct sockaddr_in6 *sin6;
11177 				greqp = (struct group_req *)i1;
11178 				if (greqp->gr_group.ss_family == AF_INET) {
11179 					sin = (struct sockaddr_in *)
11180 					    &(greqp->gr_group);
11181 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11182 					    &groupv6);
11183 				} else {
11184 					sin6 = (struct sockaddr_in6 *)
11185 					    &(greqp->gr_group);
11186 					groupv6 = sin6->sin6_addr;
11187 				}
11188 				ifindex = greqp->gr_interface;
11189 			} else {
11190 				ip_mreqp = (struct ipv6_mreq *)i1;
11191 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11192 				ifindex = ip_mreqp->ipv6mr_interface;
11193 			}
11194 			/*
11195 			 * In the multirouting case, we need to replicate
11196 			 * the request on all interfaces that will take part
11197 			 * in replication.  We do so because multirouting is
11198 			 * reflective, thus we will probably receive multi-
11199 			 * casts on those interfaces.
11200 			 * The ip_multirt_apply_membership_v6() succeeds if
11201 			 * the operation succeeds on at least one interface.
11202 			 */
11203 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11204 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11205 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11206 			if (ire != NULL) {
11207 				if (ire->ire_flags & RTF_MULTIRT) {
11208 					error = ip_multirt_apply_membership_v6(
11209 					    optfn, ire, connp, checkonly,
11210 					    &groupv6, fmode, &ipv6_all_zeros,
11211 					    first_mp);
11212 					done = B_TRUE;
11213 				}
11214 				ire_refrele(ire);
11215 			}
11216 			if (!done) {
11217 				error = optfn(connp, checkonly, &groupv6,
11218 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11219 			}
11220 			if (error) {
11221 				/*
11222 				 * EINPROGRESS is a soft error, needs retry
11223 				 * so don't make *outlenp zero.
11224 				 */
11225 				if (error != EINPROGRESS)
11226 					*outlenp = 0;
11227 				return (error);
11228 			}
11229 			/* OK return - copy input buffer into output buffer */
11230 			if (invalp != outvalp) {
11231 				/* don't trust bcopy for identical src/dst */
11232 				bcopy(invalp, outvalp, inlen);
11233 			}
11234 			*outlenp = inlen;
11235 			return (0);
11236 		}
11237 		case MCAST_BLOCK_SOURCE:
11238 		case MCAST_UNBLOCK_SOURCE:
11239 		case MCAST_JOIN_SOURCE_GROUP:
11240 		case MCAST_LEAVE_SOURCE_GROUP: {
11241 			struct group_source_req *gsreqp;
11242 			in6_addr_t v6grp, v6src;
11243 			uint32_t ifindex;
11244 			mcast_record_t fmode;
11245 			ire_t *ire;
11246 			boolean_t done = B_FALSE;
11247 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11248 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11249 
11250 			switch (name) {
11251 			case MCAST_BLOCK_SOURCE:
11252 				fmode = MODE_IS_EXCLUDE;
11253 				optfn = ip_opt_add_group_v6;
11254 				break;
11255 			case MCAST_UNBLOCK_SOURCE:
11256 				fmode = MODE_IS_EXCLUDE;
11257 				optfn = ip_opt_delete_group_v6;
11258 				break;
11259 			case MCAST_JOIN_SOURCE_GROUP:
11260 				fmode = MODE_IS_INCLUDE;
11261 				optfn = ip_opt_add_group_v6;
11262 				break;
11263 			case MCAST_LEAVE_SOURCE_GROUP:
11264 				fmode = MODE_IS_INCLUDE;
11265 				optfn = ip_opt_delete_group_v6;
11266 				break;
11267 			}
11268 
11269 			gsreqp = (struct group_source_req *)i1;
11270 			ifindex = gsreqp->gsr_interface;
11271 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11272 				struct sockaddr_in *s;
11273 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11274 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11275 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11276 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11277 			} else {
11278 				struct sockaddr_in6 *s6;
11279 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11280 				v6grp = s6->sin6_addr;
11281 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11282 				v6src = s6->sin6_addr;
11283 			}
11284 
11285 			/*
11286 			 * In the multirouting case, we need to replicate
11287 			 * the request as noted in the mcast cases above.
11288 			 */
11289 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11290 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11291 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11292 			if (ire != NULL) {
11293 				if (ire->ire_flags & RTF_MULTIRT) {
11294 					error = ip_multirt_apply_membership_v6(
11295 					    optfn, ire, connp, checkonly,
11296 					    &v6grp, fmode, &v6src, first_mp);
11297 					done = B_TRUE;
11298 				}
11299 				ire_refrele(ire);
11300 			}
11301 			if (!done) {
11302 				error = optfn(connp, checkonly, &v6grp,
11303 				    ifindex, fmode, &v6src, first_mp);
11304 			}
11305 			if (error != 0) {
11306 				/*
11307 				 * EINPROGRESS is a soft error, needs retry
11308 				 * so don't make *outlenp zero.
11309 				 */
11310 				if (error != EINPROGRESS)
11311 					*outlenp = 0;
11312 				return (error);
11313 			}
11314 			/* OK return - copy input buffer into output buffer */
11315 			if (invalp != outvalp) {
11316 				bcopy(invalp, outvalp, inlen);
11317 			}
11318 			*outlenp = inlen;
11319 			return (0);
11320 		}
11321 		case IPV6_UNICAST_HOPS:
11322 			/* Recorded in transport above IP */
11323 			break;	/* goto sizeof (int) option return */
11324 		case IPV6_UNSPEC_SRC:
11325 			/* Allow sending with a zero source address */
11326 			if (!checkonly) {
11327 				mutex_enter(&connp->conn_lock);
11328 				connp->conn_unspec_src = *i1 ? 1 : 0;
11329 				mutex_exit(&connp->conn_lock);
11330 			}
11331 			break;	/* goto sizeof (int) option return */
11332 		case IPV6_RECVPKTINFO:
11333 			if (!checkonly) {
11334 				mutex_enter(&connp->conn_lock);
11335 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11336 				mutex_exit(&connp->conn_lock);
11337 			}
11338 			break;	/* goto sizeof (int) option return */
11339 		case IPV6_RECVTCLASS:
11340 			if (!checkonly) {
11341 				if (*i1 < 0 || *i1 > 1) {
11342 					return (EINVAL);
11343 				}
11344 				mutex_enter(&connp->conn_lock);
11345 				connp->conn_ipv6_recvtclass = *i1;
11346 				mutex_exit(&connp->conn_lock);
11347 			}
11348 			break;
11349 		case IPV6_RECVPATHMTU:
11350 			if (!checkonly) {
11351 				if (*i1 < 0 || *i1 > 1) {
11352 					return (EINVAL);
11353 				}
11354 				mutex_enter(&connp->conn_lock);
11355 				connp->conn_ipv6_recvpathmtu = *i1;
11356 				mutex_exit(&connp->conn_lock);
11357 			}
11358 			break;
11359 		case IPV6_RECVHOPLIMIT:
11360 			if (!checkonly) {
11361 				mutex_enter(&connp->conn_lock);
11362 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11363 				mutex_exit(&connp->conn_lock);
11364 			}
11365 			break;	/* goto sizeof (int) option return */
11366 		case IPV6_RECVHOPOPTS:
11367 			if (!checkonly) {
11368 				mutex_enter(&connp->conn_lock);
11369 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11370 				mutex_exit(&connp->conn_lock);
11371 			}
11372 			break;	/* goto sizeof (int) option return */
11373 		case IPV6_RECVDSTOPTS:
11374 			if (!checkonly) {
11375 				mutex_enter(&connp->conn_lock);
11376 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11377 				mutex_exit(&connp->conn_lock);
11378 			}
11379 			break;	/* goto sizeof (int) option return */
11380 		case IPV6_RECVRTHDR:
11381 			if (!checkonly) {
11382 				mutex_enter(&connp->conn_lock);
11383 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11384 				mutex_exit(&connp->conn_lock);
11385 			}
11386 			break;	/* goto sizeof (int) option return */
11387 		case IPV6_RECVRTHDRDSTOPTS:
11388 			if (!checkonly) {
11389 				mutex_enter(&connp->conn_lock);
11390 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11391 				mutex_exit(&connp->conn_lock);
11392 			}
11393 			break;	/* goto sizeof (int) option return */
11394 		case IPV6_PKTINFO:
11395 			if (inlen == 0)
11396 				return (-EINVAL);	/* clearing option */
11397 			error = ip6_set_pktinfo(cr, connp,
11398 			    (struct in6_pktinfo *)invalp, first_mp);
11399 			if (error != 0)
11400 				*outlenp = 0;
11401 			else
11402 				*outlenp = inlen;
11403 			return (error);
11404 		case IPV6_NEXTHOP: {
11405 			struct sockaddr_in6 *sin6;
11406 
11407 			/* Verify that the nexthop is reachable */
11408 			if (inlen == 0)
11409 				return (-EINVAL);	/* clearing option */
11410 
11411 			sin6 = (struct sockaddr_in6 *)invalp;
11412 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11413 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11414 			    NULL, MATCH_IRE_DEFAULT, ipst);
11415 
11416 			if (ire == NULL) {
11417 				*outlenp = 0;
11418 				return (EHOSTUNREACH);
11419 			}
11420 			ire_refrele(ire);
11421 			return (-EINVAL);
11422 		}
11423 		case IPV6_SEC_OPT:
11424 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11425 			if (error != 0) {
11426 				*outlenp = 0;
11427 				return (error);
11428 			}
11429 			break;
11430 		case IPV6_SRC_PREFERENCES: {
11431 			/*
11432 			 * This is implemented strictly in the ip module
11433 			 * (here and in tcp_opt_*() to accomodate tcp
11434 			 * sockets).  Modules above ip pass this option
11435 			 * down here since ip is the only one that needs to
11436 			 * be aware of source address preferences.
11437 			 *
11438 			 * This socket option only affects connected
11439 			 * sockets that haven't already bound to a specific
11440 			 * IPv6 address.  In other words, sockets that
11441 			 * don't call bind() with an address other than the
11442 			 * unspecified address and that call connect().
11443 			 * ip_bind_connected_v6() passes these preferences
11444 			 * to the ipif_select_source_v6() function.
11445 			 */
11446 			if (inlen != sizeof (uint32_t))
11447 				return (EINVAL);
11448 			error = ip6_set_src_preferences(connp,
11449 			    *(uint32_t *)invalp);
11450 			if (error != 0) {
11451 				*outlenp = 0;
11452 				return (error);
11453 			} else {
11454 				*outlenp = sizeof (uint32_t);
11455 			}
11456 			break;
11457 		}
11458 		case IPV6_V6ONLY:
11459 			if (*i1 < 0 || *i1 > 1) {
11460 				return (EINVAL);
11461 			}
11462 			mutex_enter(&connp->conn_lock);
11463 			connp->conn_ipv6_v6only = *i1;
11464 			mutex_exit(&connp->conn_lock);
11465 			break;
11466 		default:
11467 			return (-EINVAL);
11468 		}
11469 		break;
11470 	default:
11471 		/*
11472 		 * "soft" error (negative)
11473 		 * option not handled at this level
11474 		 * Note: Do not modify *outlenp
11475 		 */
11476 		return (-EINVAL);
11477 	}
11478 	/*
11479 	 * Common case of return from an option that is sizeof (int)
11480 	 */
11481 	*(int *)outvalp = *i1;
11482 	*outlenp = sizeof (int);
11483 	return (0);
11484 }
11485 
11486 /*
11487  * This routine gets default values of certain options whose default
11488  * values are maintained by protocol specific code
11489  */
11490 /* ARGSUSED */
11491 int
11492 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11493 {
11494 	int *i1 = (int *)ptr;
11495 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11496 
11497 	switch (level) {
11498 	case IPPROTO_IP:
11499 		switch (name) {
11500 		case IP_MULTICAST_TTL:
11501 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11502 			return (sizeof (uchar_t));
11503 		case IP_MULTICAST_LOOP:
11504 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11505 			return (sizeof (uchar_t));
11506 		default:
11507 			return (-1);
11508 		}
11509 	case IPPROTO_IPV6:
11510 		switch (name) {
11511 		case IPV6_UNICAST_HOPS:
11512 			*i1 = ipst->ips_ipv6_def_hops;
11513 			return (sizeof (int));
11514 		case IPV6_MULTICAST_HOPS:
11515 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11516 			return (sizeof (int));
11517 		case IPV6_MULTICAST_LOOP:
11518 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11519 			return (sizeof (int));
11520 		case IPV6_V6ONLY:
11521 			*i1 = 1;
11522 			return (sizeof (int));
11523 		default:
11524 			return (-1);
11525 		}
11526 	default:
11527 		return (-1);
11528 	}
11529 	/* NOTREACHED */
11530 }
11531 
11532 /*
11533  * Given a destination address and a pointer to where to put the information
11534  * this routine fills in the mtuinfo.
11535  */
11536 int
11537 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11538     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11539 {
11540 	ire_t *ire;
11541 	ip_stack_t	*ipst = ns->netstack_ip;
11542 
11543 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11544 		return (-1);
11545 
11546 	bzero(mtuinfo, sizeof (*mtuinfo));
11547 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11548 	mtuinfo->ip6m_addr.sin6_port = port;
11549 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11550 
11551 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11552 	if (ire != NULL) {
11553 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11554 		ire_refrele(ire);
11555 	} else {
11556 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11557 	}
11558 	return (sizeof (struct ip6_mtuinfo));
11559 }
11560 
11561 /*
11562  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11563  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11564  * isn't.  This doesn't matter as the error checking is done properly for the
11565  * other MRT options coming in through ip_opt_set.
11566  */
11567 int
11568 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11569 {
11570 	conn_t		*connp = Q_TO_CONN(q);
11571 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11572 
11573 	switch (level) {
11574 	case IPPROTO_IP:
11575 		switch (name) {
11576 		case MRT_VERSION:
11577 		case MRT_ASSERT:
11578 			(void) ip_mrouter_get(name, q, ptr);
11579 			return (sizeof (int));
11580 		case IP_SEC_OPT:
11581 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11582 		case IP_NEXTHOP:
11583 			if (connp->conn_nexthop_set) {
11584 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11585 				return (sizeof (ipaddr_t));
11586 			} else
11587 				return (0);
11588 		case IP_RECVPKTINFO:
11589 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11590 			return (sizeof (int));
11591 		default:
11592 			break;
11593 		}
11594 		break;
11595 	case IPPROTO_IPV6:
11596 		switch (name) {
11597 		case IPV6_SEC_OPT:
11598 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11599 		case IPV6_SRC_PREFERENCES: {
11600 			return (ip6_get_src_preferences(connp,
11601 			    (uint32_t *)ptr));
11602 		}
11603 		case IPV6_V6ONLY:
11604 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11605 			return (sizeof (int));
11606 		case IPV6_PATHMTU:
11607 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11608 			    (struct ip6_mtuinfo *)ptr, connp->conn_netstack));
11609 		default:
11610 			break;
11611 		}
11612 		break;
11613 	default:
11614 		break;
11615 	}
11616 	return (-1);
11617 }
11618 
11619 /* Named Dispatch routine to get a current value out of our parameter table. */
11620 /* ARGSUSED */
11621 static int
11622 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11623 {
11624 	ipparam_t *ippa = (ipparam_t *)cp;
11625 
11626 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11627 	return (0);
11628 }
11629 
11630 /* ARGSUSED */
11631 static int
11632 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11633 {
11634 
11635 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11636 	return (0);
11637 }
11638 
11639 /*
11640  * Set ip{,6}_forwarding values.  This means walking through all of the
11641  * ill's and toggling their forwarding values.
11642  */
11643 /* ARGSUSED */
11644 static int
11645 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11646 {
11647 	long new_value;
11648 	int *forwarding_value = (int *)cp;
11649 	ill_t *ill;
11650 	boolean_t isv6;
11651 	ill_walk_context_t ctx;
11652 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11653 
11654 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11655 
11656 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11657 	    new_value < 0 || new_value > 1) {
11658 		return (EINVAL);
11659 	}
11660 
11661 	*forwarding_value = new_value;
11662 
11663 	/*
11664 	 * Regardless of the current value of ip_forwarding, set all per-ill
11665 	 * values of ip_forwarding to the value being set.
11666 	 *
11667 	 * Bring all the ill's up to date with the new global value.
11668 	 */
11669 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11670 
11671 	if (isv6)
11672 		ill = ILL_START_WALK_V6(&ctx, ipst);
11673 	else
11674 		ill = ILL_START_WALK_V4(&ctx, ipst);
11675 
11676 	for (; ill != NULL; ill = ill_next(&ctx, ill))
11677 		(void) ill_forward_set(ill, new_value != 0);
11678 
11679 	rw_exit(&ipst->ips_ill_g_lock);
11680 	return (0);
11681 }
11682 
11683 /*
11684  * Walk through the param array specified registering each element with the
11685  * Named Dispatch handler. This is called only during init. So it is ok
11686  * not to acquire any locks
11687  */
11688 static boolean_t
11689 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11690     ipndp_t *ipnd, size_t ipnd_cnt)
11691 {
11692 	for (; ippa_cnt-- > 0; ippa++) {
11693 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11694 			if (!nd_load(ndp, ippa->ip_param_name,
11695 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11696 				nd_free(ndp);
11697 				return (B_FALSE);
11698 			}
11699 		}
11700 	}
11701 
11702 	for (; ipnd_cnt-- > 0; ipnd++) {
11703 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11704 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11705 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11706 			    ipnd->ip_ndp_data)) {
11707 				nd_free(ndp);
11708 				return (B_FALSE);
11709 			}
11710 		}
11711 	}
11712 
11713 	return (B_TRUE);
11714 }
11715 
11716 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11717 /* ARGSUSED */
11718 static int
11719 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11720 {
11721 	long		new_value;
11722 	ipparam_t	*ippa = (ipparam_t *)cp;
11723 
11724 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11725 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11726 		return (EINVAL);
11727 	}
11728 	ippa->ip_param_value = new_value;
11729 	return (0);
11730 }
11731 
11732 /*
11733  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11734  * When an ipf is passed here for the first time, if
11735  * we already have in-order fragments on the queue, we convert from the fast-
11736  * path reassembly scheme to the hard-case scheme.  From then on, additional
11737  * fragments are reassembled here.  We keep track of the start and end offsets
11738  * of each piece, and the number of holes in the chain.  When the hole count
11739  * goes to zero, we are done!
11740  *
11741  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11742  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11743  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11744  * after the call to ip_reassemble().
11745  */
11746 int
11747 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11748     size_t msg_len)
11749 {
11750 	uint_t	end;
11751 	mblk_t	*next_mp;
11752 	mblk_t	*mp1;
11753 	uint_t	offset;
11754 	boolean_t incr_dups = B_TRUE;
11755 	boolean_t offset_zero_seen = B_FALSE;
11756 	boolean_t pkt_boundary_checked = B_FALSE;
11757 
11758 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11759 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11760 
11761 	/* Add in byte count */
11762 	ipf->ipf_count += msg_len;
11763 	if (ipf->ipf_end) {
11764 		/*
11765 		 * We were part way through in-order reassembly, but now there
11766 		 * is a hole.  We walk through messages already queued, and
11767 		 * mark them for hard case reassembly.  We know that up till
11768 		 * now they were in order starting from offset zero.
11769 		 */
11770 		offset = 0;
11771 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11772 			IP_REASS_SET_START(mp1, offset);
11773 			if (offset == 0) {
11774 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11775 				offset = -ipf->ipf_nf_hdr_len;
11776 			}
11777 			offset += mp1->b_wptr - mp1->b_rptr;
11778 			IP_REASS_SET_END(mp1, offset);
11779 		}
11780 		/* One hole at the end. */
11781 		ipf->ipf_hole_cnt = 1;
11782 		/* Brand it as a hard case, forever. */
11783 		ipf->ipf_end = 0;
11784 	}
11785 	/* Walk through all the new pieces. */
11786 	do {
11787 		end = start + (mp->b_wptr - mp->b_rptr);
11788 		/*
11789 		 * If start is 0, decrease 'end' only for the first mblk of
11790 		 * the fragment. Otherwise 'end' can get wrong value in the
11791 		 * second pass of the loop if first mblk is exactly the
11792 		 * size of ipf_nf_hdr_len.
11793 		 */
11794 		if (start == 0 && !offset_zero_seen) {
11795 			/* First segment */
11796 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11797 			end -= ipf->ipf_nf_hdr_len;
11798 			offset_zero_seen = B_TRUE;
11799 		}
11800 		next_mp = mp->b_cont;
11801 		/*
11802 		 * We are checking to see if there is any interesing data
11803 		 * to process.  If there isn't and the mblk isn't the
11804 		 * one which carries the unfragmentable header then we
11805 		 * drop it.  It's possible to have just the unfragmentable
11806 		 * header come through without any data.  That needs to be
11807 		 * saved.
11808 		 *
11809 		 * If the assert at the top of this function holds then the
11810 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11811 		 * is infrequently traveled enough that the test is left in
11812 		 * to protect against future code changes which break that
11813 		 * invariant.
11814 		 */
11815 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11816 			/* Empty.  Blast it. */
11817 			IP_REASS_SET_START(mp, 0);
11818 			IP_REASS_SET_END(mp, 0);
11819 			/*
11820 			 * If the ipf points to the mblk we are about to free,
11821 			 * update ipf to point to the next mblk (or NULL
11822 			 * if none).
11823 			 */
11824 			if (ipf->ipf_mp->b_cont == mp)
11825 				ipf->ipf_mp->b_cont = next_mp;
11826 			freeb(mp);
11827 			continue;
11828 		}
11829 		mp->b_cont = NULL;
11830 		IP_REASS_SET_START(mp, start);
11831 		IP_REASS_SET_END(mp, end);
11832 		if (!ipf->ipf_tail_mp) {
11833 			ipf->ipf_tail_mp = mp;
11834 			ipf->ipf_mp->b_cont = mp;
11835 			if (start == 0 || !more) {
11836 				ipf->ipf_hole_cnt = 1;
11837 				/*
11838 				 * if the first fragment comes in more than one
11839 				 * mblk, this loop will be executed for each
11840 				 * mblk. Need to adjust hole count so exiting
11841 				 * this routine will leave hole count at 1.
11842 				 */
11843 				if (next_mp)
11844 					ipf->ipf_hole_cnt++;
11845 			} else
11846 				ipf->ipf_hole_cnt = 2;
11847 			continue;
11848 		} else if (ipf->ipf_last_frag_seen && !more &&
11849 		    !pkt_boundary_checked) {
11850 			/*
11851 			 * We check datagram boundary only if this fragment
11852 			 * claims to be the last fragment and we have seen a
11853 			 * last fragment in the past too. We do this only
11854 			 * once for a given fragment.
11855 			 *
11856 			 * start cannot be 0 here as fragments with start=0
11857 			 * and MF=0 gets handled as a complete packet. These
11858 			 * fragments should not reach here.
11859 			 */
11860 
11861 			if (start + msgdsize(mp) !=
11862 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11863 				/*
11864 				 * We have two fragments both of which claim
11865 				 * to be the last fragment but gives conflicting
11866 				 * information about the whole datagram size.
11867 				 * Something fishy is going on. Drop the
11868 				 * fragment and free up the reassembly list.
11869 				 */
11870 				return (IP_REASS_FAILED);
11871 			}
11872 
11873 			/*
11874 			 * We shouldn't come to this code block again for this
11875 			 * particular fragment.
11876 			 */
11877 			pkt_boundary_checked = B_TRUE;
11878 		}
11879 
11880 		/* New stuff at or beyond tail? */
11881 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11882 		if (start >= offset) {
11883 			if (ipf->ipf_last_frag_seen) {
11884 				/* current fragment is beyond last fragment */
11885 				return (IP_REASS_FAILED);
11886 			}
11887 			/* Link it on end. */
11888 			ipf->ipf_tail_mp->b_cont = mp;
11889 			ipf->ipf_tail_mp = mp;
11890 			if (more) {
11891 				if (start != offset)
11892 					ipf->ipf_hole_cnt++;
11893 			} else if (start == offset && next_mp == NULL)
11894 					ipf->ipf_hole_cnt--;
11895 			continue;
11896 		}
11897 		mp1 = ipf->ipf_mp->b_cont;
11898 		offset = IP_REASS_START(mp1);
11899 		/* New stuff at the front? */
11900 		if (start < offset) {
11901 			if (start == 0) {
11902 				if (end >= offset) {
11903 					/* Nailed the hole at the begining. */
11904 					ipf->ipf_hole_cnt--;
11905 				}
11906 			} else if (end < offset) {
11907 				/*
11908 				 * A hole, stuff, and a hole where there used
11909 				 * to be just a hole.
11910 				 */
11911 				ipf->ipf_hole_cnt++;
11912 			}
11913 			mp->b_cont = mp1;
11914 			/* Check for overlap. */
11915 			while (end > offset) {
11916 				if (end < IP_REASS_END(mp1)) {
11917 					mp->b_wptr -= end - offset;
11918 					IP_REASS_SET_END(mp, offset);
11919 					BUMP_MIB(ill->ill_ip_mib,
11920 					    ipIfStatsReasmPartDups);
11921 					break;
11922 				}
11923 				/* Did we cover another hole? */
11924 				if ((mp1->b_cont &&
11925 				    IP_REASS_END(mp1) !=
11926 				    IP_REASS_START(mp1->b_cont) &&
11927 				    end >= IP_REASS_START(mp1->b_cont)) ||
11928 				    (!ipf->ipf_last_frag_seen && !more)) {
11929 					ipf->ipf_hole_cnt--;
11930 				}
11931 				/* Clip out mp1. */
11932 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11933 					/*
11934 					 * After clipping out mp1, this guy
11935 					 * is now hanging off the end.
11936 					 */
11937 					ipf->ipf_tail_mp = mp;
11938 				}
11939 				IP_REASS_SET_START(mp1, 0);
11940 				IP_REASS_SET_END(mp1, 0);
11941 				/* Subtract byte count */
11942 				ipf->ipf_count -= mp1->b_datap->db_lim -
11943 				    mp1->b_datap->db_base;
11944 				freeb(mp1);
11945 				BUMP_MIB(ill->ill_ip_mib,
11946 				    ipIfStatsReasmPartDups);
11947 				mp1 = mp->b_cont;
11948 				if (!mp1)
11949 					break;
11950 				offset = IP_REASS_START(mp1);
11951 			}
11952 			ipf->ipf_mp->b_cont = mp;
11953 			continue;
11954 		}
11955 		/*
11956 		 * The new piece starts somewhere between the start of the head
11957 		 * and before the end of the tail.
11958 		 */
11959 		for (; mp1; mp1 = mp1->b_cont) {
11960 			offset = IP_REASS_END(mp1);
11961 			if (start < offset) {
11962 				if (end <= offset) {
11963 					/* Nothing new. */
11964 					IP_REASS_SET_START(mp, 0);
11965 					IP_REASS_SET_END(mp, 0);
11966 					/* Subtract byte count */
11967 					ipf->ipf_count -= mp->b_datap->db_lim -
11968 					    mp->b_datap->db_base;
11969 					if (incr_dups) {
11970 						ipf->ipf_num_dups++;
11971 						incr_dups = B_FALSE;
11972 					}
11973 					freeb(mp);
11974 					BUMP_MIB(ill->ill_ip_mib,
11975 					    ipIfStatsReasmDuplicates);
11976 					break;
11977 				}
11978 				/*
11979 				 * Trim redundant stuff off beginning of new
11980 				 * piece.
11981 				 */
11982 				IP_REASS_SET_START(mp, offset);
11983 				mp->b_rptr += offset - start;
11984 				BUMP_MIB(ill->ill_ip_mib,
11985 				    ipIfStatsReasmPartDups);
11986 				start = offset;
11987 				if (!mp1->b_cont) {
11988 					/*
11989 					 * After trimming, this guy is now
11990 					 * hanging off the end.
11991 					 */
11992 					mp1->b_cont = mp;
11993 					ipf->ipf_tail_mp = mp;
11994 					if (!more) {
11995 						ipf->ipf_hole_cnt--;
11996 					}
11997 					break;
11998 				}
11999 			}
12000 			if (start >= IP_REASS_START(mp1->b_cont))
12001 				continue;
12002 			/* Fill a hole */
12003 			if (start > offset)
12004 				ipf->ipf_hole_cnt++;
12005 			mp->b_cont = mp1->b_cont;
12006 			mp1->b_cont = mp;
12007 			mp1 = mp->b_cont;
12008 			offset = IP_REASS_START(mp1);
12009 			if (end >= offset) {
12010 				ipf->ipf_hole_cnt--;
12011 				/* Check for overlap. */
12012 				while (end > offset) {
12013 					if (end < IP_REASS_END(mp1)) {
12014 						mp->b_wptr -= end - offset;
12015 						IP_REASS_SET_END(mp, offset);
12016 						/*
12017 						 * TODO we might bump
12018 						 * this up twice if there is
12019 						 * overlap at both ends.
12020 						 */
12021 						BUMP_MIB(ill->ill_ip_mib,
12022 						    ipIfStatsReasmPartDups);
12023 						break;
12024 					}
12025 					/* Did we cover another hole? */
12026 					if ((mp1->b_cont &&
12027 					    IP_REASS_END(mp1)
12028 					    != IP_REASS_START(mp1->b_cont) &&
12029 					    end >=
12030 					    IP_REASS_START(mp1->b_cont)) ||
12031 					    (!ipf->ipf_last_frag_seen &&
12032 					    !more)) {
12033 						ipf->ipf_hole_cnt--;
12034 					}
12035 					/* Clip out mp1. */
12036 					if ((mp->b_cont = mp1->b_cont) ==
12037 					    NULL) {
12038 						/*
12039 						 * After clipping out mp1,
12040 						 * this guy is now hanging
12041 						 * off the end.
12042 						 */
12043 						ipf->ipf_tail_mp = mp;
12044 					}
12045 					IP_REASS_SET_START(mp1, 0);
12046 					IP_REASS_SET_END(mp1, 0);
12047 					/* Subtract byte count */
12048 					ipf->ipf_count -=
12049 					    mp1->b_datap->db_lim -
12050 					    mp1->b_datap->db_base;
12051 					freeb(mp1);
12052 					BUMP_MIB(ill->ill_ip_mib,
12053 					    ipIfStatsReasmPartDups);
12054 					mp1 = mp->b_cont;
12055 					if (!mp1)
12056 						break;
12057 					offset = IP_REASS_START(mp1);
12058 				}
12059 			}
12060 			break;
12061 		}
12062 	} while (start = end, mp = next_mp);
12063 
12064 	/* Fragment just processed could be the last one. Remember this fact */
12065 	if (!more)
12066 		ipf->ipf_last_frag_seen = B_TRUE;
12067 
12068 	/* Still got holes? */
12069 	if (ipf->ipf_hole_cnt)
12070 		return (IP_REASS_PARTIAL);
12071 	/* Clean up overloaded fields to avoid upstream disasters. */
12072 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12073 		IP_REASS_SET_START(mp1, 0);
12074 		IP_REASS_SET_END(mp1, 0);
12075 	}
12076 	return (IP_REASS_COMPLETE);
12077 }
12078 
12079 /*
12080  * ipsec processing for the fast path, used for input UDP Packets
12081  * Returns true if ready for passup to UDP.
12082  * Return false if packet is not passable to UDP (e.g. it failed IPsec policy,
12083  * was an ESP-in-UDP packet, etc.).
12084  */
12085 static boolean_t
12086 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
12087     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present, ire_t *ire)
12088 {
12089 	uint32_t	ill_index;
12090 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
12091 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
12092 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12093 	udp_t		*udp = connp->conn_udp;
12094 
12095 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12096 	/* The ill_index of the incoming ILL */
12097 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
12098 
12099 	/* pass packet up to the transport */
12100 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
12101 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
12102 		    NULL, mctl_present);
12103 		if (*first_mpp == NULL) {
12104 			return (B_FALSE);
12105 		}
12106 	}
12107 
12108 	/* Initiate IPPF processing for fastpath UDP */
12109 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12110 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
12111 		if (*mpp == NULL) {
12112 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
12113 			    "deferred/dropped during IPPF processing\n"));
12114 			return (B_FALSE);
12115 		}
12116 	}
12117 	/*
12118 	 * Remove 0-spi if it's 0, or move everything behind
12119 	 * the UDP header over it and forward to ESP via
12120 	 * ip_proto_input().
12121 	 */
12122 	if (udp->udp_nat_t_endpoint) {
12123 		if (mctl_present) {
12124 			/* mctl_present *shouldn't* happen. */
12125 			ip_drop_packet(*first_mpp, B_TRUE, NULL,
12126 			    NULL, DROPPER(ipss, ipds_esp_nat_t_ipsec),
12127 			    &ipss->ipsec_dropper);
12128 			*first_mpp = NULL;
12129 			return (B_FALSE);
12130 		}
12131 
12132 		/* "ill" is "recv_ill" in actuality. */
12133 		if (!zero_spi_check(q, *mpp, ire, ill, ipss))
12134 			return (B_FALSE);
12135 
12136 		/* Else continue like a normal UDP packet. */
12137 	}
12138 
12139 	/*
12140 	 * We make the checks as below since we are in the fast path
12141 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12142 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12143 	 */
12144 	if (connp->conn_recvif || connp->conn_recvslla ||
12145 	    connp->conn_ip_recvpktinfo) {
12146 		if (connp->conn_recvif) {
12147 			in_flags = IPF_RECVIF;
12148 		}
12149 		/*
12150 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12151 		 * so the flag passed to ip_add_info is based on IP version
12152 		 * of connp.
12153 		 */
12154 		if (connp->conn_ip_recvpktinfo) {
12155 			if (connp->conn_af_isv6) {
12156 				/*
12157 				 * V6 only needs index
12158 				 */
12159 				in_flags |= IPF_RECVIF;
12160 			} else {
12161 				/*
12162 				 * V4 needs index + matching address.
12163 				 */
12164 				in_flags |= IPF_RECVADDR;
12165 			}
12166 		}
12167 		if (connp->conn_recvslla) {
12168 			in_flags |= IPF_RECVSLLA;
12169 		}
12170 		/*
12171 		 * since in_flags are being set ill will be
12172 		 * referenced in ip_add_info, so it better not
12173 		 * be NULL.
12174 		 */
12175 		/*
12176 		 * the actual data will be contained in b_cont
12177 		 * upon successful return of the following call.
12178 		 * If the call fails then the original mblk is
12179 		 * returned.
12180 		 */
12181 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12182 		    ipst);
12183 	}
12184 
12185 	return (B_TRUE);
12186 }
12187 
12188 /*
12189  * Fragmentation reassembly.  Each ILL has a hash table for
12190  * queuing packets undergoing reassembly for all IPIFs
12191  * associated with the ILL.  The hash is based on the packet
12192  * IP ident field.  The ILL frag hash table was allocated
12193  * as a timer block at the time the ILL was created.  Whenever
12194  * there is anything on the reassembly queue, the timer will
12195  * be running.  Returns B_TRUE if successful else B_FALSE;
12196  * frees mp on failure.
12197  */
12198 static boolean_t
12199 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
12200     uint32_t *cksum_val, uint16_t *cksum_flags)
12201 {
12202 	uint32_t	frag_offset_flags;
12203 	ill_t		*ill = (ill_t *)q->q_ptr;
12204 	mblk_t		*mp = *mpp;
12205 	mblk_t		*t_mp;
12206 	ipaddr_t	dst;
12207 	uint8_t		proto = ipha->ipha_protocol;
12208 	uint32_t	sum_val;
12209 	uint16_t	sum_flags;
12210 	ipf_t		*ipf;
12211 	ipf_t		**ipfp;
12212 	ipfb_t		*ipfb;
12213 	uint16_t	ident;
12214 	uint32_t	offset;
12215 	ipaddr_t	src;
12216 	uint_t		hdr_length;
12217 	uint32_t	end;
12218 	mblk_t		*mp1;
12219 	mblk_t		*tail_mp;
12220 	size_t		count;
12221 	size_t		msg_len;
12222 	uint8_t		ecn_info = 0;
12223 	uint32_t	packet_size;
12224 	boolean_t	pruned = B_FALSE;
12225 	ip_stack_t *ipst = ill->ill_ipst;
12226 
12227 	if (cksum_val != NULL)
12228 		*cksum_val = 0;
12229 	if (cksum_flags != NULL)
12230 		*cksum_flags = 0;
12231 
12232 	/*
12233 	 * Drop the fragmented as early as possible, if
12234 	 * we don't have resource(s) to re-assemble.
12235 	 */
12236 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12237 		freemsg(mp);
12238 		return (B_FALSE);
12239 	}
12240 
12241 	/* Check for fragmentation offset; return if there's none */
12242 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12243 	    (IPH_MF | IPH_OFFSET)) == 0)
12244 		return (B_TRUE);
12245 
12246 	/*
12247 	 * We utilize hardware computed checksum info only for UDP since
12248 	 * IP fragmentation is a normal occurence for the protocol.  In
12249 	 * addition, checksum offload support for IP fragments carrying
12250 	 * UDP payload is commonly implemented across network adapters.
12251 	 */
12252 	ASSERT(ill != NULL);
12253 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
12254 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12255 		mblk_t *mp1 = mp->b_cont;
12256 		int32_t len;
12257 
12258 		/* Record checksum information from the packet */
12259 		sum_val = (uint32_t)DB_CKSUM16(mp);
12260 		sum_flags = DB_CKSUMFLAGS(mp);
12261 
12262 		/* IP payload offset from beginning of mblk */
12263 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12264 
12265 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12266 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12267 		    offset >= DB_CKSUMSTART(mp) &&
12268 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12269 			uint32_t adj;
12270 			/*
12271 			 * Partial checksum has been calculated by hardware
12272 			 * and attached to the packet; in addition, any
12273 			 * prepended extraneous data is even byte aligned.
12274 			 * If any such data exists, we adjust the checksum;
12275 			 * this would also handle any postpended data.
12276 			 */
12277 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12278 			    mp, mp1, len, adj);
12279 
12280 			/* One's complement subtract extraneous checksum */
12281 			if (adj >= sum_val)
12282 				sum_val = ~(adj - sum_val) & 0xFFFF;
12283 			else
12284 				sum_val -= adj;
12285 		}
12286 	} else {
12287 		sum_val = 0;
12288 		sum_flags = 0;
12289 	}
12290 
12291 	/* Clear hardware checksumming flag */
12292 	DB_CKSUMFLAGS(mp) = 0;
12293 
12294 	ident = ipha->ipha_ident;
12295 	offset = (frag_offset_flags << 3) & 0xFFFF;
12296 	src = ipha->ipha_src;
12297 	dst = ipha->ipha_dst;
12298 	hdr_length = IPH_HDR_LENGTH(ipha);
12299 	end = ntohs(ipha->ipha_length) - hdr_length;
12300 
12301 	/* If end == 0 then we have a packet with no data, so just free it */
12302 	if (end == 0) {
12303 		freemsg(mp);
12304 		return (B_FALSE);
12305 	}
12306 
12307 	/* Record the ECN field info. */
12308 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12309 	if (offset != 0) {
12310 		/*
12311 		 * If this isn't the first piece, strip the header, and
12312 		 * add the offset to the end value.
12313 		 */
12314 		mp->b_rptr += hdr_length;
12315 		end += offset;
12316 	}
12317 
12318 	msg_len = MBLKSIZE(mp);
12319 	tail_mp = mp;
12320 	while (tail_mp->b_cont != NULL) {
12321 		tail_mp = tail_mp->b_cont;
12322 		msg_len += MBLKSIZE(tail_mp);
12323 	}
12324 
12325 	/* If the reassembly list for this ILL will get too big, prune it */
12326 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12327 	    ipst->ips_ip_reass_queue_bytes) {
12328 		ill_frag_prune(ill,
12329 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12330 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12331 		pruned = B_TRUE;
12332 	}
12333 
12334 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12335 	mutex_enter(&ipfb->ipfb_lock);
12336 
12337 	ipfp = &ipfb->ipfb_ipf;
12338 	/* Try to find an existing fragment queue for this packet. */
12339 	for (;;) {
12340 		ipf = ipfp[0];
12341 		if (ipf != NULL) {
12342 			/*
12343 			 * It has to match on ident and src/dst address.
12344 			 */
12345 			if (ipf->ipf_ident == ident &&
12346 			    ipf->ipf_src == src &&
12347 			    ipf->ipf_dst == dst &&
12348 			    ipf->ipf_protocol == proto) {
12349 				/*
12350 				 * If we have received too many
12351 				 * duplicate fragments for this packet
12352 				 * free it.
12353 				 */
12354 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12355 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12356 					freemsg(mp);
12357 					mutex_exit(&ipfb->ipfb_lock);
12358 					return (B_FALSE);
12359 				}
12360 				/* Found it. */
12361 				break;
12362 			}
12363 			ipfp = &ipf->ipf_hash_next;
12364 			continue;
12365 		}
12366 
12367 		/*
12368 		 * If we pruned the list, do we want to store this new
12369 		 * fragment?. We apply an optimization here based on the
12370 		 * fact that most fragments will be received in order.
12371 		 * So if the offset of this incoming fragment is zero,
12372 		 * it is the first fragment of a new packet. We will
12373 		 * keep it.  Otherwise drop the fragment, as we have
12374 		 * probably pruned the packet already (since the
12375 		 * packet cannot be found).
12376 		 */
12377 		if (pruned && offset != 0) {
12378 			mutex_exit(&ipfb->ipfb_lock);
12379 			freemsg(mp);
12380 			return (B_FALSE);
12381 		}
12382 
12383 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12384 			/*
12385 			 * Too many fragmented packets in this hash
12386 			 * bucket. Free the oldest.
12387 			 */
12388 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12389 		}
12390 
12391 		/* New guy.  Allocate a frag message. */
12392 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12393 		if (mp1 == NULL) {
12394 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12395 			freemsg(mp);
12396 reass_done:
12397 			mutex_exit(&ipfb->ipfb_lock);
12398 			return (B_FALSE);
12399 		}
12400 
12401 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12402 		mp1->b_cont = mp;
12403 
12404 		/* Initialize the fragment header. */
12405 		ipf = (ipf_t *)mp1->b_rptr;
12406 		ipf->ipf_mp = mp1;
12407 		ipf->ipf_ptphn = ipfp;
12408 		ipfp[0] = ipf;
12409 		ipf->ipf_hash_next = NULL;
12410 		ipf->ipf_ident = ident;
12411 		ipf->ipf_protocol = proto;
12412 		ipf->ipf_src = src;
12413 		ipf->ipf_dst = dst;
12414 		ipf->ipf_nf_hdr_len = 0;
12415 		/* Record reassembly start time. */
12416 		ipf->ipf_timestamp = gethrestime_sec();
12417 		/* Record ipf generation and account for frag header */
12418 		ipf->ipf_gen = ill->ill_ipf_gen++;
12419 		ipf->ipf_count = MBLKSIZE(mp1);
12420 		ipf->ipf_last_frag_seen = B_FALSE;
12421 		ipf->ipf_ecn = ecn_info;
12422 		ipf->ipf_num_dups = 0;
12423 		ipfb->ipfb_frag_pkts++;
12424 		ipf->ipf_checksum = 0;
12425 		ipf->ipf_checksum_flags = 0;
12426 
12427 		/* Store checksum value in fragment header */
12428 		if (sum_flags != 0) {
12429 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12430 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12431 			ipf->ipf_checksum = sum_val;
12432 			ipf->ipf_checksum_flags = sum_flags;
12433 		}
12434 
12435 		/*
12436 		 * We handle reassembly two ways.  In the easy case,
12437 		 * where all the fragments show up in order, we do
12438 		 * minimal bookkeeping, and just clip new pieces on
12439 		 * the end.  If we ever see a hole, then we go off
12440 		 * to ip_reassemble which has to mark the pieces and
12441 		 * keep track of the number of holes, etc.  Obviously,
12442 		 * the point of having both mechanisms is so we can
12443 		 * handle the easy case as efficiently as possible.
12444 		 */
12445 		if (offset == 0) {
12446 			/* Easy case, in-order reassembly so far. */
12447 			ipf->ipf_count += msg_len;
12448 			ipf->ipf_tail_mp = tail_mp;
12449 			/*
12450 			 * Keep track of next expected offset in
12451 			 * ipf_end.
12452 			 */
12453 			ipf->ipf_end = end;
12454 			ipf->ipf_nf_hdr_len = hdr_length;
12455 		} else {
12456 			/* Hard case, hole at the beginning. */
12457 			ipf->ipf_tail_mp = NULL;
12458 			/*
12459 			 * ipf_end == 0 means that we have given up
12460 			 * on easy reassembly.
12461 			 */
12462 			ipf->ipf_end = 0;
12463 
12464 			/* Forget checksum offload from now on */
12465 			ipf->ipf_checksum_flags = 0;
12466 
12467 			/*
12468 			 * ipf_hole_cnt is set by ip_reassemble.
12469 			 * ipf_count is updated by ip_reassemble.
12470 			 * No need to check for return value here
12471 			 * as we don't expect reassembly to complete
12472 			 * or fail for the first fragment itself.
12473 			 */
12474 			(void) ip_reassemble(mp, ipf,
12475 			    (frag_offset_flags & IPH_OFFSET) << 3,
12476 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12477 		}
12478 		/* Update per ipfb and ill byte counts */
12479 		ipfb->ipfb_count += ipf->ipf_count;
12480 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12481 		ill->ill_frag_count += ipf->ipf_count;
12482 		/* If the frag timer wasn't already going, start it. */
12483 		mutex_enter(&ill->ill_lock);
12484 		ill_frag_timer_start(ill);
12485 		mutex_exit(&ill->ill_lock);
12486 		goto reass_done;
12487 	}
12488 
12489 	/*
12490 	 * If the packet's flag has changed (it could be coming up
12491 	 * from an interface different than the previous, therefore
12492 	 * possibly different checksum capability), then forget about
12493 	 * any stored checksum states.  Otherwise add the value to
12494 	 * the existing one stored in the fragment header.
12495 	 */
12496 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12497 		sum_val += ipf->ipf_checksum;
12498 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12499 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12500 		ipf->ipf_checksum = sum_val;
12501 	} else if (ipf->ipf_checksum_flags != 0) {
12502 		/* Forget checksum offload from now on */
12503 		ipf->ipf_checksum_flags = 0;
12504 	}
12505 
12506 	/*
12507 	 * We have a new piece of a datagram which is already being
12508 	 * reassembled.  Update the ECN info if all IP fragments
12509 	 * are ECN capable.  If there is one which is not, clear
12510 	 * all the info.  If there is at least one which has CE
12511 	 * code point, IP needs to report that up to transport.
12512 	 */
12513 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12514 		if (ecn_info == IPH_ECN_CE)
12515 			ipf->ipf_ecn = IPH_ECN_CE;
12516 	} else {
12517 		ipf->ipf_ecn = IPH_ECN_NECT;
12518 	}
12519 	if (offset && ipf->ipf_end == offset) {
12520 		/* The new fragment fits at the end */
12521 		ipf->ipf_tail_mp->b_cont = mp;
12522 		/* Update the byte count */
12523 		ipf->ipf_count += msg_len;
12524 		/* Update per ipfb and ill byte counts */
12525 		ipfb->ipfb_count += msg_len;
12526 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12527 		ill->ill_frag_count += msg_len;
12528 		if (frag_offset_flags & IPH_MF) {
12529 			/* More to come. */
12530 			ipf->ipf_end = end;
12531 			ipf->ipf_tail_mp = tail_mp;
12532 			goto reass_done;
12533 		}
12534 	} else {
12535 		/* Go do the hard cases. */
12536 		int ret;
12537 
12538 		if (offset == 0)
12539 			ipf->ipf_nf_hdr_len = hdr_length;
12540 
12541 		/* Save current byte count */
12542 		count = ipf->ipf_count;
12543 		ret = ip_reassemble(mp, ipf,
12544 		    (frag_offset_flags & IPH_OFFSET) << 3,
12545 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12546 		/* Count of bytes added and subtracted (freeb()ed) */
12547 		count = ipf->ipf_count - count;
12548 		if (count) {
12549 			/* Update per ipfb and ill byte counts */
12550 			ipfb->ipfb_count += count;
12551 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12552 			ill->ill_frag_count += count;
12553 		}
12554 		if (ret == IP_REASS_PARTIAL) {
12555 			goto reass_done;
12556 		} else if (ret == IP_REASS_FAILED) {
12557 			/* Reassembly failed. Free up all resources */
12558 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12559 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12560 				IP_REASS_SET_START(t_mp, 0);
12561 				IP_REASS_SET_END(t_mp, 0);
12562 			}
12563 			freemsg(mp);
12564 			goto reass_done;
12565 		}
12566 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12567 	}
12568 	/*
12569 	 * We have completed reassembly.  Unhook the frag header from
12570 	 * the reassembly list.
12571 	 *
12572 	 * Before we free the frag header, record the ECN info
12573 	 * to report back to the transport.
12574 	 */
12575 	ecn_info = ipf->ipf_ecn;
12576 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12577 	ipfp = ipf->ipf_ptphn;
12578 
12579 	/* We need to supply these to caller */
12580 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12581 		sum_val = ipf->ipf_checksum;
12582 	else
12583 		sum_val = 0;
12584 
12585 	mp1 = ipf->ipf_mp;
12586 	count = ipf->ipf_count;
12587 	ipf = ipf->ipf_hash_next;
12588 	if (ipf != NULL)
12589 		ipf->ipf_ptphn = ipfp;
12590 	ipfp[0] = ipf;
12591 	ill->ill_frag_count -= count;
12592 	ASSERT(ipfb->ipfb_count >= count);
12593 	ipfb->ipfb_count -= count;
12594 	ipfb->ipfb_frag_pkts--;
12595 	mutex_exit(&ipfb->ipfb_lock);
12596 	/* Ditch the frag header. */
12597 	mp = mp1->b_cont;
12598 
12599 	freeb(mp1);
12600 
12601 	/* Restore original IP length in header. */
12602 	packet_size = (uint32_t)msgdsize(mp);
12603 	if (packet_size > IP_MAXPACKET) {
12604 		freemsg(mp);
12605 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12606 		return (B_FALSE);
12607 	}
12608 
12609 	if (DB_REF(mp) > 1) {
12610 		mblk_t *mp2 = copymsg(mp);
12611 
12612 		freemsg(mp);
12613 		if (mp2 == NULL) {
12614 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12615 			return (B_FALSE);
12616 		}
12617 		mp = mp2;
12618 	}
12619 	ipha = (ipha_t *)mp->b_rptr;
12620 
12621 	ipha->ipha_length = htons((uint16_t)packet_size);
12622 	/* We're now complete, zip the frag state */
12623 	ipha->ipha_fragment_offset_and_flags = 0;
12624 	/* Record the ECN info. */
12625 	ipha->ipha_type_of_service &= 0xFC;
12626 	ipha->ipha_type_of_service |= ecn_info;
12627 	*mpp = mp;
12628 
12629 	/* Reassembly is successful; return checksum information if needed */
12630 	if (cksum_val != NULL)
12631 		*cksum_val = sum_val;
12632 	if (cksum_flags != NULL)
12633 		*cksum_flags = sum_flags;
12634 
12635 	return (B_TRUE);
12636 }
12637 
12638 /*
12639  * Perform ip header check sum update local options.
12640  * return B_TRUE if all is well, else return B_FALSE and release
12641  * the mp. caller is responsible for decrementing ire ref cnt.
12642  */
12643 static boolean_t
12644 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12645     ip_stack_t *ipst)
12646 {
12647 	mblk_t		*first_mp;
12648 	boolean_t	mctl_present;
12649 	uint16_t	sum;
12650 
12651 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12652 	/*
12653 	 * Don't do the checksum if it has gone through AH/ESP
12654 	 * processing.
12655 	 */
12656 	if (!mctl_present) {
12657 		sum = ip_csum_hdr(ipha);
12658 		if (sum != 0) {
12659 			if (ill != NULL) {
12660 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12661 			} else {
12662 				BUMP_MIB(&ipst->ips_ip_mib,
12663 				    ipIfStatsInCksumErrs);
12664 			}
12665 			freemsg(first_mp);
12666 			return (B_FALSE);
12667 		}
12668 	}
12669 
12670 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12671 		if (mctl_present)
12672 			freeb(first_mp);
12673 		return (B_FALSE);
12674 	}
12675 
12676 	return (B_TRUE);
12677 }
12678 
12679 /*
12680  * All udp packet are delivered to the local host via this routine.
12681  */
12682 void
12683 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12684     ill_t *recv_ill)
12685 {
12686 	uint32_t	sum;
12687 	uint32_t	u1;
12688 	boolean_t	mctl_present;
12689 	conn_t		*connp;
12690 	mblk_t		*first_mp;
12691 	uint16_t	*up;
12692 	ill_t		*ill = (ill_t *)q->q_ptr;
12693 	uint16_t	reass_hck_flags = 0;
12694 	ip_stack_t	*ipst;
12695 
12696 	ASSERT(recv_ill != NULL);
12697 	ipst = recv_ill->ill_ipst;
12698 
12699 #define	rptr    ((uchar_t *)ipha)
12700 
12701 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12702 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12703 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12704 	ASSERT(ill != NULL);
12705 
12706 	/*
12707 	 * FAST PATH for udp packets
12708 	 */
12709 
12710 	/* u1 is # words of IP options */
12711 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12712 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12713 
12714 	/* IP options present */
12715 	if (u1 != 0)
12716 		goto ipoptions;
12717 
12718 	/* Check the IP header checksum.  */
12719 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12720 		/* Clear the IP header h/w cksum flag */
12721 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12722 	} else if (!mctl_present) {
12723 		/*
12724 		 * Don't verify header checksum if this packet is coming
12725 		 * back from AH/ESP as we already did it.
12726 		 */
12727 #define	uph	((uint16_t *)ipha)
12728 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12729 		    uph[6] + uph[7] + uph[8] + uph[9];
12730 #undef	uph
12731 		/* finish doing IP checksum */
12732 		sum = (sum & 0xFFFF) + (sum >> 16);
12733 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12734 		if (sum != 0 && sum != 0xFFFF) {
12735 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12736 			freemsg(first_mp);
12737 			return;
12738 		}
12739 	}
12740 
12741 	/*
12742 	 * Count for SNMP of inbound packets for ire.
12743 	 * if mctl is present this might be a secure packet and
12744 	 * has already been counted for in ip_proto_input().
12745 	 */
12746 	if (!mctl_present) {
12747 		UPDATE_IB_PKT_COUNT(ire);
12748 		ire->ire_last_used_time = lbolt;
12749 	}
12750 
12751 	/* packet part of fragmented IP packet? */
12752 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12753 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12754 		goto fragmented;
12755 	}
12756 
12757 	/* u1 = IP header length (20 bytes) */
12758 	u1 = IP_SIMPLE_HDR_LENGTH;
12759 
12760 	/* packet does not contain complete IP & UDP headers */
12761 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12762 		goto udppullup;
12763 
12764 	/* up points to UDP header */
12765 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12766 #define	iphs    ((uint16_t *)ipha)
12767 
12768 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12769 	if (up[3] != 0) {
12770 		mblk_t *mp1 = mp->b_cont;
12771 		boolean_t cksum_err;
12772 		uint16_t hck_flags = 0;
12773 
12774 		/* Pseudo-header checksum */
12775 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12776 		    iphs[9] + up[2];
12777 
12778 		/*
12779 		 * Revert to software checksum calculation if the interface
12780 		 * isn't capable of checksum offload or if IPsec is present.
12781 		 */
12782 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12783 			hck_flags = DB_CKSUMFLAGS(mp);
12784 
12785 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12786 			IP_STAT(ipst, ip_in_sw_cksum);
12787 
12788 		IP_CKSUM_RECV(hck_flags, u1,
12789 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12790 		    (int32_t)((uchar_t *)up - rptr),
12791 		    mp, mp1, cksum_err);
12792 
12793 		if (cksum_err) {
12794 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12795 			if (hck_flags & HCK_FULLCKSUM)
12796 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12797 			else if (hck_flags & HCK_PARTIALCKSUM)
12798 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12799 			else
12800 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12801 
12802 			freemsg(first_mp);
12803 			return;
12804 		}
12805 	}
12806 
12807 	/* Non-fragmented broadcast or multicast packet? */
12808 	if (ire->ire_type == IRE_BROADCAST)
12809 		goto udpslowpath;
12810 
12811 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12812 	    ire->ire_zoneid, ipst)) != NULL) {
12813 		ASSERT(connp->conn_upq != NULL);
12814 		IP_STAT(ipst, ip_udp_fast_path);
12815 
12816 		if (CONN_UDP_FLOWCTLD(connp)) {
12817 			freemsg(mp);
12818 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
12819 		} else {
12820 			if (!mctl_present) {
12821 				BUMP_MIB(ill->ill_ip_mib,
12822 				    ipIfStatsHCInDelivers);
12823 			}
12824 			/*
12825 			 * mp and first_mp can change.
12826 			 */
12827 			if (ip_udp_check(q, connp, recv_ill,
12828 			    ipha, &mp, &first_mp, mctl_present, ire)) {
12829 				/* Send it upstream */
12830 				(connp->conn_recv)(connp, mp, NULL);
12831 			}
12832 		}
12833 		/*
12834 		 * freeb() cannot deal with null mblk being passed
12835 		 * in and first_mp can be set to null in the call
12836 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12837 		 */
12838 		if (mctl_present && first_mp != NULL) {
12839 			freeb(first_mp);
12840 		}
12841 		CONN_DEC_REF(connp);
12842 		return;
12843 	}
12844 
12845 	/*
12846 	 * if we got here we know the packet is not fragmented and
12847 	 * has no options. The classifier could not find a conn_t and
12848 	 * most likely its an icmp packet so send it through slow path.
12849 	 */
12850 
12851 	goto udpslowpath;
12852 
12853 ipoptions:
12854 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
12855 		goto slow_done;
12856 	}
12857 
12858 	UPDATE_IB_PKT_COUNT(ire);
12859 	ire->ire_last_used_time = lbolt;
12860 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12861 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12862 fragmented:
12863 		/*
12864 		 * "sum" and "reass_hck_flags" are non-zero if the
12865 		 * reassembled packet has a valid hardware computed
12866 		 * checksum information associated with it.
12867 		 */
12868 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
12869 			goto slow_done;
12870 		/*
12871 		 * Make sure that first_mp points back to mp as
12872 		 * the mp we came in with could have changed in
12873 		 * ip_rput_fragment().
12874 		 */
12875 		ASSERT(!mctl_present);
12876 		ipha = (ipha_t *)mp->b_rptr;
12877 		first_mp = mp;
12878 	}
12879 
12880 	/* Now we have a complete datagram, destined for this machine. */
12881 	u1 = IPH_HDR_LENGTH(ipha);
12882 	/* Pull up the UDP header, if necessary. */
12883 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12884 udppullup:
12885 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12886 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12887 			freemsg(first_mp);
12888 			goto slow_done;
12889 		}
12890 		ipha = (ipha_t *)mp->b_rptr;
12891 	}
12892 
12893 	/*
12894 	 * Validate the checksum for the reassembled packet; for the
12895 	 * pullup case we calculate the payload checksum in software.
12896 	 */
12897 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12898 	if (up[3] != 0) {
12899 		boolean_t cksum_err;
12900 
12901 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12902 			IP_STAT(ipst, ip_in_sw_cksum);
12903 
12904 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12905 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12906 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12907 		    iphs[9] + up[2], sum, cksum_err);
12908 
12909 		if (cksum_err) {
12910 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12911 
12912 			if (reass_hck_flags & HCK_FULLCKSUM)
12913 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12914 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12915 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12916 			else
12917 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12918 
12919 			freemsg(first_mp);
12920 			goto slow_done;
12921 		}
12922 	}
12923 udpslowpath:
12924 
12925 	/* Clear hardware checksum flag to be safe */
12926 	DB_CKSUMFLAGS(mp) = 0;
12927 
12928 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12929 	    (ire->ire_type == IRE_BROADCAST),
12930 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
12931 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12932 
12933 slow_done:
12934 	IP_STAT(ipst, ip_udp_slow_path);
12935 	return;
12936 
12937 #undef  iphs
12938 #undef  rptr
12939 }
12940 
12941 /* ARGSUSED */
12942 static mblk_t *
12943 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12944     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12945     ill_rx_ring_t *ill_ring)
12946 {
12947 	conn_t		*connp;
12948 	uint32_t	sum;
12949 	uint32_t	u1;
12950 	uint16_t	*up;
12951 	int		offset;
12952 	ssize_t		len;
12953 	mblk_t		*mp1;
12954 	boolean_t	syn_present = B_FALSE;
12955 	tcph_t		*tcph;
12956 	uint_t		ip_hdr_len;
12957 	ill_t		*ill = (ill_t *)q->q_ptr;
12958 	zoneid_t	zoneid = ire->ire_zoneid;
12959 	boolean_t	cksum_err;
12960 	uint16_t	hck_flags = 0;
12961 	ip_stack_t	*ipst = recv_ill->ill_ipst;
12962 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12963 
12964 #define	rptr	((uchar_t *)ipha)
12965 
12966 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12967 	ASSERT(ill != NULL);
12968 
12969 	/*
12970 	 * FAST PATH for tcp packets
12971 	 */
12972 
12973 	/* u1 is # words of IP options */
12974 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12975 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12976 
12977 	/* IP options present */
12978 	if (u1) {
12979 		goto ipoptions;
12980 	} else if (!mctl_present) {
12981 		/* Check the IP header checksum.  */
12982 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12983 			/* Clear the IP header h/w cksum flag */
12984 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12985 		} else if (!mctl_present) {
12986 			/*
12987 			 * Don't verify header checksum if this packet
12988 			 * is coming back from AH/ESP as we already did it.
12989 			 */
12990 #define	uph	((uint16_t *)ipha)
12991 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12992 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12993 #undef	uph
12994 			/* finish doing IP checksum */
12995 			sum = (sum & 0xFFFF) + (sum >> 16);
12996 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12997 			if (sum != 0 && sum != 0xFFFF) {
12998 				BUMP_MIB(ill->ill_ip_mib,
12999 				    ipIfStatsInCksumErrs);
13000 				goto error;
13001 			}
13002 		}
13003 	}
13004 
13005 	if (!mctl_present) {
13006 		UPDATE_IB_PKT_COUNT(ire);
13007 		ire->ire_last_used_time = lbolt;
13008 	}
13009 
13010 	/* packet part of fragmented IP packet? */
13011 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13012 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13013 		goto fragmented;
13014 	}
13015 
13016 	/* u1 = IP header length (20 bytes) */
13017 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
13018 
13019 	/* does packet contain IP+TCP headers? */
13020 	len = mp->b_wptr - rptr;
13021 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
13022 		IP_STAT(ipst, ip_tcppullup);
13023 		goto tcppullup;
13024 	}
13025 
13026 	/* TCP options present? */
13027 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
13028 
13029 	/*
13030 	 * If options need to be pulled up, then goto tcpoptions.
13031 	 * otherwise we are still in the fast path
13032 	 */
13033 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
13034 		IP_STAT(ipst, ip_tcpoptions);
13035 		goto tcpoptions;
13036 	}
13037 
13038 	/* multiple mblks of tcp data? */
13039 	if ((mp1 = mp->b_cont) != NULL) {
13040 		/* more then two? */
13041 		if (mp1->b_cont != NULL) {
13042 			IP_STAT(ipst, ip_multipkttcp);
13043 			goto multipkttcp;
13044 		}
13045 		len += mp1->b_wptr - mp1->b_rptr;
13046 	}
13047 
13048 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
13049 
13050 	/* part of pseudo checksum */
13051 
13052 	/* TCP datagram length */
13053 	u1 = len - IP_SIMPLE_HDR_LENGTH;
13054 
13055 #define	iphs    ((uint16_t *)ipha)
13056 
13057 #ifdef	_BIG_ENDIAN
13058 	u1 += IPPROTO_TCP;
13059 #else
13060 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13061 #endif
13062 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13063 
13064 	/*
13065 	 * Revert to software checksum calculation if the interface
13066 	 * isn't capable of checksum offload or if IPsec is present.
13067 	 */
13068 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
13069 		hck_flags = DB_CKSUMFLAGS(mp);
13070 
13071 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13072 		IP_STAT(ipst, ip_in_sw_cksum);
13073 
13074 	IP_CKSUM_RECV(hck_flags, u1,
13075 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
13076 	    (int32_t)((uchar_t *)up - rptr),
13077 	    mp, mp1, cksum_err);
13078 
13079 	if (cksum_err) {
13080 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13081 
13082 		if (hck_flags & HCK_FULLCKSUM)
13083 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
13084 		else if (hck_flags & HCK_PARTIALCKSUM)
13085 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
13086 		else
13087 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
13088 
13089 		goto error;
13090 	}
13091 
13092 try_again:
13093 
13094 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
13095 	    zoneid, ipst)) == NULL) {
13096 		/* Send the TH_RST */
13097 		goto no_conn;
13098 	}
13099 
13100 	/*
13101 	 * TCP FAST PATH for AF_INET socket.
13102 	 *
13103 	 * TCP fast path to avoid extra work. An AF_INET socket type
13104 	 * does not have facility to receive extra information via
13105 	 * ip_process or ip_add_info. Also, when the connection was
13106 	 * established, we made a check if this connection is impacted
13107 	 * by any global IPsec policy or per connection policy (a
13108 	 * policy that comes in effect later will not apply to this
13109 	 * connection). Since all this can be determined at the
13110 	 * connection establishment time, a quick check of flags
13111 	 * can avoid extra work.
13112 	 */
13113 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13114 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13115 		ASSERT(first_mp == mp);
13116 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13117 		SET_SQUEUE(mp, tcp_rput_data, connp);
13118 		return (mp);
13119 	}
13120 
13121 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
13122 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
13123 		if (IPCL_IS_TCP(connp)) {
13124 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13125 			DB_CKSUMSTART(mp) =
13126 			    (intptr_t)ip_squeue_get(ill_ring);
13127 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13128 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13129 				BUMP_MIB(ill->ill_ip_mib,
13130 				    ipIfStatsHCInDelivers);
13131 				SET_SQUEUE(mp, connp->conn_recv, connp);
13132 				return (mp);
13133 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13134 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13135 				BUMP_MIB(ill->ill_ip_mib,
13136 				    ipIfStatsHCInDelivers);
13137 				ip_squeue_enter_unbound++;
13138 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13139 				    connp);
13140 				return (mp);
13141 			}
13142 			syn_present = B_TRUE;
13143 		}
13144 
13145 	}
13146 
13147 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13148 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13149 
13150 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13151 		/* No need to send this packet to TCP */
13152 		if ((flags & TH_RST) || (flags & TH_URG)) {
13153 			CONN_DEC_REF(connp);
13154 			freemsg(first_mp);
13155 			return (NULL);
13156 		}
13157 		if (flags & TH_ACK) {
13158 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
13159 			    ipst->ips_netstack->netstack_tcp, connp);
13160 			CONN_DEC_REF(connp);
13161 			return (NULL);
13162 		}
13163 
13164 		CONN_DEC_REF(connp);
13165 		freemsg(first_mp);
13166 		return (NULL);
13167 	}
13168 
13169 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13170 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13171 		    ipha, NULL, mctl_present);
13172 		if (first_mp == NULL) {
13173 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13174 			CONN_DEC_REF(connp);
13175 			return (NULL);
13176 		}
13177 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13178 			ASSERT(syn_present);
13179 			if (mctl_present) {
13180 				ASSERT(first_mp != mp);
13181 				first_mp->b_datap->db_struioflag |=
13182 				    STRUIO_POLICY;
13183 			} else {
13184 				ASSERT(first_mp == mp);
13185 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13186 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13187 			}
13188 		} else {
13189 			/*
13190 			 * Discard first_mp early since we're dealing with a
13191 			 * fully-connected conn_t and tcp doesn't do policy in
13192 			 * this case.
13193 			 */
13194 			if (mctl_present) {
13195 				freeb(first_mp);
13196 				mctl_present = B_FALSE;
13197 			}
13198 			first_mp = mp;
13199 		}
13200 	}
13201 
13202 	/* Initiate IPPF processing for fastpath */
13203 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13204 		uint32_t	ill_index;
13205 
13206 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13207 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13208 		if (mp == NULL) {
13209 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13210 			    "deferred/dropped during IPPF processing\n"));
13211 			CONN_DEC_REF(connp);
13212 			if (mctl_present)
13213 				freeb(first_mp);
13214 			return (NULL);
13215 		} else if (mctl_present) {
13216 			/*
13217 			 * ip_process might return a new mp.
13218 			 */
13219 			ASSERT(first_mp != mp);
13220 			first_mp->b_cont = mp;
13221 		} else {
13222 			first_mp = mp;
13223 		}
13224 
13225 	}
13226 
13227 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13228 		/*
13229 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13230 		 * make sure IPF_RECVIF is passed to ip_add_info.
13231 		 */
13232 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13233 		    IPCL_ZONEID(connp), ipst);
13234 		if (mp == NULL) {
13235 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13236 			CONN_DEC_REF(connp);
13237 			if (mctl_present)
13238 				freeb(first_mp);
13239 			return (NULL);
13240 		} else if (mctl_present) {
13241 			/*
13242 			 * ip_add_info might return a new mp.
13243 			 */
13244 			ASSERT(first_mp != mp);
13245 			first_mp->b_cont = mp;
13246 		} else {
13247 			first_mp = mp;
13248 		}
13249 	}
13250 
13251 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13252 	if (IPCL_IS_TCP(connp)) {
13253 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13254 		return (first_mp);
13255 	} else {
13256 		/* SOCK_RAW, IPPROTO_TCP case */
13257 		(connp->conn_recv)(connp, first_mp, NULL);
13258 		CONN_DEC_REF(connp);
13259 		return (NULL);
13260 	}
13261 
13262 no_conn:
13263 	/* Initiate IPPf processing, if needed. */
13264 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13265 		uint32_t ill_index;
13266 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13267 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13268 		if (first_mp == NULL) {
13269 			return (NULL);
13270 		}
13271 	}
13272 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13273 
13274 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13275 	    ipst->ips_netstack->netstack_tcp, NULL);
13276 	return (NULL);
13277 ipoptions:
13278 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13279 		goto slow_done;
13280 	}
13281 
13282 	UPDATE_IB_PKT_COUNT(ire);
13283 	ire->ire_last_used_time = lbolt;
13284 
13285 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13286 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13287 fragmented:
13288 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
13289 			if (mctl_present)
13290 				freeb(first_mp);
13291 			goto slow_done;
13292 		}
13293 		/*
13294 		 * Make sure that first_mp points back to mp as
13295 		 * the mp we came in with could have changed in
13296 		 * ip_rput_fragment().
13297 		 */
13298 		ASSERT(!mctl_present);
13299 		ipha = (ipha_t *)mp->b_rptr;
13300 		first_mp = mp;
13301 	}
13302 
13303 	/* Now we have a complete datagram, destined for this machine. */
13304 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13305 
13306 	len = mp->b_wptr - mp->b_rptr;
13307 	/* Pull up a minimal TCP header, if necessary. */
13308 	if (len < (u1 + 20)) {
13309 tcppullup:
13310 		if (!pullupmsg(mp, u1 + 20)) {
13311 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13312 			goto error;
13313 		}
13314 		ipha = (ipha_t *)mp->b_rptr;
13315 		len = mp->b_wptr - mp->b_rptr;
13316 	}
13317 
13318 	/*
13319 	 * Extract the offset field from the TCP header.  As usual, we
13320 	 * try to help the compiler more than the reader.
13321 	 */
13322 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13323 	if (offset != 5) {
13324 tcpoptions:
13325 		if (offset < 5) {
13326 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13327 			goto error;
13328 		}
13329 		/*
13330 		 * There must be TCP options.
13331 		 * Make sure we can grab them.
13332 		 */
13333 		offset <<= 2;
13334 		offset += u1;
13335 		if (len < offset) {
13336 			if (!pullupmsg(mp, offset)) {
13337 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13338 				goto error;
13339 			}
13340 			ipha = (ipha_t *)mp->b_rptr;
13341 			len = mp->b_wptr - rptr;
13342 		}
13343 	}
13344 
13345 	/* Get the total packet length in len, including headers. */
13346 	if (mp->b_cont) {
13347 multipkttcp:
13348 		len = msgdsize(mp);
13349 	}
13350 
13351 	/*
13352 	 * Check the TCP checksum by pulling together the pseudo-
13353 	 * header checksum, and passing it to ip_csum to be added in
13354 	 * with the TCP datagram.
13355 	 *
13356 	 * Since we are not using the hwcksum if available we must
13357 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13358 	 * If either of these fails along the way the mblk is freed.
13359 	 * If this logic ever changes and mblk is reused to say send
13360 	 * ICMP's back, then this flag may need to be cleared in
13361 	 * other places as well.
13362 	 */
13363 	DB_CKSUMFLAGS(mp) = 0;
13364 
13365 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13366 
13367 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13368 #ifdef	_BIG_ENDIAN
13369 	u1 += IPPROTO_TCP;
13370 #else
13371 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13372 #endif
13373 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13374 	/*
13375 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13376 	 */
13377 	IP_STAT(ipst, ip_in_sw_cksum);
13378 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13379 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13380 		goto error;
13381 	}
13382 
13383 	IP_STAT(ipst, ip_tcp_slow_path);
13384 	goto try_again;
13385 #undef  iphs
13386 #undef  rptr
13387 
13388 error:
13389 	freemsg(first_mp);
13390 slow_done:
13391 	return (NULL);
13392 }
13393 
13394 /* ARGSUSED */
13395 static void
13396 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13397     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13398 {
13399 	conn_t		*connp;
13400 	uint32_t	sum;
13401 	uint32_t	u1;
13402 	ssize_t		len;
13403 	sctp_hdr_t	*sctph;
13404 	zoneid_t	zoneid = ire->ire_zoneid;
13405 	uint32_t	pktsum;
13406 	uint32_t	calcsum;
13407 	uint32_t	ports;
13408 	in6_addr_t	map_src, map_dst;
13409 	ill_t		*ill = (ill_t *)q->q_ptr;
13410 	ip_stack_t	*ipst;
13411 	sctp_stack_t	*sctps;
13412 
13413 	ASSERT(recv_ill != NULL);
13414 	ipst = recv_ill->ill_ipst;
13415 	sctps = ipst->ips_netstack->netstack_sctp;
13416 
13417 #define	rptr	((uchar_t *)ipha)
13418 
13419 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13420 	ASSERT(ill != NULL);
13421 
13422 	/* u1 is # words of IP options */
13423 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13424 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13425 
13426 	/* IP options present */
13427 	if (u1 > 0) {
13428 		goto ipoptions;
13429 	} else {
13430 		/* Check the IP header checksum.  */
13431 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill) &&
13432 		    !mctl_present) {
13433 #define	uph	((uint16_t *)ipha)
13434 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13435 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13436 #undef	uph
13437 			/* finish doing IP checksum */
13438 			sum = (sum & 0xFFFF) + (sum >> 16);
13439 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13440 			/*
13441 			 * Don't verify header checksum if this packet
13442 			 * is coming back from AH/ESP as we already did it.
13443 			 */
13444 			if (sum != 0 && sum != 0xFFFF) {
13445 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13446 				goto error;
13447 			}
13448 		}
13449 		/*
13450 		 * Since there is no SCTP h/w cksum support yet, just
13451 		 * clear the flag.
13452 		 */
13453 		DB_CKSUMFLAGS(mp) = 0;
13454 	}
13455 
13456 	/*
13457 	 * Don't verify header checksum if this packet is coming
13458 	 * back from AH/ESP as we already did it.
13459 	 */
13460 	if (!mctl_present) {
13461 		UPDATE_IB_PKT_COUNT(ire);
13462 		ire->ire_last_used_time = lbolt;
13463 	}
13464 
13465 	/* packet part of fragmented IP packet? */
13466 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13467 	if (u1 & (IPH_MF | IPH_OFFSET))
13468 		goto fragmented;
13469 
13470 	/* u1 = IP header length (20 bytes) */
13471 	u1 = IP_SIMPLE_HDR_LENGTH;
13472 
13473 find_sctp_client:
13474 	/* Pullup if we don't have the sctp common header. */
13475 	len = MBLKL(mp);
13476 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13477 		if (mp->b_cont == NULL ||
13478 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13479 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13480 			goto error;
13481 		}
13482 		ipha = (ipha_t *)mp->b_rptr;
13483 		len = MBLKL(mp);
13484 	}
13485 
13486 	sctph = (sctp_hdr_t *)(rptr + u1);
13487 #ifdef	DEBUG
13488 	if (!skip_sctp_cksum) {
13489 #endif
13490 		pktsum = sctph->sh_chksum;
13491 		sctph->sh_chksum = 0;
13492 		calcsum = sctp_cksum(mp, u1);
13493 		if (calcsum != pktsum) {
13494 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
13495 			goto error;
13496 		}
13497 		sctph->sh_chksum = pktsum;
13498 #ifdef	DEBUG	/* skip_sctp_cksum */
13499 	}
13500 #endif
13501 	/* get the ports */
13502 	ports = *(uint32_t *)&sctph->sh_sport;
13503 
13504 	IRE_REFRELE(ire);
13505 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13506 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13507 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13508 	    sctps)) == NULL) {
13509 		/* Check for raw socket or OOTB handling */
13510 		goto no_conn;
13511 	}
13512 
13513 	/* Found a client; up it goes */
13514 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13515 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13516 	return;
13517 
13518 no_conn:
13519 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13520 	    ports, mctl_present, flags, B_TRUE, zoneid);
13521 	return;
13522 
13523 ipoptions:
13524 	DB_CKSUMFLAGS(mp) = 0;
13525 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13526 		goto slow_done;
13527 
13528 	UPDATE_IB_PKT_COUNT(ire);
13529 	ire->ire_last_used_time = lbolt;
13530 
13531 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13532 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13533 fragmented:
13534 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
13535 			goto slow_done;
13536 		/*
13537 		 * Make sure that first_mp points back to mp as
13538 		 * the mp we came in with could have changed in
13539 		 * ip_rput_fragment().
13540 		 */
13541 		ASSERT(!mctl_present);
13542 		ipha = (ipha_t *)mp->b_rptr;
13543 		first_mp = mp;
13544 	}
13545 
13546 	/* Now we have a complete datagram, destined for this machine. */
13547 	u1 = IPH_HDR_LENGTH(ipha);
13548 	goto find_sctp_client;
13549 #undef  iphs
13550 #undef  rptr
13551 
13552 error:
13553 	freemsg(first_mp);
13554 slow_done:
13555 	IRE_REFRELE(ire);
13556 }
13557 
13558 #define	VER_BITS	0xF0
13559 #define	VERSION_6	0x60
13560 
13561 static boolean_t
13562 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13563     ipaddr_t *dstp, ip_stack_t *ipst)
13564 {
13565 	uint_t	opt_len;
13566 	ipha_t *ipha;
13567 	ssize_t len;
13568 	uint_t	pkt_len;
13569 
13570 	ASSERT(ill != NULL);
13571 	IP_STAT(ipst, ip_ipoptions);
13572 	ipha = *iphapp;
13573 
13574 #define	rptr    ((uchar_t *)ipha)
13575 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13576 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13577 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13578 		freemsg(mp);
13579 		return (B_FALSE);
13580 	}
13581 
13582 	/* multiple mblk or too short */
13583 	pkt_len = ntohs(ipha->ipha_length);
13584 
13585 	/* Get the number of words of IP options in the IP header. */
13586 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13587 	if (opt_len) {
13588 		/* IP Options present!  Validate and process. */
13589 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13590 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13591 			goto done;
13592 		}
13593 		/*
13594 		 * Recompute complete header length and make sure we
13595 		 * have access to all of it.
13596 		 */
13597 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13598 		if (len > (mp->b_wptr - rptr)) {
13599 			if (len > pkt_len) {
13600 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13601 				goto done;
13602 			}
13603 			if (!pullupmsg(mp, len)) {
13604 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13605 				goto done;
13606 			}
13607 			ipha = (ipha_t *)mp->b_rptr;
13608 		}
13609 		/*
13610 		 * Go off to ip_rput_options which returns the next hop
13611 		 * destination address, which may have been affected
13612 		 * by source routing.
13613 		 */
13614 		IP_STAT(ipst, ip_opt);
13615 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13616 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13617 			return (B_FALSE);
13618 		}
13619 	}
13620 	*iphapp = ipha;
13621 	return (B_TRUE);
13622 done:
13623 	/* clear b_prev - used by ip_mroute_decap */
13624 	mp->b_prev = NULL;
13625 	freemsg(mp);
13626 	return (B_FALSE);
13627 #undef  rptr
13628 }
13629 
13630 /*
13631  * Deal with the fact that there is no ire for the destination.
13632  */
13633 static ire_t *
13634 ip_rput_noire(queue_t *q, mblk_t *mp, int ll_multicast, ipaddr_t dst)
13635 {
13636 	ipha_t	*ipha;
13637 	ill_t	*ill;
13638 	ire_t	*ire;
13639 	boolean_t	check_multirt = B_FALSE;
13640 	ip_stack_t *ipst;
13641 
13642 	ipha = (ipha_t *)mp->b_rptr;
13643 	ill = (ill_t *)q->q_ptr;
13644 
13645 	ASSERT(ill != NULL);
13646 	ipst = ill->ill_ipst;
13647 
13648 	/*
13649 	 * No IRE for this destination, so it can't be for us.
13650 	 * Unless we are forwarding, drop the packet.
13651 	 * We have to let source routed packets through
13652 	 * since we don't yet know if they are 'ping -l'
13653 	 * packets i.e. if they will go out over the
13654 	 * same interface as they came in on.
13655 	 */
13656 	if (ll_multicast) {
13657 		freemsg(mp);
13658 		return (NULL);
13659 	}
13660 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13661 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13662 		freemsg(mp);
13663 		return (NULL);
13664 	}
13665 
13666 	/*
13667 	 * Mark this packet as having originated externally.
13668 	 *
13669 	 * For non-forwarding code path, ire_send later double
13670 	 * checks this interface to see if it is still exists
13671 	 * post-ARP resolution.
13672 	 *
13673 	 * Also, IPQOS uses this to differentiate between
13674 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13675 	 * QOS packet processing in ip_wput_attach_llhdr().
13676 	 * The QoS module can mark the b_band for a fastpath message
13677 	 * or the dl_priority field in a unitdata_req header for
13678 	 * CoS marking. This info can only be found in
13679 	 * ip_wput_attach_llhdr().
13680 	 */
13681 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13682 	/*
13683 	 * Clear the indication that this may have a hardware checksum
13684 	 * as we are not using it
13685 	 */
13686 	DB_CKSUMFLAGS(mp) = 0;
13687 
13688 	ire = ire_forward(dst, &check_multirt, NULL, NULL,
13689 	    MBLK_GETLABEL(mp), ipst);
13690 
13691 	if (ire == NULL && check_multirt) {
13692 		/* Let ip_newroute handle CGTP  */
13693 		ip_newroute(q, mp, dst, NULL, GLOBAL_ZONEID, ipst);
13694 		return (NULL);
13695 	}
13696 
13697 	if (ire != NULL)
13698 		return (ire);
13699 
13700 	mp->b_prev = mp->b_next = 0;
13701 	/* send icmp unreachable */
13702 	q = WR(q);
13703 	/* Sent by forwarding path, and router is global zone */
13704 	if (ip_source_routed(ipha, ipst)) {
13705 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13706 		    GLOBAL_ZONEID, ipst);
13707 	} else {
13708 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13709 		    ipst);
13710 	}
13711 
13712 	return (NULL);
13713 
13714 }
13715 
13716 /*
13717  * check ip header length and align it.
13718  */
13719 static boolean_t
13720 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13721 {
13722 	ssize_t len;
13723 	ill_t *ill;
13724 	ipha_t	*ipha;
13725 
13726 	len = MBLKL(mp);
13727 
13728 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13729 		ill = (ill_t *)q->q_ptr;
13730 
13731 		if (!OK_32PTR(mp->b_rptr))
13732 			IP_STAT(ipst, ip_notaligned1);
13733 		else
13734 			IP_STAT(ipst, ip_notaligned2);
13735 		/* Guard against bogus device drivers */
13736 		if (len < 0) {
13737 			/* clear b_prev - used by ip_mroute_decap */
13738 			mp->b_prev = NULL;
13739 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13740 			freemsg(mp);
13741 			return (B_FALSE);
13742 		}
13743 
13744 		if (ip_rput_pullups++ == 0) {
13745 			ipha = (ipha_t *)mp->b_rptr;
13746 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13747 			    "ip_check_and_align_header: %s forced us to "
13748 			    " pullup pkt, hdr len %ld, hdr addr %p",
13749 			    ill->ill_name, len, ipha);
13750 		}
13751 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13752 			/* clear b_prev - used by ip_mroute_decap */
13753 			mp->b_prev = NULL;
13754 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13755 			freemsg(mp);
13756 			return (B_FALSE);
13757 		}
13758 	}
13759 	return (B_TRUE);
13760 }
13761 
13762 ire_t *
13763 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13764 {
13765 	ire_t		*new_ire;
13766 	ill_t		*ire_ill;
13767 	uint_t		ifindex;
13768 	ip_stack_t	*ipst = ill->ill_ipst;
13769 	boolean_t	strict_check = B_FALSE;
13770 
13771 	/*
13772 	 * This packet came in on an interface other than the one associated
13773 	 * with the first ire we found for the destination address. We do
13774 	 * another ire lookup here, using the ingress ill, to see if the
13775 	 * interface is in an interface group.
13776 	 * As long as the ills belong to the same group, we don't consider
13777 	 * them to be arriving on the wrong interface. Thus, if the switch
13778 	 * is doing inbound load spreading, we won't drop packets when the
13779 	 * ip*_strict_dst_multihoming switch is on. Note, the same holds true
13780 	 * for 'usesrc groups' where the destination address may belong to
13781 	 * another interface to allow multipathing to happen.
13782 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
13783 	 * where the local address may not be unique. In this case we were
13784 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
13785 	 * actually returned. The new lookup, which is more specific, should
13786 	 * only find the IRE_LOCAL associated with the ingress ill if one
13787 	 * exists.
13788 	 */
13789 
13790 	if (ire->ire_ipversion == IPV4_VERSION) {
13791 		if (ipst->ips_ip_strict_dst_multihoming)
13792 			strict_check = B_TRUE;
13793 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
13794 		    ill->ill_ipif, ALL_ZONES, NULL,
13795 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13796 	} else {
13797 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
13798 		if (ipst->ips_ipv6_strict_dst_multihoming)
13799 			strict_check = B_TRUE;
13800 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
13801 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
13802 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13803 	}
13804 	/*
13805 	 * If the same ire that was returned in ip_input() is found then this
13806 	 * is an indication that interface groups are in use. The packet
13807 	 * arrived on a different ill in the group than the one associated with
13808 	 * the destination address.  If a different ire was found then the same
13809 	 * IP address must be hosted on multiple ills. This is possible with
13810 	 * unnumbered point2point interfaces. We switch to use this new ire in
13811 	 * order to have accurate interface statistics.
13812 	 */
13813 	if (new_ire != NULL) {
13814 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
13815 			ire_refrele(ire);
13816 			ire = new_ire;
13817 		} else {
13818 			ire_refrele(new_ire);
13819 		}
13820 		return (ire);
13821 	} else if ((ire->ire_rfq == NULL) &&
13822 	    (ire->ire_ipversion == IPV4_VERSION)) {
13823 		/*
13824 		 * The best match could have been the original ire which
13825 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
13826 		 * the strict multihoming checks are irrelevant as we consider
13827 		 * local addresses hosted on lo0 to be interface agnostic. We
13828 		 * only expect a null ire_rfq on IREs which are associated with
13829 		 * lo0 hence we can return now.
13830 		 */
13831 		return (ire);
13832 	}
13833 
13834 	/*
13835 	 * Chase pointers once and store locally.
13836 	 */
13837 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
13838 	    (ill_t *)(ire->ire_rfq->q_ptr);
13839 	ifindex = ill->ill_usesrc_ifindex;
13840 
13841 	/*
13842 	 * Check if it's a legal address on the 'usesrc' interface.
13843 	 */
13844 	if ((ifindex != 0) && (ire_ill != NULL) &&
13845 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
13846 		return (ire);
13847 	}
13848 
13849 	/*
13850 	 * If the ip*_strict_dst_multihoming switch is on then we can
13851 	 * only accept this packet if the interface is marked as routing.
13852 	 */
13853 	if (!(strict_check))
13854 		return (ire);
13855 
13856 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
13857 	    ILLF_ROUTER) != 0) {
13858 		return (ire);
13859 	}
13860 
13861 	ire_refrele(ire);
13862 	return (NULL);
13863 }
13864 
13865 ire_t *
13866 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13867 {
13868 	ipha_t	*ipha;
13869 	ipaddr_t ip_dst, ip_src;
13870 	ire_t	*src_ire = NULL;
13871 	ill_t	*stq_ill;
13872 	uint_t	hlen;
13873 	uint_t	pkt_len;
13874 	uint32_t sum;
13875 	queue_t	*dev_q;
13876 	boolean_t check_multirt = B_FALSE;
13877 	ip_stack_t *ipst = ill->ill_ipst;
13878 
13879 	ipha = (ipha_t *)mp->b_rptr;
13880 
13881 	/*
13882 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13883 	 * The loopback address check for both src and dst has already
13884 	 * been checked in ip_input
13885 	 */
13886 	ip_dst = ntohl(dst);
13887 	ip_src = ntohl(ipha->ipha_src);
13888 
13889 	if (ip_dst == INADDR_ANY || IN_BADCLASS(ip_dst) ||
13890 	    IN_CLASSD(ip_src)) {
13891 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13892 		goto drop;
13893 	}
13894 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13895 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
13896 
13897 	if (src_ire != NULL) {
13898 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13899 		goto drop;
13900 	}
13901 
13902 
13903 	/* No ire cache of nexthop. So first create one  */
13904 	if (ire == NULL) {
13905 		ire = ire_forward(dst, &check_multirt, NULL, NULL, NULL, ipst);
13906 		/*
13907 		 * We only come to ip_fast_forward if ip_cgtp_filter is
13908 		 * is not set. So upon return from ire_forward
13909 		 * check_multirt should remain as false.
13910 		 */
13911 		ASSERT(!check_multirt);
13912 		if (ire == NULL) {
13913 			/* An attempt was made to forward the packet */
13914 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13915 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13916 			mp->b_prev = mp->b_next = 0;
13917 			/* send icmp unreachable */
13918 			/* Sent by forwarding path, and router is global zone */
13919 			if (ip_source_routed(ipha, ipst)) {
13920 				icmp_unreachable(ill->ill_wq, mp,
13921 				    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID,
13922 				    ipst);
13923 			} else {
13924 				icmp_unreachable(ill->ill_wq, mp,
13925 				    ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13926 				    ipst);
13927 			}
13928 			return (ire);
13929 		}
13930 	}
13931 
13932 	/*
13933 	 * Forwarding fastpath exception case:
13934 	 * If either of the follwoing case is true, we take
13935 	 * the slowpath
13936 	 *	o forwarding is not enabled
13937 	 *	o incoming and outgoing interface are the same, or the same
13938 	 *	  IPMP group
13939 	 *	o corresponding ire is in incomplete state
13940 	 *	o packet needs fragmentation
13941 	 *
13942 	 * The codeflow from here on is thus:
13943 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
13944 	 */
13945 	pkt_len = ntohs(ipha->ipha_length);
13946 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
13947 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
13948 	    !(ill->ill_flags & ILLF_ROUTER) ||
13949 	    (ill == stq_ill) ||
13950 	    (ill->ill_group != NULL && ill->ill_group == stq_ill->ill_group) ||
13951 	    (ire->ire_nce == NULL) ||
13952 	    (ire->ire_nce->nce_state != ND_REACHABLE) ||
13953 	    (pkt_len > ire->ire_max_frag) ||
13954 	    ipha->ipha_ttl <= 1) {
13955 		ip_rput_process_forward(ill->ill_rq, mp, ire,
13956 		    ipha, ill, B_FALSE);
13957 		return (ire);
13958 	}
13959 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13960 
13961 	DTRACE_PROBE4(ip4__forwarding__start,
13962 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
13963 
13964 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
13965 	    ipst->ips_ipv4firewall_forwarding,
13966 	    ill, stq_ill, ipha, mp, mp, ipst);
13967 
13968 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
13969 
13970 	if (mp == NULL)
13971 		goto drop;
13972 
13973 	mp->b_datap->db_struioun.cksum.flags = 0;
13974 	/* Adjust the checksum to reflect the ttl decrement. */
13975 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
13976 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
13977 	ipha->ipha_ttl--;
13978 
13979 	dev_q = ire->ire_stq->q_next;
13980 	if ((dev_q->q_next != NULL ||
13981 	    dev_q->q_first != NULL) && !canput(dev_q)) {
13982 		goto indiscard;
13983 	}
13984 
13985 	hlen = ire->ire_nce->nce_fp_mp != NULL ?
13986 	    MBLKL(ire->ire_nce->nce_fp_mp) : 0;
13987 
13988 	if (hlen != 0 || ire->ire_nce->nce_res_mp != NULL) {
13989 		mblk_t *mpip = mp;
13990 
13991 		mp = ip_wput_attach_llhdr(mpip, ire, 0, 0);
13992 		if (mp != NULL) {
13993 			DTRACE_PROBE4(ip4__physical__out__start,
13994 			    ill_t *, NULL, ill_t *, stq_ill,
13995 			    ipha_t *, ipha, mblk_t *, mp);
13996 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
13997 			    ipst->ips_ipv4firewall_physical_out,
13998 			    NULL, stq_ill, ipha, mp, mpip, ipst);
13999 			DTRACE_PROBE1(ip4__physical__out__end, mblk_t *,
14000 			    mp);
14001 			if (mp == NULL)
14002 				goto drop;
14003 
14004 			UPDATE_IB_PKT_COUNT(ire);
14005 			ire->ire_last_used_time = lbolt;
14006 			BUMP_MIB(stq_ill->ill_ip_mib,
14007 			    ipIfStatsHCOutForwDatagrams);
14008 			BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14009 			UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets,
14010 			    pkt_len);
14011 			putnext(ire->ire_stq, mp);
14012 			return (ire);
14013 		}
14014 	}
14015 
14016 indiscard:
14017 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14018 drop:
14019 	if (mp != NULL)
14020 		freemsg(mp);
14021 	if (src_ire != NULL)
14022 		ire_refrele(src_ire);
14023 	return (ire);
14024 
14025 }
14026 
14027 /*
14028  * This function is called in the forwarding slowpath, when
14029  * either the ire lacks the link-layer address, or the packet needs
14030  * further processing(eg. fragmentation), before transmission.
14031  */
14032 
14033 static void
14034 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14035     ill_t *ill, boolean_t ll_multicast)
14036 {
14037 	ill_group_t	*ill_group;
14038 	ill_group_t	*ire_group;
14039 	queue_t		*dev_q;
14040 	ire_t		*src_ire;
14041 	ip_stack_t	*ipst = ill->ill_ipst;
14042 
14043 	ASSERT(ire->ire_stq != NULL);
14044 
14045 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14046 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14047 
14048 	if (ll_multicast != 0) {
14049 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14050 		goto drop_pkt;
14051 	}
14052 
14053 	/*
14054 	 * check if ipha_src is a broadcast address. Note that this
14055 	 * check is redundant when we get here from ip_fast_forward()
14056 	 * which has already done this check. However, since we can
14057 	 * also get here from ip_rput_process_broadcast() or, for
14058 	 * for the slow path through ip_fast_forward(), we perform
14059 	 * the check again for code-reusability
14060 	 */
14061 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14062 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14063 	if (src_ire != NULL || ntohl(ipha->ipha_dst) == INADDR_ANY ||
14064 	    IN_BADCLASS(ntohl(ipha->ipha_dst))) {
14065 		if (src_ire != NULL)
14066 			ire_refrele(src_ire);
14067 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14068 		ip2dbg(("ip_rput_process_forward: Received packet with"
14069 		    " bad src/dst address on %s\n", ill->ill_name));
14070 		goto drop_pkt;
14071 	}
14072 
14073 	ill_group = ill->ill_group;
14074 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
14075 	/*
14076 	 * Check if we want to forward this one at this time.
14077 	 * We allow source routed packets on a host provided that
14078 	 * they go out the same interface or same interface group
14079 	 * as they came in on.
14080 	 *
14081 	 * XXX To be quicker, we may wish to not chase pointers to
14082 	 * get the ILLF_ROUTER flag and instead store the
14083 	 * forwarding policy in the ire.  An unfortunate
14084 	 * side-effect of that would be requiring an ire flush
14085 	 * whenever the ILLF_ROUTER flag changes.
14086 	 */
14087 	if (((ill->ill_flags &
14088 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
14089 	    ILLF_ROUTER) == 0) &&
14090 	    !(ip_source_routed(ipha, ipst) && (ire->ire_rfq == q ||
14091 	    (ill_group != NULL && ill_group == ire_group)))) {
14092 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14093 		if (ip_source_routed(ipha, ipst)) {
14094 			q = WR(q);
14095 			/*
14096 			 * Clear the indication that this may have
14097 			 * hardware checksum as we are not using it.
14098 			 */
14099 			DB_CKSUMFLAGS(mp) = 0;
14100 			/* Sent by forwarding path, and router is global zone */
14101 			icmp_unreachable(q, mp,
14102 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
14103 			return;
14104 		}
14105 		goto drop_pkt;
14106 	}
14107 
14108 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14109 
14110 	/* Packet is being forwarded. Turning off hwcksum flag. */
14111 	DB_CKSUMFLAGS(mp) = 0;
14112 	if (ipst->ips_ip_g_send_redirects) {
14113 		/*
14114 		 * Check whether the incoming interface and outgoing
14115 		 * interface is part of the same group. If so,
14116 		 * send redirects.
14117 		 *
14118 		 * Check the source address to see if it originated
14119 		 * on the same logical subnet it is going back out on.
14120 		 * If so, we should be able to send it a redirect.
14121 		 * Avoid sending a redirect if the destination
14122 		 * is directly connected (i.e., ipha_dst is the same
14123 		 * as ire_gateway_addr or the ire_addr of the
14124 		 * nexthop IRE_CACHE ), or if the packet was source
14125 		 * routed out this interface.
14126 		 */
14127 		ipaddr_t src, nhop;
14128 		mblk_t	*mp1;
14129 		ire_t	*nhop_ire = NULL;
14130 
14131 		/*
14132 		 * Check whether ire_rfq and q are from the same ill
14133 		 * or if they are not same, they at least belong
14134 		 * to the same group. If so, send redirects.
14135 		 */
14136 		if ((ire->ire_rfq == q ||
14137 		    (ill_group != NULL && ill_group == ire_group)) &&
14138 		    !ip_source_routed(ipha, ipst)) {
14139 
14140 			nhop = (ire->ire_gateway_addr != 0 ?
14141 			    ire->ire_gateway_addr : ire->ire_addr);
14142 
14143 			if (ipha->ipha_dst == nhop) {
14144 				/*
14145 				 * We avoid sending a redirect if the
14146 				 * destination is directly connected
14147 				 * because it is possible that multiple
14148 				 * IP subnets may have been configured on
14149 				 * the link, and the source may not
14150 				 * be on the same subnet as ip destination,
14151 				 * even though they are on the same
14152 				 * physical link.
14153 				 */
14154 				goto sendit;
14155 			}
14156 
14157 			src = ipha->ipha_src;
14158 
14159 			/*
14160 			 * We look up the interface ire for the nexthop,
14161 			 * to see if ipha_src is in the same subnet
14162 			 * as the nexthop.
14163 			 *
14164 			 * Note that, if, in the future, IRE_CACHE entries
14165 			 * are obsoleted,  this lookup will not be needed,
14166 			 * as the ire passed to this function will be the
14167 			 * same as the nhop_ire computed below.
14168 			 */
14169 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14170 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14171 			    0, NULL, MATCH_IRE_TYPE, ipst);
14172 
14173 			if (nhop_ire != NULL) {
14174 				if ((src & nhop_ire->ire_mask) ==
14175 				    (nhop & nhop_ire->ire_mask)) {
14176 					/*
14177 					 * The source is directly connected.
14178 					 * Just copy the ip header (which is
14179 					 * in the first mblk)
14180 					 */
14181 					mp1 = copyb(mp);
14182 					if (mp1 != NULL) {
14183 						icmp_send_redirect(WR(q), mp1,
14184 						    nhop, ipst);
14185 					}
14186 				}
14187 				ire_refrele(nhop_ire);
14188 			}
14189 		}
14190 	}
14191 sendit:
14192 	dev_q = ire->ire_stq->q_next;
14193 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
14194 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14195 		freemsg(mp);
14196 		return;
14197 	}
14198 
14199 	ip_rput_forward(ire, ipha, mp, ill);
14200 	return;
14201 
14202 drop_pkt:
14203 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14204 	freemsg(mp);
14205 }
14206 
14207 ire_t *
14208 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14209     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14210 {
14211 	queue_t		*q;
14212 	uint16_t	hcksumflags;
14213 	ip_stack_t	*ipst = ill->ill_ipst;
14214 
14215 	q = *qp;
14216 
14217 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14218 
14219 	/*
14220 	 * Clear the indication that this may have hardware
14221 	 * checksum as we are not using it for forwarding.
14222 	 */
14223 	hcksumflags = DB_CKSUMFLAGS(mp);
14224 	DB_CKSUMFLAGS(mp) = 0;
14225 
14226 	/*
14227 	 * Directed broadcast forwarding: if the packet came in over a
14228 	 * different interface then it is routed out over we can forward it.
14229 	 */
14230 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14231 		ire_refrele(ire);
14232 		freemsg(mp);
14233 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14234 		return (NULL);
14235 	}
14236 	/*
14237 	 * For multicast we have set dst to be INADDR_BROADCAST
14238 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
14239 	 * only for broadcast packets.
14240 	 */
14241 	if (!CLASSD(ipha->ipha_dst)) {
14242 		ire_t *new_ire;
14243 		ipif_t *ipif;
14244 		/*
14245 		 * For ill groups, as the switch duplicates broadcasts
14246 		 * across all the ports, we need to filter out and
14247 		 * send up only one copy. There is one copy for every
14248 		 * broadcast address on each ill. Thus, we look for a
14249 		 * specific IRE on this ill and look at IRE_MARK_NORECV
14250 		 * later to see whether this ill is eligible to receive
14251 		 * them or not. ill_nominate_bcast_rcv() nominates only
14252 		 * one set of IREs for receiving.
14253 		 */
14254 
14255 		ipif = ipif_get_next_ipif(NULL, ill);
14256 		if (ipif == NULL) {
14257 			ire_refrele(ire);
14258 			freemsg(mp);
14259 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14260 			return (NULL);
14261 		}
14262 		new_ire = ire_ctable_lookup(dst, 0, 0,
14263 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14264 		ipif_refrele(ipif);
14265 
14266 		if (new_ire != NULL) {
14267 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
14268 				ire_refrele(ire);
14269 				ire_refrele(new_ire);
14270 				freemsg(mp);
14271 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14272 				return (NULL);
14273 			}
14274 			/*
14275 			 * In the special case of multirouted broadcast
14276 			 * packets, we unconditionally need to "gateway"
14277 			 * them to the appropriate interface here.
14278 			 * In the normal case, this cannot happen, because
14279 			 * there is no broadcast IRE tagged with the
14280 			 * RTF_MULTIRT flag.
14281 			 */
14282 			if (new_ire->ire_flags & RTF_MULTIRT) {
14283 				ire_refrele(new_ire);
14284 				if (ire->ire_rfq != NULL) {
14285 					q = ire->ire_rfq;
14286 					*qp = q;
14287 				}
14288 			} else {
14289 				ire_refrele(ire);
14290 				ire = new_ire;
14291 			}
14292 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14293 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14294 				/*
14295 				 * Free the message if
14296 				 * ip_g_forward_directed_bcast is turned
14297 				 * off for non-local broadcast.
14298 				 */
14299 				ire_refrele(ire);
14300 				freemsg(mp);
14301 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14302 				return (NULL);
14303 			}
14304 		} else {
14305 			/*
14306 			 * This CGTP packet successfully passed the
14307 			 * CGTP filter, but the related CGTP
14308 			 * broadcast IRE has not been found,
14309 			 * meaning that the redundant ipif is
14310 			 * probably down. However, if we discarded
14311 			 * this packet, its duplicate would be
14312 			 * filtered out by the CGTP filter so none
14313 			 * of them would get through. So we keep
14314 			 * going with this one.
14315 			 */
14316 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14317 			if (ire->ire_rfq != NULL) {
14318 				q = ire->ire_rfq;
14319 				*qp = q;
14320 			}
14321 		}
14322 	}
14323 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14324 		/*
14325 		 * Verify that there are not more then one
14326 		 * IRE_BROADCAST with this broadcast address which
14327 		 * has ire_stq set.
14328 		 * TODO: simplify, loop over all IRE's
14329 		 */
14330 		ire_t	*ire1;
14331 		int	num_stq = 0;
14332 		mblk_t	*mp1;
14333 
14334 		/* Find the first one with ire_stq set */
14335 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14336 		for (ire1 = ire; ire1 &&
14337 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14338 		    ire1 = ire1->ire_next)
14339 			;
14340 		if (ire1) {
14341 			ire_refrele(ire);
14342 			ire = ire1;
14343 			IRE_REFHOLD(ire);
14344 		}
14345 
14346 		/* Check if there are additional ones with stq set */
14347 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14348 			if (ire->ire_addr != ire1->ire_addr)
14349 				break;
14350 			if (ire1->ire_stq) {
14351 				num_stq++;
14352 				break;
14353 			}
14354 		}
14355 		rw_exit(&ire->ire_bucket->irb_lock);
14356 		if (num_stq == 1 && ire->ire_stq != NULL) {
14357 			ip1dbg(("ip_rput_process_broadcast: directed "
14358 			    "broadcast to 0x%x\n",
14359 			    ntohl(ire->ire_addr)));
14360 			mp1 = copymsg(mp);
14361 			if (mp1) {
14362 				switch (ipha->ipha_protocol) {
14363 				case IPPROTO_UDP:
14364 					ip_udp_input(q, mp1, ipha, ire, ill);
14365 					break;
14366 				default:
14367 					ip_proto_input(q, mp1, ipha, ire, ill,
14368 					    B_FALSE);
14369 					break;
14370 				}
14371 			}
14372 			/*
14373 			 * Adjust ttl to 2 (1+1 - the forward engine
14374 			 * will decrement it by one.
14375 			 */
14376 			if (ip_csum_hdr(ipha)) {
14377 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14378 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14379 				freemsg(mp);
14380 				ire_refrele(ire);
14381 				return (NULL);
14382 			}
14383 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14384 			ipha->ipha_hdr_checksum = 0;
14385 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14386 			ip_rput_process_forward(q, mp, ire, ipha,
14387 			    ill, ll_multicast);
14388 			ire_refrele(ire);
14389 			return (NULL);
14390 		}
14391 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14392 		    ntohl(ire->ire_addr)));
14393 	}
14394 
14395 
14396 	/* Restore any hardware checksum flags */
14397 	DB_CKSUMFLAGS(mp) = hcksumflags;
14398 	return (ire);
14399 }
14400 
14401 /* ARGSUSED */
14402 static boolean_t
14403 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14404     int *ll_multicast, ipaddr_t *dstp)
14405 {
14406 	ip_stack_t	*ipst = ill->ill_ipst;
14407 
14408 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14409 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14410 	    ntohs(ipha->ipha_length));
14411 
14412 	/*
14413 	 * Forward packets only if we have joined the allmulti
14414 	 * group on this interface.
14415 	 */
14416 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14417 		int retval;
14418 
14419 		/*
14420 		 * Clear the indication that this may have hardware
14421 		 * checksum as we are not using it.
14422 		 */
14423 		DB_CKSUMFLAGS(mp) = 0;
14424 		retval = ip_mforward(ill, ipha, mp);
14425 		/* ip_mforward updates mib variables if needed */
14426 		/* clear b_prev - used by ip_mroute_decap */
14427 		mp->b_prev = NULL;
14428 
14429 		switch (retval) {
14430 		case 0:
14431 			/*
14432 			 * pkt is okay and arrived on phyint.
14433 			 *
14434 			 * If we are running as a multicast router
14435 			 * we need to see all IGMP and/or PIM packets.
14436 			 */
14437 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14438 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14439 				goto done;
14440 			}
14441 			break;
14442 		case -1:
14443 			/* pkt is mal-formed, toss it */
14444 			goto drop_pkt;
14445 		case 1:
14446 			/* pkt is okay and arrived on a tunnel */
14447 			/*
14448 			 * If we are running a multicast router
14449 			 *  we need to see all igmp packets.
14450 			 */
14451 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14452 				*dstp = INADDR_BROADCAST;
14453 				*ll_multicast = 1;
14454 				return (B_FALSE);
14455 			}
14456 
14457 			goto drop_pkt;
14458 		}
14459 	}
14460 
14461 	ILM_WALKER_HOLD(ill);
14462 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14463 		/*
14464 		 * This might just be caused by the fact that
14465 		 * multiple IP Multicast addresses map to the same
14466 		 * link layer multicast - no need to increment counter!
14467 		 */
14468 		ILM_WALKER_RELE(ill);
14469 		freemsg(mp);
14470 		return (B_TRUE);
14471 	}
14472 	ILM_WALKER_RELE(ill);
14473 done:
14474 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14475 	/*
14476 	 * This assumes the we deliver to all streams for multicast
14477 	 * and broadcast packets.
14478 	 */
14479 	*dstp = INADDR_BROADCAST;
14480 	*ll_multicast = 1;
14481 	return (B_FALSE);
14482 drop_pkt:
14483 	ip2dbg(("ip_rput: drop pkt\n"));
14484 	freemsg(mp);
14485 	return (B_TRUE);
14486 }
14487 
14488 static boolean_t
14489 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14490     int *ll_multicast, mblk_t **mpp)
14491 {
14492 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14493 	boolean_t must_copy = B_FALSE;
14494 	struct iocblk   *iocp;
14495 	ipha_t		*ipha;
14496 	ip_stack_t	*ipst = ill->ill_ipst;
14497 
14498 #define	rptr    ((uchar_t *)ipha)
14499 
14500 	first_mp = *first_mpp;
14501 	mp = *mpp;
14502 
14503 	ASSERT(first_mp == mp);
14504 
14505 	/*
14506 	 * if db_ref > 1 then copymsg and free original. Packet may be
14507 	 * changed and do not want other entity who has a reference to this
14508 	 * message to trip over the changes. This is a blind change because
14509 	 * trying to catch all places that might change packet is too
14510 	 * difficult (since it may be a module above this one)
14511 	 *
14512 	 * This corresponds to the non-fast path case. We walk down the full
14513 	 * chain in this case, and check the db_ref count of all the dblks,
14514 	 * and do a copymsg if required. It is possible that the db_ref counts
14515 	 * of the data blocks in the mblk chain can be different.
14516 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14517 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14518 	 * 'snoop' is running.
14519 	 */
14520 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14521 		if (mp1->b_datap->db_ref > 1) {
14522 			must_copy = B_TRUE;
14523 			break;
14524 		}
14525 	}
14526 
14527 	if (must_copy) {
14528 		mp1 = copymsg(mp);
14529 		if (mp1 == NULL) {
14530 			for (mp1 = mp; mp1 != NULL;
14531 			    mp1 = mp1->b_cont) {
14532 				mp1->b_next = NULL;
14533 				mp1->b_prev = NULL;
14534 			}
14535 			freemsg(mp);
14536 			if (ill != NULL) {
14537 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14538 			} else {
14539 				BUMP_MIB(&ipst->ips_ip_mib,
14540 				    ipIfStatsInDiscards);
14541 			}
14542 			return (B_TRUE);
14543 		}
14544 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14545 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14546 			/* Copy b_prev - used by ip_mroute_decap */
14547 			to_mp->b_prev = from_mp->b_prev;
14548 			from_mp->b_prev = NULL;
14549 		}
14550 		*first_mpp = first_mp = mp1;
14551 		freemsg(mp);
14552 		mp = mp1;
14553 		*mpp = mp1;
14554 	}
14555 
14556 	ipha = (ipha_t *)mp->b_rptr;
14557 
14558 	/*
14559 	 * previous code has a case for M_DATA.
14560 	 * We want to check how that happens.
14561 	 */
14562 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14563 	switch (first_mp->b_datap->db_type) {
14564 	case M_PROTO:
14565 	case M_PCPROTO:
14566 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14567 		    DL_UNITDATA_IND) {
14568 			/* Go handle anything other than data elsewhere. */
14569 			ip_rput_dlpi(q, mp);
14570 			return (B_TRUE);
14571 		}
14572 		*ll_multicast = ((dl_unitdata_ind_t *)rptr)->dl_group_address;
14573 		/* Ditch the DLPI header. */
14574 		mp1 = mp->b_cont;
14575 		ASSERT(first_mp == mp);
14576 		*first_mpp = mp1;
14577 		freeb(mp);
14578 		*mpp = mp1;
14579 		return (B_FALSE);
14580 	case M_IOCACK:
14581 		ip1dbg(("got iocack "));
14582 		iocp = (struct iocblk *)mp->b_rptr;
14583 		switch (iocp->ioc_cmd) {
14584 		case DL_IOC_HDR_INFO:
14585 			ill = (ill_t *)q->q_ptr;
14586 			ill_fastpath_ack(ill, mp);
14587 			return (B_TRUE);
14588 		case SIOCSTUNPARAM:
14589 		case OSIOCSTUNPARAM:
14590 			/* Go through qwriter_ip */
14591 			break;
14592 		case SIOCGTUNPARAM:
14593 		case OSIOCGTUNPARAM:
14594 			ip_rput_other(NULL, q, mp, NULL);
14595 			return (B_TRUE);
14596 		default:
14597 			putnext(q, mp);
14598 			return (B_TRUE);
14599 		}
14600 		/* FALLTHRU */
14601 	case M_ERROR:
14602 	case M_HANGUP:
14603 		/*
14604 		 * Since this is on the ill stream we unconditionally
14605 		 * bump up the refcount
14606 		 */
14607 		ill_refhold(ill);
14608 		qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14609 		return (B_TRUE);
14610 	case M_CTL:
14611 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14612 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14613 		    IPHADA_M_CTL)) {
14614 			/*
14615 			 * It's an IPsec accelerated packet.
14616 			 * Make sure that the ill from which we received the
14617 			 * packet has enabled IPsec hardware acceleration.
14618 			 */
14619 			if (!(ill->ill_capabilities &
14620 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14621 				/* IPsec kstats: bean counter */
14622 				freemsg(mp);
14623 				return (B_TRUE);
14624 			}
14625 
14626 			/*
14627 			 * Make mp point to the mblk following the M_CTL,
14628 			 * then process according to type of mp.
14629 			 * After this processing, first_mp will point to
14630 			 * the data-attributes and mp to the pkt following
14631 			 * the M_CTL.
14632 			 */
14633 			mp = first_mp->b_cont;
14634 			if (mp == NULL) {
14635 				freemsg(first_mp);
14636 				return (B_TRUE);
14637 			}
14638 			/*
14639 			 * A Hardware Accelerated packet can only be M_DATA
14640 			 * ESP or AH packet.
14641 			 */
14642 			if (mp->b_datap->db_type != M_DATA) {
14643 				/* non-M_DATA IPsec accelerated packet */
14644 				IPSECHW_DEBUG(IPSECHW_PKT,
14645 				    ("non-M_DATA IPsec accelerated pkt\n"));
14646 				freemsg(first_mp);
14647 				return (B_TRUE);
14648 			}
14649 			ipha = (ipha_t *)mp->b_rptr;
14650 			if (ipha->ipha_protocol != IPPROTO_AH &&
14651 			    ipha->ipha_protocol != IPPROTO_ESP) {
14652 				IPSECHW_DEBUG(IPSECHW_PKT,
14653 				    ("non-M_DATA IPsec accelerated pkt\n"));
14654 				freemsg(first_mp);
14655 				return (B_TRUE);
14656 			}
14657 			*mpp = mp;
14658 			return (B_FALSE);
14659 		}
14660 		putnext(q, mp);
14661 		return (B_TRUE);
14662 	case M_IOCNAK:
14663 		ip1dbg(("got iocnak "));
14664 		iocp = (struct iocblk *)mp->b_rptr;
14665 		switch (iocp->ioc_cmd) {
14666 		case SIOCSTUNPARAM:
14667 		case OSIOCSTUNPARAM:
14668 			/*
14669 			 * Since this is on the ill stream we unconditionally
14670 			 * bump up the refcount
14671 			 */
14672 			ill_refhold(ill);
14673 			qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14674 			return (B_TRUE);
14675 		case DL_IOC_HDR_INFO:
14676 		case SIOCGTUNPARAM:
14677 		case OSIOCGTUNPARAM:
14678 			ip_rput_other(NULL, q, mp, NULL);
14679 			return (B_TRUE);
14680 		default:
14681 			break;
14682 		}
14683 		/* FALLTHRU */
14684 	default:
14685 		putnext(q, mp);
14686 		return (B_TRUE);
14687 	}
14688 }
14689 
14690 /* Read side put procedure.  Packets coming from the wire arrive here. */
14691 void
14692 ip_rput(queue_t *q, mblk_t *mp)
14693 {
14694 	ill_t	*ill;
14695 	union DL_primitives *dl;
14696 
14697 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14698 
14699 	ill = (ill_t *)q->q_ptr;
14700 
14701 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14702 		/*
14703 		 * If things are opening or closing, only accept high-priority
14704 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
14705 		 * created; on close, things hanging off the ill may have been
14706 		 * freed already.)
14707 		 */
14708 		dl = (union DL_primitives *)mp->b_rptr;
14709 		if (DB_TYPE(mp) != M_PCPROTO ||
14710 		    dl->dl_primitive == DL_UNITDATA_IND) {
14711 			/*
14712 			 * SIOC[GS]TUNPARAM ioctls can come here.
14713 			 */
14714 			inet_freemsg(mp);
14715 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14716 			    "ip_rput_end: q %p (%S)", q, "uninit");
14717 			return;
14718 		}
14719 	}
14720 
14721 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14722 	    "ip_rput_end: q %p (%S)", q, "end");
14723 
14724 	ip_input(ill, NULL, mp, NULL);
14725 }
14726 
14727 static mblk_t *
14728 ip_fix_dbref(ill_t *ill, mblk_t *mp)
14729 {
14730 	mblk_t *mp1;
14731 	boolean_t adjusted = B_FALSE;
14732 	ip_stack_t *ipst = ill->ill_ipst;
14733 
14734 	IP_STAT(ipst, ip_db_ref);
14735 	/*
14736 	 * The IP_RECVSLLA option depends on having the
14737 	 * link layer header. First check that:
14738 	 * a> the underlying device is of type ether,
14739 	 * since this option is currently supported only
14740 	 * over ethernet.
14741 	 * b> there is enough room to copy over the link
14742 	 * layer header.
14743 	 *
14744 	 * Once the checks are done, adjust rptr so that
14745 	 * the link layer header will be copied via
14746 	 * copymsg. Note that, IFT_ETHER may be returned
14747 	 * by some non-ethernet drivers but in this case
14748 	 * the second check will fail.
14749 	 */
14750 	if (ill->ill_type == IFT_ETHER &&
14751 	    (mp->b_rptr - mp->b_datap->db_base) >=
14752 	    sizeof (struct ether_header)) {
14753 		mp->b_rptr -= sizeof (struct ether_header);
14754 		adjusted = B_TRUE;
14755 	}
14756 	mp1 = copymsg(mp);
14757 
14758 	if (mp1 == NULL) {
14759 		mp->b_next = NULL;
14760 		/* clear b_prev - used by ip_mroute_decap */
14761 		mp->b_prev = NULL;
14762 		freemsg(mp);
14763 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14764 		return (NULL);
14765 	}
14766 
14767 	if (adjusted) {
14768 		/*
14769 		 * Copy is done. Restore the pointer in
14770 		 * the _new_ mblk
14771 		 */
14772 		mp1->b_rptr += sizeof (struct ether_header);
14773 	}
14774 
14775 	/* Copy b_prev - used by ip_mroute_decap */
14776 	mp1->b_prev = mp->b_prev;
14777 	mp->b_prev = NULL;
14778 
14779 	/* preserve the hardware checksum flags and data, if present */
14780 	if (DB_CKSUMFLAGS(mp) != 0) {
14781 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
14782 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
14783 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
14784 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
14785 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
14786 	}
14787 
14788 	freemsg(mp);
14789 	return (mp1);
14790 }
14791 
14792 /*
14793  * Direct read side procedure capable of dealing with chains. GLDv3 based
14794  * drivers call this function directly with mblk chains while STREAMS
14795  * read side procedure ip_rput() calls this for single packet with ip_ring
14796  * set to NULL to process one packet at a time.
14797  *
14798  * The ill will always be valid if this function is called directly from
14799  * the driver.
14800  *
14801  * If ip_input() is called from GLDv3:
14802  *
14803  *   - This must be a non-VLAN IP stream.
14804  *   - 'mp' is either an untagged or a special priority-tagged packet.
14805  *   - Any VLAN tag that was in the MAC header has been stripped.
14806  *
14807  * If the IP header in packet is not 32-bit aligned, every message in the
14808  * chain will be aligned before further operations. This is required on SPARC
14809  * platform.
14810  */
14811 /* ARGSUSED */
14812 void
14813 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14814     struct mac_header_info_s *mhip)
14815 {
14816 	ipaddr_t		dst = NULL;
14817 	ipaddr_t		prev_dst;
14818 	ire_t			*ire = NULL;
14819 	ipha_t			*ipha;
14820 	uint_t			pkt_len;
14821 	ssize_t			len;
14822 	uint_t			opt_len;
14823 	int			ll_multicast;
14824 	int			cgtp_flt_pkt;
14825 	queue_t			*q = ill->ill_rq;
14826 	squeue_t		*curr_sqp = NULL;
14827 	mblk_t 			*head = NULL;
14828 	mblk_t			*tail = NULL;
14829 	mblk_t			*first_mp;
14830 	mblk_t 			*mp;
14831 	mblk_t			*dmp;
14832 	int			cnt = 0;
14833 	ip_stack_t		*ipst = ill->ill_ipst;
14834 
14835 	ASSERT(mp_chain != NULL);
14836 	ASSERT(ill != NULL);
14837 
14838 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14839 
14840 #define	rptr	((uchar_t *)ipha)
14841 
14842 	while (mp_chain != NULL) {
14843 		first_mp = mp = mp_chain;
14844 		mp_chain = mp_chain->b_next;
14845 		mp->b_next = NULL;
14846 		ll_multicast = 0;
14847 
14848 		/*
14849 		 * We do ire caching from one iteration to
14850 		 * another. In the event the packet chain contains
14851 		 * all packets from the same dst, this caching saves
14852 		 * an ire_cache_lookup for each of the succeeding
14853 		 * packets in a packet chain.
14854 		 */
14855 		prev_dst = dst;
14856 
14857 		/*
14858 		 * if db_ref > 1 then copymsg and free original. Packet
14859 		 * may be changed and we do not want the other entity
14860 		 * who has a reference to this message to trip over the
14861 		 * changes. This is a blind change because trying to
14862 		 * catch all places that might change the packet is too
14863 		 * difficult.
14864 		 *
14865 		 * This corresponds to the fast path case, where we have
14866 		 * a chain of M_DATA mblks.  We check the db_ref count
14867 		 * of only the 1st data block in the mblk chain. There
14868 		 * doesn't seem to be a reason why a device driver would
14869 		 * send up data with varying db_ref counts in the mblk
14870 		 * chain. In any case the Fast path is a private
14871 		 * interface, and our drivers don't do such a thing.
14872 		 * Given the above assumption, there is no need to walk
14873 		 * down the entire mblk chain (which could have a
14874 		 * potential performance problem)
14875 		 */
14876 
14877 		if (DB_REF(mp) > 1) {
14878 			if ((mp = ip_fix_dbref(ill, mp)) == NULL)
14879 				continue;
14880 		}
14881 
14882 		/*
14883 		 * Check and align the IP header.
14884 		 */
14885 		first_mp = mp;
14886 		if (DB_TYPE(mp) == M_DATA) {
14887 			dmp = mp;
14888 		} else if (DB_TYPE(mp) == M_PROTO &&
14889 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14890 			dmp = mp->b_cont;
14891 		} else {
14892 			dmp = NULL;
14893 		}
14894 		if (dmp != NULL) {
14895 			/*
14896 			 * IP header ptr not aligned?
14897 			 * OR IP header not complete in first mblk
14898 			 */
14899 			if (!OK_32PTR(dmp->b_rptr) ||
14900 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
14901 				if (!ip_check_and_align_header(q, dmp, ipst))
14902 					continue;
14903 			}
14904 		}
14905 
14906 		/*
14907 		 * ip_input fast path
14908 		 */
14909 
14910 		/* mblk type is not M_DATA */
14911 		if (DB_TYPE(mp) != M_DATA) {
14912 			if (ip_rput_process_notdata(q, &first_mp, ill,
14913 			    &ll_multicast, &mp))
14914 				continue;
14915 		}
14916 
14917 		/* Make sure its an M_DATA and that its aligned */
14918 		ASSERT(DB_TYPE(mp) == M_DATA);
14919 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
14920 
14921 		ipha = (ipha_t *)mp->b_rptr;
14922 		len = mp->b_wptr - rptr;
14923 		pkt_len = ntohs(ipha->ipha_length);
14924 
14925 		/*
14926 		 * We must count all incoming packets, even if they end
14927 		 * up being dropped later on.
14928 		 */
14929 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
14930 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
14931 
14932 		/* multiple mblk or too short */
14933 		len -= pkt_len;
14934 		if (len != 0) {
14935 			/*
14936 			 * Make sure we have data length consistent
14937 			 * with the IP header.
14938 			 */
14939 			if (mp->b_cont == NULL) {
14940 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14941 					BUMP_MIB(ill->ill_ip_mib,
14942 					    ipIfStatsInHdrErrors);
14943 					ip2dbg(("ip_input: drop pkt\n"));
14944 					freemsg(mp);
14945 					continue;
14946 				}
14947 				mp->b_wptr = rptr + pkt_len;
14948 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
14949 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14950 					BUMP_MIB(ill->ill_ip_mib,
14951 					    ipIfStatsInHdrErrors);
14952 					ip2dbg(("ip_input: drop pkt\n"));
14953 					freemsg(mp);
14954 					continue;
14955 				}
14956 				(void) adjmsg(mp, -len);
14957 				IP_STAT(ipst, ip_multimblk3);
14958 			}
14959 		}
14960 
14961 		/* Obtain the dst of the current packet */
14962 		dst = ipha->ipha_dst;
14963 
14964 		if (IP_LOOPBACK_ADDR(dst) ||
14965 		    IP_LOOPBACK_ADDR(ipha->ipha_src)) {
14966 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
14967 			cmn_err(CE_CONT, "dst %X src %X\n",
14968 			    dst, ipha->ipha_src);
14969 			freemsg(mp);
14970 			continue;
14971 		}
14972 
14973 		/*
14974 		 * The event for packets being received from a 'physical'
14975 		 * interface is placed after validation of the source and/or
14976 		 * destination address as being local so that packets can be
14977 		 * redirected to loopback addresses using ipnat.
14978 		 */
14979 		DTRACE_PROBE4(ip4__physical__in__start,
14980 		    ill_t *, ill, ill_t *, NULL,
14981 		    ipha_t *, ipha, mblk_t *, first_mp);
14982 
14983 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
14984 		    ipst->ips_ipv4firewall_physical_in,
14985 		    ill, NULL, ipha, first_mp, mp, ipst);
14986 
14987 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
14988 
14989 		if (first_mp == NULL) {
14990 			continue;
14991 		}
14992 		dst = ipha->ipha_dst;
14993 
14994 		/*
14995 		 * Attach any necessary label information to
14996 		 * this packet
14997 		 */
14998 		if (is_system_labeled() &&
14999 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
15000 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
15001 			freemsg(mp);
15002 			continue;
15003 		}
15004 
15005 		/*
15006 		 * Reuse the cached ire only if the ipha_dst of the previous
15007 		 * packet is the same as the current packet AND it is not
15008 		 * INADDR_ANY.
15009 		 */
15010 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15011 		    (ire != NULL)) {
15012 			ire_refrele(ire);
15013 			ire = NULL;
15014 		}
15015 		opt_len = ipha->ipha_version_and_hdr_length -
15016 		    IP_SIMPLE_HDR_VERSION;
15017 
15018 		/*
15019 		 * Check to see if we can take the fastpath.
15020 		 * That is possible if the following conditions are met
15021 		 *	o Tsol disabled
15022 		 *	o CGTP disabled
15023 		 *	o ipp_action_count is 0
15024 		 *	o no options in the packet
15025 		 *	o not a RSVP packet
15026 		 * 	o not a multicast packet
15027 		 *	o ill not in IP_DHCPINIT_IF mode
15028 		 */
15029 		if (!is_system_labeled() &&
15030 		    !ipst->ips_ip_cgtp_filter && ipp_action_count == 0 &&
15031 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
15032 		    !ll_multicast && !CLASSD(dst) && ill->ill_dhcpinit == 0) {
15033 			if (ire == NULL)
15034 				ire = ire_cache_lookup(dst, ALL_ZONES, NULL,
15035 				    ipst);
15036 
15037 			/* incoming packet is for forwarding */
15038 			if (ire == NULL || (ire->ire_type & IRE_CACHE)) {
15039 				ire = ip_fast_forward(ire, dst, ill, mp);
15040 				continue;
15041 			}
15042 			/* incoming packet is for local consumption */
15043 			if (ire->ire_type & IRE_LOCAL)
15044 				goto local;
15045 		}
15046 
15047 		/*
15048 		 * Disable ire caching for anything more complex
15049 		 * than the simple fast path case we checked for above.
15050 		 */
15051 		if (ire != NULL) {
15052 			ire_refrele(ire);
15053 			ire = NULL;
15054 		}
15055 
15056 		/*
15057 		 * Brutal hack for DHCPv4 unicast: RFC2131 allows a DHCP
15058 		 * server to unicast DHCP packets to a DHCP client using the
15059 		 * IP address it is offering to the client.  This can be
15060 		 * disabled through the "broadcast bit", but not all DHCP
15061 		 * servers honor that bit.  Therefore, to interoperate with as
15062 		 * many DHCP servers as possible, the DHCP client allows the
15063 		 * server to unicast, but we treat those packets as broadcast
15064 		 * here.  Note that we don't rewrite the packet itself since
15065 		 * (a) that would mess up the checksums and (b) the DHCP
15066 		 * client conn is bound to INADDR_ANY so ip_fanout_udp() will
15067 		 * hand it the packet regardless.
15068 		 */
15069 		if (ill->ill_dhcpinit != 0 &&
15070 		    IS_SIMPLE_IPH(ipha) && ipha->ipha_protocol == IPPROTO_UDP &&
15071 		    MBLKL(mp) > sizeof (ipha_t) + sizeof (udpha_t)) {
15072 			udpha_t *udpha = (udpha_t *)&ipha[1];
15073 
15074 			if (ntohs(udpha->uha_dst_port) == IPPORT_BOOTPC) {
15075 				DTRACE_PROBE2(ip4__dhcpinit__pkt, ill_t *, ill,
15076 				    mblk_t *, mp);
15077 				dst = INADDR_BROADCAST;
15078 			}
15079 		}
15080 
15081 		/* Full-blown slow path */
15082 		if (opt_len != 0) {
15083 			if (len != 0)
15084 				IP_STAT(ipst, ip_multimblk4);
15085 			else
15086 				IP_STAT(ipst, ip_ipoptions);
15087 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15088 			    &dst, ipst))
15089 				continue;
15090 		}
15091 
15092 		/*
15093 		 * Invoke the CGTP (multirouting) filtering module to process
15094 		 * the incoming packet. Packets identified as duplicates
15095 		 * must be discarded. Filtering is active only if the
15096 		 * the ip_cgtp_filter ndd variable is non-zero.
15097 		 */
15098 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15099 		if (ipst->ips_ip_cgtp_filter &&
15100 		    ipst->ips_ip_cgtp_filter_ops != NULL) {
15101 			netstackid_t stackid;
15102 
15103 			stackid = ipst->ips_netstack->netstack_stackid;
15104 			cgtp_flt_pkt =
15105 			    ipst->ips_ip_cgtp_filter_ops->cfo_filter(stackid,
15106 			    ill->ill_phyint->phyint_ifindex, mp);
15107 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15108 				freemsg(first_mp);
15109 				continue;
15110 			}
15111 		}
15112 
15113 		/*
15114 		 * If rsvpd is running, let RSVP daemon handle its processing
15115 		 * and forwarding of RSVP multicast/unicast packets.
15116 		 * If rsvpd is not running but mrouted is running, RSVP
15117 		 * multicast packets are forwarded as multicast traffic
15118 		 * and RSVP unicast packets are forwarded by unicast router.
15119 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15120 		 * packets are not forwarded, but the unicast packets are
15121 		 * forwarded like unicast traffic.
15122 		 */
15123 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15124 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15125 		    NULL) {
15126 			/* RSVP packet and rsvpd running. Treat as ours */
15127 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15128 			/*
15129 			 * This assumes that we deliver to all streams for
15130 			 * multicast and broadcast packets.
15131 			 * We have to force ll_multicast to 1 to handle the
15132 			 * M_DATA messages passed in from ip_mroute_decap.
15133 			 */
15134 			dst = INADDR_BROADCAST;
15135 			ll_multicast = 1;
15136 		} else if (CLASSD(dst)) {
15137 			/* packet is multicast */
15138 			mp->b_next = NULL;
15139 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15140 			    &ll_multicast, &dst))
15141 				continue;
15142 		}
15143 
15144 		if (ire == NULL) {
15145 			ire = ire_cache_lookup(dst, ALL_ZONES,
15146 			    MBLK_GETLABEL(mp), ipst);
15147 		}
15148 
15149 		if (ire == NULL) {
15150 			/*
15151 			 * No IRE for this destination, so it can't be for us.
15152 			 * Unless we are forwarding, drop the packet.
15153 			 * We have to let source routed packets through
15154 			 * since we don't yet know if they are 'ping -l'
15155 			 * packets i.e. if they will go out over the
15156 			 * same interface as they came in on.
15157 			 */
15158 			ire = ip_rput_noire(q, mp, ll_multicast, dst);
15159 			if (ire == NULL)
15160 				continue;
15161 		}
15162 
15163 		/*
15164 		 * Broadcast IRE may indicate either broadcast or
15165 		 * multicast packet
15166 		 */
15167 		if (ire->ire_type == IRE_BROADCAST) {
15168 			/*
15169 			 * Skip broadcast checks if packet is UDP multicast;
15170 			 * we'd rather not enter ip_rput_process_broadcast()
15171 			 * unless the packet is broadcast for real, since
15172 			 * that routine is a no-op for multicast.
15173 			 */
15174 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15175 			    !CLASSD(ipha->ipha_dst)) {
15176 				ire = ip_rput_process_broadcast(&q, mp,
15177 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15178 				    ll_multicast);
15179 				if (ire == NULL)
15180 					continue;
15181 			}
15182 		} else if (ire->ire_stq != NULL) {
15183 			/* fowarding? */
15184 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15185 			    ll_multicast);
15186 			/* ip_rput_process_forward consumed the packet */
15187 			continue;
15188 		}
15189 
15190 local:
15191 		/*
15192 		 * If the queue in the ire is different to the ingress queue
15193 		 * then we need to check to see if we can accept the packet.
15194 		 * Note that for multicast packets and broadcast packets sent
15195 		 * to a broadcast address which is shared between multiple
15196 		 * interfaces we should not do this since we just got a random
15197 		 * broadcast ire.
15198 		 */
15199 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15200 			if ((ire = ip_check_multihome(&ipha->ipha_dst, ire,
15201 			    ill)) == NULL) {
15202 				/* Drop packet */
15203 				BUMP_MIB(ill->ill_ip_mib,
15204 				    ipIfStatsForwProhibits);
15205 				freemsg(mp);
15206 				continue;
15207 			}
15208 			if (ire->ire_rfq != NULL)
15209 				q = ire->ire_rfq;
15210 		}
15211 
15212 		switch (ipha->ipha_protocol) {
15213 		case IPPROTO_TCP:
15214 			ASSERT(first_mp == mp);
15215 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15216 			    mp, 0, q, ip_ring)) != NULL) {
15217 				if (curr_sqp == NULL) {
15218 					curr_sqp = GET_SQUEUE(mp);
15219 					ASSERT(cnt == 0);
15220 					cnt++;
15221 					head = tail = mp;
15222 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15223 					ASSERT(tail != NULL);
15224 					cnt++;
15225 					tail->b_next = mp;
15226 					tail = mp;
15227 				} else {
15228 					/*
15229 					 * A different squeue. Send the
15230 					 * chain for the previous squeue on
15231 					 * its way. This shouldn't happen
15232 					 * often unless interrupt binding
15233 					 * changes.
15234 					 */
15235 					IP_STAT(ipst, ip_input_multi_squeue);
15236 					squeue_enter_chain(curr_sqp, head,
15237 					    tail, cnt, SQTAG_IP_INPUT);
15238 					curr_sqp = GET_SQUEUE(mp);
15239 					head = mp;
15240 					tail = mp;
15241 					cnt = 1;
15242 				}
15243 			}
15244 			continue;
15245 		case IPPROTO_UDP:
15246 			ASSERT(first_mp == mp);
15247 			ip_udp_input(q, mp, ipha, ire, ill);
15248 			continue;
15249 		case IPPROTO_SCTP:
15250 			ASSERT(first_mp == mp);
15251 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15252 			    q, dst);
15253 			/* ire has been released by ip_sctp_input */
15254 			ire = NULL;
15255 			continue;
15256 		default:
15257 			ip_proto_input(q, first_mp, ipha, ire, ill, B_FALSE);
15258 			continue;
15259 		}
15260 	}
15261 
15262 	if (ire != NULL)
15263 		ire_refrele(ire);
15264 
15265 	if (head != NULL)
15266 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
15267 
15268 	/*
15269 	 * This code is there just to make netperf/ttcp look good.
15270 	 *
15271 	 * Its possible that after being in polling mode (and having cleared
15272 	 * the backlog), squeues have turned the interrupt frequency higher
15273 	 * to improve latency at the expense of more CPU utilization (less
15274 	 * packets per interrupts or more number of interrupts). Workloads
15275 	 * like ttcp/netperf do manage to tickle polling once in a while
15276 	 * but for the remaining time, stay in higher interrupt mode since
15277 	 * their packet arrival rate is pretty uniform and this shows up
15278 	 * as higher CPU utilization. Since people care about CPU utilization
15279 	 * while running netperf/ttcp, turn the interrupt frequency back to
15280 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
15281 	 */
15282 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
15283 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
15284 			ip_ring->rr_poll_state &= ~ILL_POLLING;
15285 			ip_ring->rr_blank(ip_ring->rr_handle,
15286 			    ip_ring->rr_normal_blank_time,
15287 			    ip_ring->rr_normal_pkt_cnt);
15288 		}
15289 		}
15290 
15291 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15292 	    "ip_input_end: q %p (%S)", q, "end");
15293 #undef  rptr
15294 }
15295 
15296 static void
15297 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15298     t_uscalar_t err)
15299 {
15300 	if (dl_err == DL_SYSERR) {
15301 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15302 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15303 		    ill->ill_name, dlpi_prim_str(prim), err);
15304 		return;
15305 	}
15306 
15307 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15308 	    "%s: %s failed: %s\n", ill->ill_name, dlpi_prim_str(prim),
15309 	    dlpi_err_str(dl_err));
15310 }
15311 
15312 /*
15313  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15314  * than DL_UNITDATA_IND messages. If we need to process this message
15315  * exclusively, we call qwriter_ip, in which case we also need to call
15316  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15317  */
15318 void
15319 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15320 {
15321 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15322 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15323 	ill_t		*ill = (ill_t *)q->q_ptr;
15324 	boolean_t	pending;
15325 
15326 	ip1dbg(("ip_rput_dlpi"));
15327 	if (dloa->dl_primitive == DL_ERROR_ACK) {
15328 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
15329 		    "%s (0x%x), unix %u\n", ill->ill_name,
15330 		    dlpi_prim_str(dlea->dl_error_primitive),
15331 		    dlea->dl_error_primitive,
15332 		    dlpi_err_str(dlea->dl_errno),
15333 		    dlea->dl_errno,
15334 		    dlea->dl_unix_errno));
15335 	}
15336 
15337 	/*
15338 	 * If we received an ACK but didn't send a request for it, then it
15339 	 * can't be part of any pending operation; discard up-front.
15340 	 */
15341 	switch (dloa->dl_primitive) {
15342 	case DL_NOTIFY_IND:
15343 		pending = B_TRUE;
15344 		break;
15345 	case DL_ERROR_ACK:
15346 		pending = ill_dlpi_pending(ill, dlea->dl_error_primitive);
15347 		break;
15348 	case DL_OK_ACK:
15349 		pending = ill_dlpi_pending(ill, dloa->dl_correct_primitive);
15350 		break;
15351 	case DL_INFO_ACK:
15352 		pending = ill_dlpi_pending(ill, DL_INFO_REQ);
15353 		break;
15354 	case DL_BIND_ACK:
15355 		pending = ill_dlpi_pending(ill, DL_BIND_REQ);
15356 		break;
15357 	case DL_PHYS_ADDR_ACK:
15358 		pending = ill_dlpi_pending(ill, DL_PHYS_ADDR_REQ);
15359 		break;
15360 	case DL_NOTIFY_ACK:
15361 		pending = ill_dlpi_pending(ill, DL_NOTIFY_REQ);
15362 		break;
15363 	case DL_CONTROL_ACK:
15364 		pending = ill_dlpi_pending(ill, DL_CONTROL_REQ);
15365 		break;
15366 	case DL_CAPABILITY_ACK:
15367 		pending = ill_dlpi_pending(ill, DL_CAPABILITY_REQ);
15368 		break;
15369 	default:
15370 		/* Not a DLPI message we support or were expecting */
15371 		freemsg(mp);
15372 		return;
15373 	}
15374 
15375 	if (!pending) {
15376 		freemsg(mp);
15377 		return;
15378 	}
15379 
15380 	switch (dloa->dl_primitive) {
15381 	case DL_ERROR_ACK:
15382 		if (dlea->dl_error_primitive == DL_UNBIND_REQ) {
15383 			mutex_enter(&ill->ill_lock);
15384 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15385 			cv_signal(&ill->ill_cv);
15386 			mutex_exit(&ill->ill_lock);
15387 		}
15388 		break;
15389 
15390 	case DL_OK_ACK:
15391 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
15392 		    dlpi_prim_str((int)dloa->dl_correct_primitive)));
15393 		switch (dloa->dl_correct_primitive) {
15394 		case DL_UNBIND_REQ:
15395 			mutex_enter(&ill->ill_lock);
15396 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15397 			cv_signal(&ill->ill_cv);
15398 			mutex_exit(&ill->ill_lock);
15399 			break;
15400 
15401 		case DL_ENABMULTI_REQ:
15402 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15403 				ill->ill_dlpi_multicast_state = IDS_OK;
15404 			break;
15405 		}
15406 		break;
15407 	default:
15408 		break;
15409 	}
15410 
15411 	/*
15412 	 * We know the message is one we're waiting for (or DL_NOTIFY_IND),
15413 	 * and we need to become writer to continue to process it. If it's not
15414 	 * a DL_NOTIFY_IND, we assume we're in the middle of an exclusive
15415 	 * operation and pass CUR_OP.  If this isn't true, we'll end up doing
15416 	 * some work as part of the current exclusive operation that actually
15417 	 * is not part of it -- which is wrong, but better than the
15418 	 * alternative of deadlock (if NEW_OP is always used).  Someday, we
15419 	 * should track which DLPI requests have ACKs that we wait on
15420 	 * synchronously so we can know whether to use CUR_OP or NEW_OP.
15421 	 *
15422 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
15423 	 * Since this is on the ill stream we unconditionally bump up the
15424 	 * refcount without doing ILL_CAN_LOOKUP().
15425 	 */
15426 	ill_refhold(ill);
15427 	if (dloa->dl_primitive == DL_NOTIFY_IND)
15428 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
15429 	else
15430 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
15431 }
15432 
15433 /*
15434  * Handling of DLPI messages that require exclusive access to the ipsq.
15435  *
15436  * Need to do ill_pending_mp_release on ioctl completion, which could
15437  * happen here. (along with mi_copy_done)
15438  */
15439 /* ARGSUSED */
15440 static void
15441 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15442 {
15443 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15444 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15445 	int		err = 0;
15446 	ill_t		*ill;
15447 	ipif_t		*ipif = NULL;
15448 	mblk_t		*mp1 = NULL;
15449 	conn_t		*connp = NULL;
15450 	t_uscalar_t	paddrreq;
15451 	mblk_t		*mp_hw;
15452 	boolean_t	success;
15453 	boolean_t	ioctl_aborted = B_FALSE;
15454 	boolean_t	log = B_TRUE;
15455 	hook_nic_event_t	*info;
15456 	ip_stack_t		*ipst;
15457 
15458 	ip1dbg(("ip_rput_dlpi_writer .."));
15459 	ill = (ill_t *)q->q_ptr;
15460 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15461 
15462 	ASSERT(IAM_WRITER_ILL(ill));
15463 
15464 	ipst = ill->ill_ipst;
15465 
15466 	/*
15467 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
15468 	 * both are null or non-null. However we can assert that only
15469 	 * after grabbing the ipsq_lock. So we don't make any assertion
15470 	 * here and in other places in the code.
15471 	 */
15472 	ipif = ipsq->ipsq_pending_ipif;
15473 	/*
15474 	 * The current ioctl could have been aborted by the user and a new
15475 	 * ioctl to bring up another ill could have started. We could still
15476 	 * get a response from the driver later.
15477 	 */
15478 	if (ipif != NULL && ipif->ipif_ill != ill)
15479 		ioctl_aborted = B_TRUE;
15480 
15481 	switch (dloa->dl_primitive) {
15482 	case DL_ERROR_ACK:
15483 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
15484 		    dlpi_prim_str(dlea->dl_error_primitive)));
15485 
15486 		switch (dlea->dl_error_primitive) {
15487 		case DL_PROMISCON_REQ:
15488 		case DL_PROMISCOFF_REQ:
15489 		case DL_DISABMULTI_REQ:
15490 		case DL_UNBIND_REQ:
15491 		case DL_ATTACH_REQ:
15492 		case DL_INFO_REQ:
15493 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15494 			break;
15495 		case DL_NOTIFY_REQ:
15496 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15497 			log = B_FALSE;
15498 			break;
15499 		case DL_PHYS_ADDR_REQ:
15500 			/*
15501 			 * For IPv6 only, there are two additional
15502 			 * phys_addr_req's sent to the driver to get the
15503 			 * IPv6 token and lla. This allows IP to acquire
15504 			 * the hardware address format for a given interface
15505 			 * without having built in knowledge of the hardware
15506 			 * address. ill_phys_addr_pend keeps track of the last
15507 			 * DL_PAR sent so we know which response we are
15508 			 * dealing with. ill_dlpi_done will update
15509 			 * ill_phys_addr_pend when it sends the next req.
15510 			 * We don't complete the IOCTL until all three DL_PARs
15511 			 * have been attempted, so set *_len to 0 and break.
15512 			 */
15513 			paddrreq = ill->ill_phys_addr_pend;
15514 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15515 			if (paddrreq == DL_IPV6_TOKEN) {
15516 				ill->ill_token_length = 0;
15517 				log = B_FALSE;
15518 				break;
15519 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15520 				ill->ill_nd_lla_len = 0;
15521 				log = B_FALSE;
15522 				break;
15523 			}
15524 			/*
15525 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15526 			 * We presumably have an IOCTL hanging out waiting
15527 			 * for completion. Find it and complete the IOCTL
15528 			 * with the error noted.
15529 			 * However, ill_dl_phys was called on an ill queue
15530 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15531 			 * set. But the ioctl is known to be pending on ill_wq.
15532 			 */
15533 			if (!ill->ill_ifname_pending)
15534 				break;
15535 			ill->ill_ifname_pending = 0;
15536 			if (!ioctl_aborted)
15537 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15538 			if (mp1 != NULL) {
15539 				/*
15540 				 * This operation (SIOCSLIFNAME) must have
15541 				 * happened on the ill. Assert there is no conn
15542 				 */
15543 				ASSERT(connp == NULL);
15544 				q = ill->ill_wq;
15545 			}
15546 			break;
15547 		case DL_BIND_REQ:
15548 			ill_dlpi_done(ill, DL_BIND_REQ);
15549 			if (ill->ill_ifname_pending)
15550 				break;
15551 			/*
15552 			 * Something went wrong with the bind.  We presumably
15553 			 * have an IOCTL hanging out waiting for completion.
15554 			 * Find it, take down the interface that was coming
15555 			 * up, and complete the IOCTL with the error noted.
15556 			 */
15557 			if (!ioctl_aborted)
15558 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15559 			if (mp1 != NULL) {
15560 				/*
15561 				 * This operation (SIOCSLIFFLAGS) must have
15562 				 * happened from a conn.
15563 				 */
15564 				ASSERT(connp != NULL);
15565 				q = CONNP_TO_WQ(connp);
15566 				if (ill->ill_move_in_progress) {
15567 					ILL_CLEAR_MOVE(ill);
15568 				}
15569 				(void) ipif_down(ipif, NULL, NULL);
15570 				/* error is set below the switch */
15571 			}
15572 			break;
15573 		case DL_ENABMULTI_REQ:
15574 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
15575 
15576 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15577 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15578 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15579 				ipif_t *ipif;
15580 
15581 				printf("ip: joining multicasts failed (%d)"
15582 				    " on %s - will use link layer "
15583 				    "broadcasts for multicast\n",
15584 				    dlea->dl_errno, ill->ill_name);
15585 
15586 				/*
15587 				 * Set up the multicast mapping alone.
15588 				 * writer, so ok to access ill->ill_ipif
15589 				 * without any lock.
15590 				 */
15591 				ipif = ill->ill_ipif;
15592 				mutex_enter(&ill->ill_phyint->phyint_lock);
15593 				ill->ill_phyint->phyint_flags |=
15594 				    PHYI_MULTI_BCAST;
15595 				mutex_exit(&ill->ill_phyint->phyint_lock);
15596 
15597 				if (!ill->ill_isv6) {
15598 					(void) ipif_arp_setup_multicast(ipif,
15599 					    NULL);
15600 				} else {
15601 					(void) ipif_ndp_setup_multicast(ipif,
15602 					    NULL);
15603 				}
15604 			}
15605 			freemsg(mp);	/* Don't want to pass this up */
15606 			return;
15607 
15608 		case DL_CAPABILITY_REQ:
15609 		case DL_CONTROL_REQ:
15610 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15611 			ill->ill_dlpi_capab_state = IDS_FAILED;
15612 			freemsg(mp);
15613 			return;
15614 		}
15615 		/*
15616 		 * Note the error for IOCTL completion (mp1 is set when
15617 		 * ready to complete ioctl). If ill_ifname_pending_err is
15618 		 * set, an error occured during plumbing (ill_ifname_pending),
15619 		 * so we want to report that error.
15620 		 *
15621 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15622 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15623 		 * expected to get errack'd if the driver doesn't support
15624 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15625 		 * if these error conditions are encountered.
15626 		 */
15627 		if (mp1 != NULL) {
15628 			if (ill->ill_ifname_pending_err != 0)  {
15629 				err = ill->ill_ifname_pending_err;
15630 				ill->ill_ifname_pending_err = 0;
15631 			} else {
15632 				err = dlea->dl_unix_errno ?
15633 				    dlea->dl_unix_errno : ENXIO;
15634 			}
15635 		/*
15636 		 * If we're plumbing an interface and an error hasn't already
15637 		 * been saved, set ill_ifname_pending_err to the error passed
15638 		 * up. Ignore the error if log is B_FALSE (see comment above).
15639 		 */
15640 		} else if (log && ill->ill_ifname_pending &&
15641 		    ill->ill_ifname_pending_err == 0) {
15642 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15643 			    dlea->dl_unix_errno : ENXIO;
15644 		}
15645 
15646 		if (log)
15647 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15648 			    dlea->dl_errno, dlea->dl_unix_errno);
15649 		break;
15650 	case DL_CAPABILITY_ACK:
15651 		/* Call a routine to handle this one. */
15652 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
15653 		ill_capability_ack(ill, mp);
15654 
15655 		/*
15656 		 * If the ack is due to renegotiation, we will need to send
15657 		 * a new CAPABILITY_REQ to start the renegotiation.
15658 		 */
15659 		if (ill->ill_capab_reneg) {
15660 			ill->ill_capab_reneg = B_FALSE;
15661 			ill_capability_probe(ill);
15662 		}
15663 		break;
15664 	case DL_CONTROL_ACK:
15665 		/* We treat all of these as "fire and forget" */
15666 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15667 		break;
15668 	case DL_INFO_ACK:
15669 		/* Call a routine to handle this one. */
15670 		ill_dlpi_done(ill, DL_INFO_REQ);
15671 		ip_ll_subnet_defaults(ill, mp);
15672 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15673 		return;
15674 	case DL_BIND_ACK:
15675 		/*
15676 		 * We should have an IOCTL waiting on this unless
15677 		 * sent by ill_dl_phys, in which case just return
15678 		 */
15679 		ill_dlpi_done(ill, DL_BIND_REQ);
15680 		if (ill->ill_ifname_pending)
15681 			break;
15682 
15683 		if (!ioctl_aborted)
15684 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15685 		if (mp1 == NULL)
15686 			break;
15687 		/*
15688 		 * Because mp1 was added by ill_dl_up(), and it always
15689 		 * passes a valid connp, connp must be valid here.
15690 		 */
15691 		ASSERT(connp != NULL);
15692 		q = CONNP_TO_WQ(connp);
15693 
15694 		/*
15695 		 * We are exclusive. So nothing can change even after
15696 		 * we get the pending mp. If need be we can put it back
15697 		 * and restart, as in calling ipif_arp_up()  below.
15698 		 */
15699 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15700 
15701 		mutex_enter(&ill->ill_lock);
15702 
15703 		ill->ill_dl_up = 1;
15704 
15705 		if ((info = ill->ill_nic_event_info) != NULL) {
15706 			ip2dbg(("ip_rput_dlpi_writer: unexpected nic event %d "
15707 			    "attached for %s\n", info->hne_event,
15708 			    ill->ill_name));
15709 			if (info->hne_data != NULL)
15710 				kmem_free(info->hne_data, info->hne_datalen);
15711 			kmem_free(info, sizeof (hook_nic_event_t));
15712 		}
15713 
15714 		info = kmem_alloc(sizeof (hook_nic_event_t), KM_NOSLEEP);
15715 		if (info != NULL) {
15716 			info->hne_nic = ill->ill_phyint->phyint_hook_ifindex;
15717 			info->hne_lif = 0;
15718 			info->hne_event = NE_UP;
15719 			info->hne_data = NULL;
15720 			info->hne_datalen = 0;
15721 			info->hne_family = ill->ill_isv6 ?
15722 			    ipst->ips_ipv6_net_data : ipst->ips_ipv4_net_data;
15723 		} else
15724 			ip2dbg(("ip_rput_dlpi_writer: could not attach UP nic "
15725 			    "event information for %s (ENOMEM)\n",
15726 			    ill->ill_name));
15727 
15728 		ill->ill_nic_event_info = info;
15729 
15730 		mutex_exit(&ill->ill_lock);
15731 
15732 		/*
15733 		 * Now bring up the resolver; when that is complete, we'll
15734 		 * create IREs.  Note that we intentionally mirror what
15735 		 * ipif_up() would have done, because we got here by way of
15736 		 * ill_dl_up(), which stopped ipif_up()'s processing.
15737 		 */
15738 		if (ill->ill_isv6) {
15739 			/*
15740 			 * v6 interfaces.
15741 			 * Unlike ARP which has to do another bind
15742 			 * and attach, once we get here we are
15743 			 * done with NDP. Except in the case of
15744 			 * ILLF_XRESOLV, in which case we send an
15745 			 * AR_INTERFACE_UP to the external resolver.
15746 			 * If all goes well, the ioctl will complete
15747 			 * in ip_rput(). If there's an error, we
15748 			 * complete it here.
15749 			 */
15750 			if ((err = ipif_ndp_up(ipif)) == 0) {
15751 				if (ill->ill_flags & ILLF_XRESOLV) {
15752 					mutex_enter(&connp->conn_lock);
15753 					mutex_enter(&ill->ill_lock);
15754 					success = ipsq_pending_mp_add(
15755 					    connp, ipif, q, mp1, 0);
15756 					mutex_exit(&ill->ill_lock);
15757 					mutex_exit(&connp->conn_lock);
15758 					if (success) {
15759 						err = ipif_resolver_up(ipif,
15760 						    Res_act_initial);
15761 						if (err == EINPROGRESS) {
15762 							freemsg(mp);
15763 							return;
15764 						}
15765 						ASSERT(err != 0);
15766 						mp1 = ipsq_pending_mp_get(ipsq,
15767 						    &connp);
15768 						ASSERT(mp1 != NULL);
15769 					} else {
15770 						/* conn has started closing */
15771 						err = EINTR;
15772 					}
15773 				} else { /* Non XRESOLV interface */
15774 					(void) ipif_resolver_up(ipif,
15775 					    Res_act_initial);
15776 					err = ipif_up_done_v6(ipif);
15777 				}
15778 			}
15779 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
15780 			/*
15781 			 * ARP and other v4 external resolvers.
15782 			 * Leave the pending mblk intact so that
15783 			 * the ioctl completes in ip_rput().
15784 			 */
15785 			mutex_enter(&connp->conn_lock);
15786 			mutex_enter(&ill->ill_lock);
15787 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
15788 			mutex_exit(&ill->ill_lock);
15789 			mutex_exit(&connp->conn_lock);
15790 			if (success) {
15791 				err = ipif_resolver_up(ipif, Res_act_initial);
15792 				if (err == EINPROGRESS) {
15793 					freemsg(mp);
15794 					return;
15795 				}
15796 				ASSERT(err != 0);
15797 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15798 			} else {
15799 				/* The conn has started closing */
15800 				err = EINTR;
15801 			}
15802 		} else {
15803 			/*
15804 			 * This one is complete. Reply to pending ioctl.
15805 			 */
15806 			(void) ipif_resolver_up(ipif, Res_act_initial);
15807 			err = ipif_up_done(ipif);
15808 		}
15809 
15810 		if ((err == 0) && (ill->ill_up_ipifs)) {
15811 			err = ill_up_ipifs(ill, q, mp1);
15812 			if (err == EINPROGRESS) {
15813 				freemsg(mp);
15814 				return;
15815 			}
15816 		}
15817 
15818 		if (ill->ill_up_ipifs) {
15819 			ill_group_cleanup(ill);
15820 		}
15821 
15822 		break;
15823 	case DL_NOTIFY_IND: {
15824 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
15825 		ire_t *ire;
15826 		boolean_t need_ire_walk_v4 = B_FALSE;
15827 		boolean_t need_ire_walk_v6 = B_FALSE;
15828 
15829 		switch (notify->dl_notification) {
15830 		case DL_NOTE_PHYS_ADDR:
15831 			err = ill_set_phys_addr(ill, mp);
15832 			break;
15833 
15834 		case DL_NOTE_FASTPATH_FLUSH:
15835 			ill_fastpath_flush(ill);
15836 			break;
15837 
15838 		case DL_NOTE_SDU_SIZE:
15839 			/*
15840 			 * Change the MTU size of the interface, of all
15841 			 * attached ipif's, and of all relevant ire's.  The
15842 			 * new value's a uint32_t at notify->dl_data.
15843 			 * Mtu change Vs. new ire creation - protocol below.
15844 			 *
15845 			 * a Mark the ipif as IPIF_CHANGING.
15846 			 * b Set the new mtu in the ipif.
15847 			 * c Change the ire_max_frag on all affected ires
15848 			 * d Unmark the IPIF_CHANGING
15849 			 *
15850 			 * To see how the protocol works, assume an interface
15851 			 * route is also being added simultaneously by
15852 			 * ip_rt_add and let 'ipif' be the ipif referenced by
15853 			 * the ire. If the ire is created before step a,
15854 			 * it will be cleaned up by step c. If the ire is
15855 			 * created after step d, it will see the new value of
15856 			 * ipif_mtu. Any attempt to create the ire between
15857 			 * steps a to d will fail because of the IPIF_CHANGING
15858 			 * flag. Note that ire_create() is passed a pointer to
15859 			 * the ipif_mtu, and not the value. During ire_add
15860 			 * under the bucket lock, the ire_max_frag of the
15861 			 * new ire being created is set from the ipif/ire from
15862 			 * which it is being derived.
15863 			 */
15864 			mutex_enter(&ill->ill_lock);
15865 			ill->ill_max_frag = (uint_t)notify->dl_data;
15866 
15867 			/*
15868 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
15869 			 * leave it alone
15870 			 */
15871 			if (ill->ill_mtu_userspecified) {
15872 				mutex_exit(&ill->ill_lock);
15873 				break;
15874 			}
15875 			ill->ill_max_mtu = ill->ill_max_frag;
15876 			if (ill->ill_isv6) {
15877 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
15878 					ill->ill_max_mtu = IPV6_MIN_MTU;
15879 			} else {
15880 				if (ill->ill_max_mtu < IP_MIN_MTU)
15881 					ill->ill_max_mtu = IP_MIN_MTU;
15882 			}
15883 			for (ipif = ill->ill_ipif; ipif != NULL;
15884 			    ipif = ipif->ipif_next) {
15885 				/*
15886 				 * Don't override the mtu if the user
15887 				 * has explicitly set it.
15888 				 */
15889 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
15890 					continue;
15891 				ipif->ipif_mtu = (uint_t)notify->dl_data;
15892 				if (ipif->ipif_isv6)
15893 					ire = ipif_to_ire_v6(ipif);
15894 				else
15895 					ire = ipif_to_ire(ipif);
15896 				if (ire != NULL) {
15897 					ire->ire_max_frag = ipif->ipif_mtu;
15898 					ire_refrele(ire);
15899 				}
15900 				if (ipif->ipif_flags & IPIF_UP) {
15901 					if (ill->ill_isv6)
15902 						need_ire_walk_v6 = B_TRUE;
15903 					else
15904 						need_ire_walk_v4 = B_TRUE;
15905 				}
15906 			}
15907 			mutex_exit(&ill->ill_lock);
15908 			if (need_ire_walk_v4)
15909 				ire_walk_v4(ill_mtu_change, (char *)ill,
15910 				    ALL_ZONES, ipst);
15911 			if (need_ire_walk_v6)
15912 				ire_walk_v6(ill_mtu_change, (char *)ill,
15913 				    ALL_ZONES, ipst);
15914 			break;
15915 		case DL_NOTE_LINK_UP:
15916 		case DL_NOTE_LINK_DOWN: {
15917 			/*
15918 			 * We are writer. ill / phyint / ipsq assocs stable.
15919 			 * The RUNNING flag reflects the state of the link.
15920 			 */
15921 			phyint_t *phyint = ill->ill_phyint;
15922 			uint64_t new_phyint_flags;
15923 			boolean_t changed = B_FALSE;
15924 			boolean_t went_up;
15925 
15926 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
15927 			mutex_enter(&phyint->phyint_lock);
15928 			new_phyint_flags = went_up ?
15929 			    phyint->phyint_flags | PHYI_RUNNING :
15930 			    phyint->phyint_flags & ~PHYI_RUNNING;
15931 			if (new_phyint_flags != phyint->phyint_flags) {
15932 				phyint->phyint_flags = new_phyint_flags;
15933 				changed = B_TRUE;
15934 			}
15935 			mutex_exit(&phyint->phyint_lock);
15936 			/*
15937 			 * ill_restart_dad handles the DAD restart and routing
15938 			 * socket notification logic.
15939 			 */
15940 			if (changed) {
15941 				ill_restart_dad(phyint->phyint_illv4, went_up);
15942 				ill_restart_dad(phyint->phyint_illv6, went_up);
15943 			}
15944 			break;
15945 		}
15946 		case DL_NOTE_PROMISC_ON_PHYS:
15947 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15948 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
15949 			mutex_enter(&ill->ill_lock);
15950 			ill->ill_promisc_on_phys = B_TRUE;
15951 			mutex_exit(&ill->ill_lock);
15952 			break;
15953 		case DL_NOTE_PROMISC_OFF_PHYS:
15954 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15955 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
15956 			mutex_enter(&ill->ill_lock);
15957 			ill->ill_promisc_on_phys = B_FALSE;
15958 			mutex_exit(&ill->ill_lock);
15959 			break;
15960 		case DL_NOTE_CAPAB_RENEG:
15961 			/*
15962 			 * Something changed on the driver side.
15963 			 * It wants us to renegotiate the capabilities
15964 			 * on this ill. One possible cause is the aggregation
15965 			 * interface under us where a port got added or
15966 			 * went away.
15967 			 *
15968 			 * If the capability negotiation is already done
15969 			 * or is in progress, reset the capabilities and
15970 			 * mark the ill's ill_capab_reneg to be B_TRUE,
15971 			 * so that when the ack comes back, we can start
15972 			 * the renegotiation process.
15973 			 *
15974 			 * Note that if ill_capab_reneg is already B_TRUE
15975 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
15976 			 * the capability resetting request has been sent
15977 			 * and the renegotiation has not been started yet;
15978 			 * nothing needs to be done in this case.
15979 			 */
15980 			if (ill->ill_dlpi_capab_state != IDS_UNKNOWN) {
15981 				ill_capability_reset(ill);
15982 				ill->ill_capab_reneg = B_TRUE;
15983 			}
15984 			break;
15985 		default:
15986 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
15987 			    "type 0x%x for DL_NOTIFY_IND\n",
15988 			    notify->dl_notification));
15989 			break;
15990 		}
15991 
15992 		/*
15993 		 * As this is an asynchronous operation, we
15994 		 * should not call ill_dlpi_done
15995 		 */
15996 		break;
15997 	}
15998 	case DL_NOTIFY_ACK: {
15999 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
16000 
16001 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
16002 			ill->ill_note_link = 1;
16003 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
16004 		break;
16005 	}
16006 	case DL_PHYS_ADDR_ACK: {
16007 		/*
16008 		 * As part of plumbing the interface via SIOCSLIFNAME,
16009 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
16010 		 * whose answers we receive here.  As each answer is received,
16011 		 * we call ill_dlpi_done() to dispatch the next request as
16012 		 * we're processing the current one.  Once all answers have
16013 		 * been received, we use ipsq_pending_mp_get() to dequeue the
16014 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
16015 		 * is invoked from an ill queue, conn_oper_pending_ill is not
16016 		 * available, but we know the ioctl is pending on ill_wq.)
16017 		 */
16018 		uint_t paddrlen, paddroff;
16019 
16020 		paddrreq = ill->ill_phys_addr_pend;
16021 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
16022 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
16023 
16024 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
16025 		if (paddrreq == DL_IPV6_TOKEN) {
16026 			/*
16027 			 * bcopy to low-order bits of ill_token
16028 			 *
16029 			 * XXX Temporary hack - currently, all known tokens
16030 			 * are 64 bits, so I'll cheat for the moment.
16031 			 */
16032 			bcopy(mp->b_rptr + paddroff,
16033 			    &ill->ill_token.s6_addr32[2], paddrlen);
16034 			ill->ill_token_length = paddrlen;
16035 			break;
16036 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16037 			ASSERT(ill->ill_nd_lla_mp == NULL);
16038 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
16039 			mp = NULL;
16040 			break;
16041 		}
16042 
16043 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
16044 		ASSERT(ill->ill_phys_addr_mp == NULL);
16045 		if (!ill->ill_ifname_pending)
16046 			break;
16047 		ill->ill_ifname_pending = 0;
16048 		if (!ioctl_aborted)
16049 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16050 		if (mp1 != NULL) {
16051 			ASSERT(connp == NULL);
16052 			q = ill->ill_wq;
16053 		}
16054 		/*
16055 		 * If any error acks received during the plumbing sequence,
16056 		 * ill_ifname_pending_err will be set. Break out and send up
16057 		 * the error to the pending ioctl.
16058 		 */
16059 		if (ill->ill_ifname_pending_err != 0) {
16060 			err = ill->ill_ifname_pending_err;
16061 			ill->ill_ifname_pending_err = 0;
16062 			break;
16063 		}
16064 
16065 		ill->ill_phys_addr_mp = mp;
16066 		ill->ill_phys_addr = mp->b_rptr + paddroff;
16067 		mp = NULL;
16068 
16069 		/*
16070 		 * If paddrlen is zero, the DLPI provider doesn't support
16071 		 * physical addresses.  The other two tests were historical
16072 		 * workarounds for bugs in our former PPP implementation, but
16073 		 * now other things have grown dependencies on them -- e.g.,
16074 		 * the tun module specifies a dl_addr_length of zero in its
16075 		 * DL_BIND_ACK, but then specifies an incorrect value in its
16076 		 * DL_PHYS_ADDR_ACK.  These bogus checks need to be removed,
16077 		 * but only after careful testing ensures that all dependent
16078 		 * broken DLPI providers have been fixed.
16079 		 */
16080 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0 ||
16081 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
16082 			ill->ill_phys_addr = NULL;
16083 		} else if (paddrlen != ill->ill_phys_addr_length) {
16084 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16085 			    paddrlen, ill->ill_phys_addr_length));
16086 			err = EINVAL;
16087 			break;
16088 		}
16089 
16090 		if (ill->ill_nd_lla_mp == NULL) {
16091 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16092 				err = ENOMEM;
16093 				break;
16094 			}
16095 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16096 		}
16097 
16098 		/*
16099 		 * Set the interface token.  If the zeroth interface address
16100 		 * is unspecified, then set it to the link local address.
16101 		 */
16102 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
16103 			(void) ill_setdefaulttoken(ill);
16104 
16105 		ASSERT(ill->ill_ipif->ipif_id == 0);
16106 		if (ipif != NULL &&
16107 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr)) {
16108 			(void) ipif_setlinklocal(ipif);
16109 		}
16110 		break;
16111 	}
16112 	case DL_OK_ACK:
16113 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16114 		    dlpi_prim_str((int)dloa->dl_correct_primitive),
16115 		    dloa->dl_correct_primitive));
16116 		switch (dloa->dl_correct_primitive) {
16117 		case DL_PROMISCON_REQ:
16118 		case DL_PROMISCOFF_REQ:
16119 		case DL_ENABMULTI_REQ:
16120 		case DL_DISABMULTI_REQ:
16121 		case DL_UNBIND_REQ:
16122 		case DL_ATTACH_REQ:
16123 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16124 			break;
16125 		}
16126 		break;
16127 	default:
16128 		break;
16129 	}
16130 
16131 	freemsg(mp);
16132 	if (mp1 != NULL) {
16133 		/*
16134 		 * The operation must complete without EINPROGRESS
16135 		 * since ipsq_pending_mp_get() has removed the mblk
16136 		 * from ipsq_pending_mp.  Otherwise, the operation
16137 		 * will be stuck forever in the ipsq.
16138 		 */
16139 		ASSERT(err != EINPROGRESS);
16140 
16141 		switch (ipsq->ipsq_current_ioctl) {
16142 		case 0:
16143 			ipsq_current_finish(ipsq);
16144 			break;
16145 
16146 		case SIOCLIFADDIF:
16147 		case SIOCSLIFNAME:
16148 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16149 			break;
16150 
16151 		default:
16152 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16153 			break;
16154 		}
16155 	}
16156 }
16157 
16158 /*
16159  * ip_rput_other is called by ip_rput to handle messages modifying the global
16160  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16161  */
16162 /* ARGSUSED */
16163 void
16164 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16165 {
16166 	ill_t		*ill;
16167 	struct iocblk	*iocp;
16168 	mblk_t		*mp1;
16169 	conn_t		*connp = NULL;
16170 
16171 	ip1dbg(("ip_rput_other "));
16172 	ill = (ill_t *)q->q_ptr;
16173 	/*
16174 	 * This routine is not a writer in the case of SIOCGTUNPARAM
16175 	 * in which case ipsq is NULL.
16176 	 */
16177 	if (ipsq != NULL) {
16178 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16179 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
16180 	}
16181 
16182 	switch (mp->b_datap->db_type) {
16183 	case M_ERROR:
16184 	case M_HANGUP:
16185 		/*
16186 		 * The device has a problem.  We force the ILL down.  It can
16187 		 * be brought up again manually using SIOCSIFFLAGS (via
16188 		 * ifconfig or equivalent).
16189 		 */
16190 		ASSERT(ipsq != NULL);
16191 		if (mp->b_rptr < mp->b_wptr)
16192 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16193 		if (ill->ill_error == 0)
16194 			ill->ill_error = ENXIO;
16195 		if (!ill_down_start(q, mp))
16196 			return;
16197 		ipif_all_down_tail(ipsq, q, mp, NULL);
16198 		break;
16199 	case M_IOCACK:
16200 		iocp = (struct iocblk *)mp->b_rptr;
16201 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16202 		switch (iocp->ioc_cmd) {
16203 		case SIOCSTUNPARAM:
16204 		case OSIOCSTUNPARAM:
16205 			ASSERT(ipsq != NULL);
16206 			/*
16207 			 * Finish socket ioctl passed through to tun.
16208 			 * We should have an IOCTL waiting on this.
16209 			 */
16210 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16211 			if (ill->ill_isv6) {
16212 				struct iftun_req *ta;
16213 
16214 				/*
16215 				 * if a source or destination is
16216 				 * being set, try and set the link
16217 				 * local address for the tunnel
16218 				 */
16219 				ta = (struct iftun_req *)mp->b_cont->
16220 				    b_cont->b_rptr;
16221 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16222 					ipif_set_tun_llink(ill, ta);
16223 				}
16224 
16225 			}
16226 			if (mp1 != NULL) {
16227 				/*
16228 				 * Now copy back the b_next/b_prev used by
16229 				 * mi code for the mi_copy* functions.
16230 				 * See ip_sioctl_tunparam() for the reason.
16231 				 * Also protect against missing b_cont.
16232 				 */
16233 				if (mp->b_cont != NULL) {
16234 					mp->b_cont->b_next =
16235 					    mp1->b_cont->b_next;
16236 					mp->b_cont->b_prev =
16237 					    mp1->b_cont->b_prev;
16238 				}
16239 				inet_freemsg(mp1);
16240 				ASSERT(connp != NULL);
16241 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16242 				    iocp->ioc_error, NO_COPYOUT, ipsq);
16243 			} else {
16244 				ASSERT(connp == NULL);
16245 				putnext(q, mp);
16246 			}
16247 			break;
16248 		case SIOCGTUNPARAM:
16249 		case OSIOCGTUNPARAM:
16250 			/*
16251 			 * This is really M_IOCDATA from the tunnel driver.
16252 			 * convert back and complete the ioctl.
16253 			 * We should have an IOCTL waiting on this.
16254 			 */
16255 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16256 			if (mp1) {
16257 				/*
16258 				 * Now copy back the b_next/b_prev used by
16259 				 * mi code for the mi_copy* functions.
16260 				 * See ip_sioctl_tunparam() for the reason.
16261 				 * Also protect against missing b_cont.
16262 				 */
16263 				if (mp->b_cont != NULL) {
16264 					mp->b_cont->b_next =
16265 					    mp1->b_cont->b_next;
16266 					mp->b_cont->b_prev =
16267 					    mp1->b_cont->b_prev;
16268 				}
16269 				inet_freemsg(mp1);
16270 				if (iocp->ioc_error == 0)
16271 					mp->b_datap->db_type = M_IOCDATA;
16272 				ASSERT(connp != NULL);
16273 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16274 				    iocp->ioc_error, COPYOUT, NULL);
16275 			} else {
16276 				ASSERT(connp == NULL);
16277 				putnext(q, mp);
16278 			}
16279 			break;
16280 		default:
16281 			break;
16282 		}
16283 		break;
16284 	case M_IOCNAK:
16285 		iocp = (struct iocblk *)mp->b_rptr;
16286 
16287 		switch (iocp->ioc_cmd) {
16288 		int mode;
16289 
16290 		case DL_IOC_HDR_INFO:
16291 			/*
16292 			 * If this was the first attempt turn of the
16293 			 * fastpath probing.
16294 			 */
16295 			mutex_enter(&ill->ill_lock);
16296 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16297 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16298 				mutex_exit(&ill->ill_lock);
16299 				ill_fastpath_nack(ill);
16300 				ip1dbg(("ip_rput: DLPI fastpath off on "
16301 				    "interface %s\n",
16302 				    ill->ill_name));
16303 			} else {
16304 				mutex_exit(&ill->ill_lock);
16305 			}
16306 			freemsg(mp);
16307 			break;
16308 		case SIOCSTUNPARAM:
16309 		case OSIOCSTUNPARAM:
16310 			ASSERT(ipsq != NULL);
16311 			/*
16312 			 * Finish socket ioctl passed through to tun
16313 			 * We should have an IOCTL waiting on this.
16314 			 */
16315 			/* FALLTHRU */
16316 		case SIOCGTUNPARAM:
16317 		case OSIOCGTUNPARAM:
16318 			/*
16319 			 * This is really M_IOCDATA from the tunnel driver.
16320 			 * convert back and complete the ioctl.
16321 			 * We should have an IOCTL waiting on this.
16322 			 */
16323 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16324 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16325 				mp1 = ill_pending_mp_get(ill, &connp,
16326 				    iocp->ioc_id);
16327 				mode = COPYOUT;
16328 				ipsq = NULL;
16329 			} else {
16330 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16331 				mode = NO_COPYOUT;
16332 			}
16333 			if (mp1 != NULL) {
16334 				/*
16335 				 * Now copy back the b_next/b_prev used by
16336 				 * mi code for the mi_copy* functions.
16337 				 * See ip_sioctl_tunparam() for the reason.
16338 				 * Also protect against missing b_cont.
16339 				 */
16340 				if (mp->b_cont != NULL) {
16341 					mp->b_cont->b_next =
16342 					    mp1->b_cont->b_next;
16343 					mp->b_cont->b_prev =
16344 					    mp1->b_cont->b_prev;
16345 				}
16346 				inet_freemsg(mp1);
16347 				if (iocp->ioc_error == 0)
16348 					iocp->ioc_error = EINVAL;
16349 				ASSERT(connp != NULL);
16350 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16351 				    iocp->ioc_error, mode, ipsq);
16352 			} else {
16353 				ASSERT(connp == NULL);
16354 				putnext(q, mp);
16355 			}
16356 			break;
16357 		default:
16358 			break;
16359 		}
16360 	default:
16361 		break;
16362 	}
16363 }
16364 
16365 /*
16366  * NOTE : This function does not ire_refrele the ire argument passed in.
16367  *
16368  * IPQoS notes
16369  * IP policy is invoked twice for a forwarded packet, once on the read side
16370  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16371  * enabled. An additional parameter, in_ill, has been added for this purpose.
16372  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16373  * because ip_mroute drops this information.
16374  *
16375  */
16376 void
16377 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16378 {
16379 	uint32_t	old_pkt_len;
16380 	uint32_t	pkt_len;
16381 	queue_t	*q;
16382 	uint32_t	sum;
16383 #define	rptr	((uchar_t *)ipha)
16384 	uint32_t	max_frag;
16385 	uint32_t	ill_index;
16386 	ill_t		*out_ill;
16387 	mib2_ipIfStatsEntry_t *mibptr;
16388 	ip_stack_t	*ipst = ((ill_t *)(ire->ire_stq->q_ptr))->ill_ipst;
16389 
16390 	/* Get the ill_index of the incoming ILL */
16391 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16392 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16393 
16394 	/* Initiate Read side IPPF processing */
16395 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16396 		ip_process(IPP_FWD_IN, &mp, ill_index);
16397 		if (mp == NULL) {
16398 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16399 			    "during IPPF processing\n"));
16400 			return;
16401 		}
16402 	}
16403 
16404 	/* Adjust the checksum to reflect the ttl decrement. */
16405 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16406 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16407 
16408 	if (ipha->ipha_ttl-- <= 1) {
16409 		if (ip_csum_hdr(ipha)) {
16410 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16411 			goto drop_pkt;
16412 		}
16413 		/*
16414 		 * Note: ire_stq this will be NULL for multicast
16415 		 * datagrams using the long path through arp (the IRE
16416 		 * is not an IRE_CACHE). This should not cause
16417 		 * problems since we don't generate ICMP errors for
16418 		 * multicast packets.
16419 		 */
16420 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16421 		q = ire->ire_stq;
16422 		if (q != NULL) {
16423 			/* Sent by forwarding path, and router is global zone */
16424 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16425 			    GLOBAL_ZONEID, ipst);
16426 		} else
16427 			freemsg(mp);
16428 		return;
16429 	}
16430 
16431 	/*
16432 	 * Don't forward if the interface is down
16433 	 */
16434 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16435 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16436 		ip2dbg(("ip_rput_forward:interface is down\n"));
16437 		goto drop_pkt;
16438 	}
16439 
16440 	/* Get the ill_index of the outgoing ILL */
16441 	out_ill = ire_to_ill(ire);
16442 	ill_index = out_ill->ill_phyint->phyint_ifindex;
16443 
16444 	DTRACE_PROBE4(ip4__forwarding__start,
16445 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16446 
16447 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16448 	    ipst->ips_ipv4firewall_forwarding,
16449 	    in_ill, out_ill, ipha, mp, mp, ipst);
16450 
16451 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16452 
16453 	if (mp == NULL)
16454 		return;
16455 	old_pkt_len = pkt_len = ntohs(ipha->ipha_length);
16456 
16457 	if (is_system_labeled()) {
16458 		mblk_t *mp1;
16459 
16460 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16461 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16462 			goto drop_pkt;
16463 		}
16464 		/* Size may have changed */
16465 		mp = mp1;
16466 		ipha = (ipha_t *)mp->b_rptr;
16467 		pkt_len = ntohs(ipha->ipha_length);
16468 	}
16469 
16470 	/* Check if there are options to update */
16471 	if (!IS_SIMPLE_IPH(ipha)) {
16472 		if (ip_csum_hdr(ipha)) {
16473 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16474 			goto drop_pkt;
16475 		}
16476 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16477 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16478 			return;
16479 		}
16480 
16481 		ipha->ipha_hdr_checksum = 0;
16482 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16483 	}
16484 	max_frag = ire->ire_max_frag;
16485 	if (pkt_len > max_frag) {
16486 		/*
16487 		 * It needs fragging on its way out.  We haven't
16488 		 * verified the header checksum yet.  Since we
16489 		 * are going to put a surely good checksum in the
16490 		 * outgoing header, we have to make sure that it
16491 		 * was good coming in.
16492 		 */
16493 		if (ip_csum_hdr(ipha)) {
16494 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16495 			goto drop_pkt;
16496 		}
16497 		/* Initiate Write side IPPF processing */
16498 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16499 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16500 			if (mp == NULL) {
16501 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16502 				    " during IPPF processing\n"));
16503 				return;
16504 			}
16505 		}
16506 		/*
16507 		 * Handle labeled packet resizing.
16508 		 *
16509 		 * If we have added a label, inform ip_wput_frag() of its
16510 		 * effect on the MTU for ICMP messages.
16511 		 */
16512 		if (pkt_len > old_pkt_len) {
16513 			uint32_t secopt_size;
16514 
16515 			secopt_size = pkt_len - old_pkt_len;
16516 			if (secopt_size < max_frag)
16517 				max_frag -= secopt_size;
16518 		}
16519 
16520 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID, ipst);
16521 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16522 		return;
16523 	}
16524 
16525 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16526 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16527 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16528 	    ipst->ips_ipv4firewall_physical_out,
16529 	    NULL, out_ill, ipha, mp, mp, ipst);
16530 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16531 	if (mp == NULL)
16532 		return;
16533 
16534 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16535 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16536 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE);
16537 	/* ip_xmit_v4 always consumes the packet */
16538 	return;
16539 
16540 drop_pkt:;
16541 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16542 	freemsg(mp);
16543 #undef	rptr
16544 }
16545 
16546 void
16547 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16548 {
16549 	ire_t	*ire;
16550 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
16551 
16552 	ASSERT(!ipif->ipif_isv6);
16553 	/*
16554 	 * Find an IRE which matches the destination and the outgoing
16555 	 * queue in the cache table. All we need is an IRE_CACHE which
16556 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
16557 	 * then it is enough to have some IRE_CACHE in the group.
16558 	 */
16559 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16560 		dst = ipif->ipif_pp_dst_addr;
16561 
16562 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
16563 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR, ipst);
16564 	if (ire == NULL) {
16565 		/*
16566 		 * Mark this packet to make it be delivered to
16567 		 * ip_rput_forward after the new ire has been
16568 		 * created.
16569 		 */
16570 		mp->b_prev = NULL;
16571 		mp->b_next = mp;
16572 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16573 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
16574 	} else {
16575 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16576 		IRE_REFRELE(ire);
16577 	}
16578 }
16579 
16580 /* Update any source route, record route or timestamp options */
16581 static int
16582 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
16583 {
16584 	ipoptp_t	opts;
16585 	uchar_t		*opt;
16586 	uint8_t		optval;
16587 	uint8_t		optlen;
16588 	ipaddr_t	dst;
16589 	uint32_t	ts;
16590 	ire_t		*dst_ire = NULL;
16591 	ire_t		*tmp_ire = NULL;
16592 	timestruc_t	now;
16593 
16594 	ip2dbg(("ip_rput_forward_options\n"));
16595 	dst = ipha->ipha_dst;
16596 	for (optval = ipoptp_first(&opts, ipha);
16597 	    optval != IPOPT_EOL;
16598 	    optval = ipoptp_next(&opts)) {
16599 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16600 		opt = opts.ipoptp_cur;
16601 		optlen = opts.ipoptp_len;
16602 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16603 		    optval, opts.ipoptp_len));
16604 		switch (optval) {
16605 			uint32_t off;
16606 		case IPOPT_SSRR:
16607 		case IPOPT_LSRR:
16608 			/* Check if adminstratively disabled */
16609 			if (!ipst->ips_ip_forward_src_routed) {
16610 				if (ire->ire_stq != NULL) {
16611 					/*
16612 					 * Sent by forwarding path, and router
16613 					 * is global zone
16614 					 */
16615 					icmp_unreachable(ire->ire_stq, mp,
16616 					    ICMP_SOURCE_ROUTE_FAILED,
16617 					    GLOBAL_ZONEID, ipst);
16618 				} else {
16619 					ip0dbg(("ip_rput_forward_options: "
16620 					    "unable to send unreach\n"));
16621 					freemsg(mp);
16622 				}
16623 				return (-1);
16624 			}
16625 
16626 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16627 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16628 			if (dst_ire == NULL) {
16629 				/*
16630 				 * Must be partial since ip_rput_options
16631 				 * checked for strict.
16632 				 */
16633 				break;
16634 			}
16635 			off = opt[IPOPT_OFFSET];
16636 			off--;
16637 		redo_srr:
16638 			if (optlen < IP_ADDR_LEN ||
16639 			    off > optlen - IP_ADDR_LEN) {
16640 				/* End of source route */
16641 				ip1dbg((
16642 				    "ip_rput_forward_options: end of SR\n"));
16643 				ire_refrele(dst_ire);
16644 				break;
16645 			}
16646 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16647 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16648 			    IP_ADDR_LEN);
16649 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16650 			    ntohl(dst)));
16651 
16652 			/*
16653 			 * Check if our address is present more than
16654 			 * once as consecutive hops in source route.
16655 			 */
16656 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16657 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16658 			if (tmp_ire != NULL) {
16659 				ire_refrele(tmp_ire);
16660 				off += IP_ADDR_LEN;
16661 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16662 				goto redo_srr;
16663 			}
16664 			ipha->ipha_dst = dst;
16665 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16666 			ire_refrele(dst_ire);
16667 			break;
16668 		case IPOPT_RR:
16669 			off = opt[IPOPT_OFFSET];
16670 			off--;
16671 			if (optlen < IP_ADDR_LEN ||
16672 			    off > optlen - IP_ADDR_LEN) {
16673 				/* No more room - ignore */
16674 				ip1dbg((
16675 				    "ip_rput_forward_options: end of RR\n"));
16676 				break;
16677 			}
16678 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16679 			    IP_ADDR_LEN);
16680 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16681 			break;
16682 		case IPOPT_TS:
16683 			/* Insert timestamp if there is room */
16684 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16685 			case IPOPT_TS_TSONLY:
16686 				off = IPOPT_TS_TIMELEN;
16687 				break;
16688 			case IPOPT_TS_PRESPEC:
16689 			case IPOPT_TS_PRESPEC_RFC791:
16690 				/* Verify that the address matched */
16691 				off = opt[IPOPT_OFFSET] - 1;
16692 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16693 				dst_ire = ire_ctable_lookup(dst, 0,
16694 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16695 				    MATCH_IRE_TYPE, ipst);
16696 				if (dst_ire == NULL) {
16697 					/* Not for us */
16698 					break;
16699 				}
16700 				ire_refrele(dst_ire);
16701 				/* FALLTHRU */
16702 			case IPOPT_TS_TSANDADDR:
16703 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16704 				break;
16705 			default:
16706 				/*
16707 				 * ip_*put_options should have already
16708 				 * dropped this packet.
16709 				 */
16710 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16711 				    "unknown IT - bug in ip_rput_options?\n");
16712 				return (0);	/* Keep "lint" happy */
16713 			}
16714 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16715 				/* Increase overflow counter */
16716 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16717 				opt[IPOPT_POS_OV_FLG] =
16718 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16719 				    (off << 4));
16720 				break;
16721 			}
16722 			off = opt[IPOPT_OFFSET] - 1;
16723 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16724 			case IPOPT_TS_PRESPEC:
16725 			case IPOPT_TS_PRESPEC_RFC791:
16726 			case IPOPT_TS_TSANDADDR:
16727 				bcopy(&ire->ire_src_addr,
16728 				    (char *)opt + off, IP_ADDR_LEN);
16729 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16730 				/* FALLTHRU */
16731 			case IPOPT_TS_TSONLY:
16732 				off = opt[IPOPT_OFFSET] - 1;
16733 				/* Compute # of milliseconds since midnight */
16734 				gethrestime(&now);
16735 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16736 				    now.tv_nsec / (NANOSEC / MILLISEC);
16737 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16738 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16739 				break;
16740 			}
16741 			break;
16742 		}
16743 	}
16744 	return (0);
16745 }
16746 
16747 /*
16748  * This is called after processing at least one of AH/ESP headers.
16749  *
16750  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16751  * the actual, physical interface on which the packet was received,
16752  * but, when ip_strict_dst_multihoming is set to 1, could be the
16753  * interface which had the ipha_dst configured when the packet went
16754  * through ip_rput. The ill_index corresponding to the recv_ill
16755  * is saved in ipsec_in_rill_index
16756  *
16757  * NOTE2: The "ire" argument is only used in IPv4 cases.  This function
16758  * cannot assume "ire" points to valid data for any IPv6 cases.
16759  */
16760 void
16761 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
16762 {
16763 	mblk_t *mp;
16764 	ipaddr_t dst;
16765 	in6_addr_t *v6dstp;
16766 	ipha_t *ipha;
16767 	ip6_t *ip6h;
16768 	ipsec_in_t *ii;
16769 	boolean_t ill_need_rele = B_FALSE;
16770 	boolean_t rill_need_rele = B_FALSE;
16771 	boolean_t ire_need_rele = B_FALSE;
16772 	netstack_t	*ns;
16773 	ip_stack_t	*ipst;
16774 
16775 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
16776 	ASSERT(ii->ipsec_in_ill_index != 0);
16777 	ns = ii->ipsec_in_ns;
16778 	ASSERT(ii->ipsec_in_ns != NULL);
16779 	ipst = ns->netstack_ip;
16780 
16781 	mp = ipsec_mp->b_cont;
16782 	ASSERT(mp != NULL);
16783 
16784 
16785 	if (ill == NULL) {
16786 		ASSERT(recv_ill == NULL);
16787 		/*
16788 		 * We need to get the original queue on which ip_rput_local
16789 		 * or ip_rput_data_v6 was called.
16790 		 */
16791 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
16792 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
16793 		ill_need_rele = B_TRUE;
16794 
16795 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
16796 			recv_ill = ill_lookup_on_ifindex(
16797 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
16798 			    NULL, NULL, NULL, NULL, ipst);
16799 			rill_need_rele = B_TRUE;
16800 		} else {
16801 			recv_ill = ill;
16802 		}
16803 
16804 		if ((ill == NULL) || (recv_ill == NULL)) {
16805 			ip0dbg(("ip_fanout_proto_again: interface "
16806 			    "disappeared\n"));
16807 			if (ill != NULL)
16808 				ill_refrele(ill);
16809 			if (recv_ill != NULL)
16810 				ill_refrele(recv_ill);
16811 			freemsg(ipsec_mp);
16812 			return;
16813 		}
16814 	}
16815 
16816 	ASSERT(ill != NULL && recv_ill != NULL);
16817 
16818 	if (mp->b_datap->db_type == M_CTL) {
16819 		/*
16820 		 * AH/ESP is returning the ICMP message after
16821 		 * removing their headers. Fanout again till
16822 		 * it gets to the right protocol.
16823 		 */
16824 		if (ii->ipsec_in_v4) {
16825 			icmph_t *icmph;
16826 			int iph_hdr_length;
16827 			int hdr_length;
16828 
16829 			ipha = (ipha_t *)mp->b_rptr;
16830 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
16831 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
16832 			ipha = (ipha_t *)&icmph[1];
16833 			hdr_length = IPH_HDR_LENGTH(ipha);
16834 			/*
16835 			 * icmp_inbound_error_fanout may need to do pullupmsg.
16836 			 * Reset the type to M_DATA.
16837 			 */
16838 			mp->b_datap->db_type = M_DATA;
16839 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
16840 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
16841 			    B_FALSE, ill, ii->ipsec_in_zoneid);
16842 		} else {
16843 			icmp6_t *icmp6;
16844 			int hdr_length;
16845 
16846 			ip6h = (ip6_t *)mp->b_rptr;
16847 			/* Don't call hdr_length_v6() unless you have to. */
16848 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
16849 				hdr_length = ip_hdr_length_v6(mp, ip6h);
16850 			else
16851 				hdr_length = IPV6_HDR_LEN;
16852 
16853 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
16854 			/*
16855 			 * icmp_inbound_error_fanout_v6 may need to do
16856 			 * pullupmsg.  Reset the type to M_DATA.
16857 			 */
16858 			mp->b_datap->db_type = M_DATA;
16859 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
16860 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
16861 		}
16862 		if (ill_need_rele)
16863 			ill_refrele(ill);
16864 		if (rill_need_rele)
16865 			ill_refrele(recv_ill);
16866 		return;
16867 	}
16868 
16869 	if (ii->ipsec_in_v4) {
16870 		ipha = (ipha_t *)mp->b_rptr;
16871 		dst = ipha->ipha_dst;
16872 		if (CLASSD(dst)) {
16873 			/*
16874 			 * Multicast has to be delivered to all streams.
16875 			 */
16876 			dst = INADDR_BROADCAST;
16877 		}
16878 
16879 		if (ire == NULL) {
16880 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
16881 			    MBLK_GETLABEL(mp), ipst);
16882 			if (ire == NULL) {
16883 				if (ill_need_rele)
16884 					ill_refrele(ill);
16885 				if (rill_need_rele)
16886 					ill_refrele(recv_ill);
16887 				ip1dbg(("ip_fanout_proto_again: "
16888 				    "IRE not found"));
16889 				freemsg(ipsec_mp);
16890 				return;
16891 			}
16892 			ire_need_rele = B_TRUE;
16893 		}
16894 
16895 		switch (ipha->ipha_protocol) {
16896 			case IPPROTO_UDP:
16897 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
16898 				    recv_ill);
16899 				if (ire_need_rele)
16900 					ire_refrele(ire);
16901 				break;
16902 			case IPPROTO_TCP:
16903 				if (!ire_need_rele)
16904 					IRE_REFHOLD(ire);
16905 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
16906 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
16907 				IRE_REFRELE(ire);
16908 				if (mp != NULL)
16909 					squeue_enter_chain(GET_SQUEUE(mp), mp,
16910 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
16911 				break;
16912 			case IPPROTO_SCTP:
16913 				if (!ire_need_rele)
16914 					IRE_REFHOLD(ire);
16915 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
16916 				    ipsec_mp, 0, ill->ill_rq, dst);
16917 				break;
16918 			default:
16919 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
16920 				    recv_ill, B_FALSE);
16921 				if (ire_need_rele)
16922 					ire_refrele(ire);
16923 				break;
16924 		}
16925 	} else {
16926 		uint32_t rput_flags = 0;
16927 
16928 		ip6h = (ip6_t *)mp->b_rptr;
16929 		v6dstp = &ip6h->ip6_dst;
16930 		/*
16931 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
16932 		 * address.
16933 		 *
16934 		 * Currently, we don't store that state in the IPSEC_IN
16935 		 * message, and we may need to.
16936 		 */
16937 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
16938 		    IP6_IN_LLMCAST : 0);
16939 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
16940 		    NULL, NULL);
16941 	}
16942 	if (ill_need_rele)
16943 		ill_refrele(ill);
16944 	if (rill_need_rele)
16945 		ill_refrele(recv_ill);
16946 }
16947 
16948 /*
16949  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
16950  * returns 'true' if there are still fragments left on the queue, in
16951  * which case we restart the timer.
16952  */
16953 void
16954 ill_frag_timer(void *arg)
16955 {
16956 	ill_t	*ill = (ill_t *)arg;
16957 	boolean_t frag_pending;
16958 	ip_stack_t	*ipst = ill->ill_ipst;
16959 
16960 	mutex_enter(&ill->ill_lock);
16961 	ASSERT(!ill->ill_fragtimer_executing);
16962 	if (ill->ill_state_flags & ILL_CONDEMNED) {
16963 		ill->ill_frag_timer_id = 0;
16964 		mutex_exit(&ill->ill_lock);
16965 		return;
16966 	}
16967 	ill->ill_fragtimer_executing = 1;
16968 	mutex_exit(&ill->ill_lock);
16969 
16970 	frag_pending = ill_frag_timeout(ill, ipst->ips_ip_g_frag_timeout);
16971 
16972 	/*
16973 	 * Restart the timer, if we have fragments pending or if someone
16974 	 * wanted us to be scheduled again.
16975 	 */
16976 	mutex_enter(&ill->ill_lock);
16977 	ill->ill_fragtimer_executing = 0;
16978 	ill->ill_frag_timer_id = 0;
16979 	if (frag_pending || ill->ill_fragtimer_needrestart)
16980 		ill_frag_timer_start(ill);
16981 	mutex_exit(&ill->ill_lock);
16982 }
16983 
16984 void
16985 ill_frag_timer_start(ill_t *ill)
16986 {
16987 	ip_stack_t	*ipst = ill->ill_ipst;
16988 
16989 	ASSERT(MUTEX_HELD(&ill->ill_lock));
16990 
16991 	/* If the ill is closing or opening don't proceed */
16992 	if (ill->ill_state_flags & ILL_CONDEMNED)
16993 		return;
16994 
16995 	if (ill->ill_fragtimer_executing) {
16996 		/*
16997 		 * ill_frag_timer is currently executing. Just record the
16998 		 * the fact that we want the timer to be restarted.
16999 		 * ill_frag_timer will post a timeout before it returns,
17000 		 * ensuring it will be called again.
17001 		 */
17002 		ill->ill_fragtimer_needrestart = 1;
17003 		return;
17004 	}
17005 
17006 	if (ill->ill_frag_timer_id == 0) {
17007 		/*
17008 		 * The timer is neither running nor is the timeout handler
17009 		 * executing. Post a timeout so that ill_frag_timer will be
17010 		 * called
17011 		 */
17012 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
17013 		    MSEC_TO_TICK(ipst->ips_ip_g_frag_timo_ms >> 1));
17014 		ill->ill_fragtimer_needrestart = 0;
17015 	}
17016 }
17017 
17018 /*
17019  * This routine is needed for loopback when forwarding multicasts.
17020  *
17021  * IPQoS Notes:
17022  * IPPF processing is done in fanout routines.
17023  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
17024  * processing for IPsec packets is done when it comes back in clear.
17025  * NOTE : The callers of this function need to do the ire_refrele for the
17026  *	  ire that is being passed in.
17027  */
17028 void
17029 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17030     ill_t *recv_ill, boolean_t esp_in_udp_packet)
17031 {
17032 	ill_t	*ill = (ill_t *)q->q_ptr;
17033 	uint32_t	sum;
17034 	uint32_t	u1;
17035 	uint32_t	u2;
17036 	int		hdr_length;
17037 	boolean_t	mctl_present;
17038 	mblk_t		*first_mp = mp;
17039 	mblk_t		*hada_mp = NULL;
17040 	ipha_t		*inner_ipha;
17041 	ip_stack_t	*ipst;
17042 
17043 	ASSERT(recv_ill != NULL);
17044 	ipst = recv_ill->ill_ipst;
17045 
17046 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17047 	    "ip_rput_locl_start: q %p", q);
17048 
17049 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17050 	ASSERT(ill != NULL);
17051 
17052 
17053 #define	rptr	((uchar_t *)ipha)
17054 #define	iphs	((uint16_t *)ipha)
17055 
17056 	/*
17057 	 * no UDP or TCP packet should come here anymore.
17058 	 */
17059 	ASSERT(ipha->ipha_protocol != IPPROTO_TCP &&
17060 	    ipha->ipha_protocol != IPPROTO_UDP);
17061 
17062 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17063 	if (mctl_present &&
17064 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17065 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17066 
17067 		/*
17068 		 * It's an IPsec accelerated packet.
17069 		 * Keep a pointer to the data attributes around until
17070 		 * we allocate the ipsec_info_t.
17071 		 */
17072 		IPSECHW_DEBUG(IPSECHW_PKT,
17073 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17074 		hada_mp = first_mp;
17075 		hada_mp->b_cont = NULL;
17076 		/*
17077 		 * Since it is accelerated, it comes directly from
17078 		 * the ill and the data attributes is followed by
17079 		 * the packet data.
17080 		 */
17081 		ASSERT(mp->b_datap->db_type != M_CTL);
17082 		first_mp = mp;
17083 		mctl_present = B_FALSE;
17084 	}
17085 
17086 	/*
17087 	 * IF M_CTL is not present, then ipsec_in_is_secure
17088 	 * should return B_TRUE. There is a case where loopback
17089 	 * packets has an M_CTL in the front with all the
17090 	 * IPsec options set to IPSEC_PREF_NEVER - which means
17091 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17092 	 * packets never comes here, it is safe to ASSERT the
17093 	 * following.
17094 	 */
17095 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17096 
17097 	/*
17098 	 * Also, we should never have an mctl_present if this is an
17099 	 * ESP-in-UDP packet.
17100 	 */
17101 	ASSERT(!mctl_present || !esp_in_udp_packet);
17102 
17103 
17104 	/* u1 is # words of IP options */
17105 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
17106 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17107 
17108 	if (u1 || (!esp_in_udp_packet && !mctl_present)) {
17109 		if (u1) {
17110 			if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17111 				if (hada_mp != NULL)
17112 					freemsg(hada_mp);
17113 				return;
17114 			}
17115 		} else {
17116 			/* Check the IP header checksum.  */
17117 #define	uph	((uint16_t *)ipha)
17118 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
17119 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
17120 #undef  uph
17121 			/* finish doing IP checksum */
17122 			sum = (sum & 0xFFFF) + (sum >> 16);
17123 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
17124 			if (sum && sum != 0xFFFF) {
17125 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17126 				goto drop_pkt;
17127 			}
17128 		}
17129 	}
17130 
17131 	/*
17132 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17133 	 * might be called more than once for secure packets, count only
17134 	 * the first time.
17135 	 */
17136 	if (!mctl_present) {
17137 		UPDATE_IB_PKT_COUNT(ire);
17138 		ire->ire_last_used_time = lbolt;
17139 	}
17140 
17141 	/* Check for fragmentation offset. */
17142 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17143 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17144 	if (u1) {
17145 		/*
17146 		 * We re-assemble fragments before we do the AH/ESP
17147 		 * processing. Thus, M_CTL should not be present
17148 		 * while we are re-assembling.
17149 		 */
17150 		ASSERT(!mctl_present);
17151 		ASSERT(first_mp == mp);
17152 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
17153 			return;
17154 		}
17155 		/*
17156 		 * Make sure that first_mp points back to mp as
17157 		 * the mp we came in with could have changed in
17158 		 * ip_rput_fragment().
17159 		 */
17160 		ipha = (ipha_t *)mp->b_rptr;
17161 		first_mp = mp;
17162 	}
17163 
17164 	/*
17165 	 * Clear hardware checksumming flag as it is currently only
17166 	 * used by TCP and UDP.
17167 	 */
17168 	DB_CKSUMFLAGS(mp) = 0;
17169 
17170 	/* Now we have a complete datagram, destined for this machine. */
17171 	u1 = IPH_HDR_LENGTH(ipha);
17172 	switch (ipha->ipha_protocol) {
17173 	case IPPROTO_ICMP: {
17174 		ire_t		*ire_zone;
17175 		ilm_t		*ilm;
17176 		mblk_t		*mp1;
17177 		zoneid_t	last_zoneid;
17178 
17179 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(recv_ill)) {
17180 			ASSERT(ire->ire_type == IRE_BROADCAST);
17181 			/*
17182 			 * In the multicast case, applications may have joined
17183 			 * the group from different zones, so we need to deliver
17184 			 * the packet to each of them. Loop through the
17185 			 * multicast memberships structures (ilm) on the receive
17186 			 * ill and send a copy of the packet up each matching
17187 			 * one. However, we don't do this for multicasts sent on
17188 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17189 			 * they must stay in the sender's zone.
17190 			 *
17191 			 * ilm_add_v6() ensures that ilms in the same zone are
17192 			 * contiguous in the ill_ilm list. We use this property
17193 			 * to avoid sending duplicates needed when two
17194 			 * applications in the same zone join the same group on
17195 			 * different logical interfaces: we ignore the ilm if
17196 			 * its zoneid is the same as the last matching one.
17197 			 * In addition, the sending of the packet for
17198 			 * ire_zoneid is delayed until all of the other ilms
17199 			 * have been exhausted.
17200 			 */
17201 			last_zoneid = -1;
17202 			ILM_WALKER_HOLD(recv_ill);
17203 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
17204 			    ilm = ilm->ilm_next) {
17205 				if ((ilm->ilm_flags & ILM_DELETED) ||
17206 				    ipha->ipha_dst != ilm->ilm_addr ||
17207 				    ilm->ilm_zoneid == last_zoneid ||
17208 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17209 				    ilm->ilm_zoneid == ALL_ZONES ||
17210 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17211 					continue;
17212 				mp1 = ip_copymsg(first_mp);
17213 				if (mp1 == NULL)
17214 					continue;
17215 				icmp_inbound(q, mp1, B_TRUE, ill,
17216 				    0, sum, mctl_present, B_TRUE,
17217 				    recv_ill, ilm->ilm_zoneid);
17218 				last_zoneid = ilm->ilm_zoneid;
17219 			}
17220 			ILM_WALKER_RELE(recv_ill);
17221 		} else if (ire->ire_type == IRE_BROADCAST) {
17222 			/*
17223 			 * In the broadcast case, there may be many zones
17224 			 * which need a copy of the packet delivered to them.
17225 			 * There is one IRE_BROADCAST per broadcast address
17226 			 * and per zone; we walk those using a helper function.
17227 			 * In addition, the sending of the packet for ire is
17228 			 * delayed until all of the other ires have been
17229 			 * processed.
17230 			 */
17231 			IRB_REFHOLD(ire->ire_bucket);
17232 			ire_zone = NULL;
17233 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17234 			    ire)) != NULL) {
17235 				mp1 = ip_copymsg(first_mp);
17236 				if (mp1 == NULL)
17237 					continue;
17238 
17239 				UPDATE_IB_PKT_COUNT(ire_zone);
17240 				ire_zone->ire_last_used_time = lbolt;
17241 				icmp_inbound(q, mp1, B_TRUE, ill,
17242 				    0, sum, mctl_present, B_TRUE,
17243 				    recv_ill, ire_zone->ire_zoneid);
17244 			}
17245 			IRB_REFRELE(ire->ire_bucket);
17246 		}
17247 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17248 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17249 		    ire->ire_zoneid);
17250 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17251 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17252 		return;
17253 	}
17254 	case IPPROTO_IGMP:
17255 		/*
17256 		 * If we are not willing to accept IGMP packets in clear,
17257 		 * then check with global policy.
17258 		 */
17259 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17260 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17261 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17262 			if (first_mp == NULL)
17263 				return;
17264 		}
17265 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17266 			freemsg(first_mp);
17267 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17268 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17269 			return;
17270 		}
17271 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17272 			/* Bad packet - discarded by igmp_input */
17273 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17274 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17275 			if (mctl_present)
17276 				freeb(first_mp);
17277 			return;
17278 		}
17279 		/*
17280 		 * igmp_input() may have returned the pulled up message.
17281 		 * So first_mp and ipha need to be reinitialized.
17282 		 */
17283 		ipha = (ipha_t *)mp->b_rptr;
17284 		if (mctl_present)
17285 			first_mp->b_cont = mp;
17286 		else
17287 			first_mp = mp;
17288 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17289 		    connf_head != NULL) {
17290 			/* No user-level listener for IGMP packets */
17291 			goto drop_pkt;
17292 		}
17293 		/* deliver to local raw users */
17294 		break;
17295 	case IPPROTO_PIM:
17296 		/*
17297 		 * If we are not willing to accept PIM packets in clear,
17298 		 * then check with global policy.
17299 		 */
17300 		if (ipst->ips_pim_accept_clear_messages == 0) {
17301 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17302 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17303 			if (first_mp == NULL)
17304 				return;
17305 		}
17306 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17307 			freemsg(first_mp);
17308 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17309 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17310 			return;
17311 		}
17312 		if (pim_input(q, mp, ill) != 0) {
17313 			/* Bad packet - discarded by pim_input */
17314 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17315 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17316 			if (mctl_present)
17317 				freeb(first_mp);
17318 			return;
17319 		}
17320 
17321 		/*
17322 		 * pim_input() may have pulled up the message so ipha needs to
17323 		 * be reinitialized.
17324 		 */
17325 		ipha = (ipha_t *)mp->b_rptr;
17326 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17327 		    connf_head != NULL) {
17328 			/* No user-level listener for PIM packets */
17329 			goto drop_pkt;
17330 		}
17331 		/* deliver to local raw users */
17332 		break;
17333 	case IPPROTO_ENCAP:
17334 		/*
17335 		 * Handle self-encapsulated packets (IP-in-IP where
17336 		 * the inner addresses == the outer addresses).
17337 		 */
17338 		hdr_length = IPH_HDR_LENGTH(ipha);
17339 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17340 		    mp->b_wptr) {
17341 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17342 			    sizeof (ipha_t) - mp->b_rptr)) {
17343 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17344 				freemsg(first_mp);
17345 				return;
17346 			}
17347 			ipha = (ipha_t *)mp->b_rptr;
17348 		}
17349 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17350 		/*
17351 		 * Check the sanity of the inner IP header.
17352 		 */
17353 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17354 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17355 			freemsg(first_mp);
17356 			return;
17357 		}
17358 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17359 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17360 			freemsg(first_mp);
17361 			return;
17362 		}
17363 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17364 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17365 			ipsec_in_t *ii;
17366 
17367 			/*
17368 			 * Self-encapsulated tunnel packet. Remove
17369 			 * the outer IP header and fanout again.
17370 			 * We also need to make sure that the inner
17371 			 * header is pulled up until options.
17372 			 */
17373 			mp->b_rptr = (uchar_t *)inner_ipha;
17374 			ipha = inner_ipha;
17375 			hdr_length = IPH_HDR_LENGTH(ipha);
17376 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17377 				if (!pullupmsg(mp, (uchar_t *)ipha +
17378 				    + hdr_length - mp->b_rptr)) {
17379 					freemsg(first_mp);
17380 					return;
17381 				}
17382 				ipha = (ipha_t *)mp->b_rptr;
17383 			}
17384 			if (!mctl_present) {
17385 				ASSERT(first_mp == mp);
17386 				/*
17387 				 * This means that somebody is sending
17388 				 * Self-encapsualted packets without AH/ESP.
17389 				 * If AH/ESP was present, we would have already
17390 				 * allocated the first_mp.
17391 				 */
17392 				first_mp = ipsec_in_alloc(B_TRUE,
17393 				    ipst->ips_netstack);
17394 				if (first_mp == NULL) {
17395 					ip1dbg(("ip_proto_input: IPSEC_IN "
17396 					    "allocation failure.\n"));
17397 					BUMP_MIB(ill->ill_ip_mib,
17398 					    ipIfStatsInDiscards);
17399 					freemsg(mp);
17400 					return;
17401 				}
17402 				first_mp->b_cont = mp;
17403 			}
17404 			/*
17405 			 * We generally store the ill_index if we need to
17406 			 * do IPsec processing as we lose the ill queue when
17407 			 * we come back. But in this case, we never should
17408 			 * have to store the ill_index here as it should have
17409 			 * been stored previously when we processed the
17410 			 * AH/ESP header in this routine or for non-ipsec
17411 			 * cases, we still have the queue. But for some bad
17412 			 * packets from the wire, we can get to IPsec after
17413 			 * this and we better store the index for that case.
17414 			 */
17415 			ill = (ill_t *)q->q_ptr;
17416 			ii = (ipsec_in_t *)first_mp->b_rptr;
17417 			ii->ipsec_in_ill_index =
17418 			    ill->ill_phyint->phyint_ifindex;
17419 			ii->ipsec_in_rill_index =
17420 			    recv_ill->ill_phyint->phyint_ifindex;
17421 			if (ii->ipsec_in_decaps) {
17422 				/*
17423 				 * This packet is self-encapsulated multiple
17424 				 * times. We don't want to recurse infinitely.
17425 				 * To keep it simple, drop the packet.
17426 				 */
17427 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17428 				freemsg(first_mp);
17429 				return;
17430 			}
17431 			ii->ipsec_in_decaps = B_TRUE;
17432 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17433 			    ire);
17434 			return;
17435 		}
17436 		break;
17437 	case IPPROTO_AH:
17438 	case IPPROTO_ESP: {
17439 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17440 
17441 		/*
17442 		 * Fast path for AH/ESP. If this is the first time
17443 		 * we are sending a datagram to AH/ESP, allocate
17444 		 * a IPSEC_IN message and prepend it. Otherwise,
17445 		 * just fanout.
17446 		 */
17447 
17448 		int ipsec_rc;
17449 		ipsec_in_t *ii;
17450 		netstack_t *ns = ipst->ips_netstack;
17451 
17452 		IP_STAT(ipst, ipsec_proto_ahesp);
17453 		if (!mctl_present) {
17454 			ASSERT(first_mp == mp);
17455 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17456 			if (first_mp == NULL) {
17457 				ip1dbg(("ip_proto_input: IPSEC_IN "
17458 				    "allocation failure.\n"));
17459 				freemsg(hada_mp); /* okay ifnull */
17460 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17461 				freemsg(mp);
17462 				return;
17463 			}
17464 			/*
17465 			 * Store the ill_index so that when we come back
17466 			 * from IPsec we ride on the same queue.
17467 			 */
17468 			ill = (ill_t *)q->q_ptr;
17469 			ii = (ipsec_in_t *)first_mp->b_rptr;
17470 			ii->ipsec_in_ill_index =
17471 			    ill->ill_phyint->phyint_ifindex;
17472 			ii->ipsec_in_rill_index =
17473 			    recv_ill->ill_phyint->phyint_ifindex;
17474 			first_mp->b_cont = mp;
17475 			/*
17476 			 * Cache hardware acceleration info.
17477 			 */
17478 			if (hada_mp != NULL) {
17479 				IPSECHW_DEBUG(IPSECHW_PKT,
17480 				    ("ip_rput_local: caching data attr.\n"));
17481 				ii->ipsec_in_accelerated = B_TRUE;
17482 				ii->ipsec_in_da = hada_mp;
17483 				hada_mp = NULL;
17484 			}
17485 		} else {
17486 			ii = (ipsec_in_t *)first_mp->b_rptr;
17487 		}
17488 
17489 		if (!ipsec_loaded(ipss)) {
17490 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17491 			    ire->ire_zoneid, ipst);
17492 			return;
17493 		}
17494 
17495 		ns = ipst->ips_netstack;
17496 		/* select inbound SA and have IPsec process the pkt */
17497 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17498 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17499 			boolean_t esp_in_udp_sa;
17500 			if (esph == NULL)
17501 				return;
17502 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17503 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17504 			esp_in_udp_sa = ((ii->ipsec_in_esp_sa->ipsa_flags &
17505 			    IPSA_F_NATT) != 0);
17506 			/*
17507 			 * The following is a fancy, but quick, way of saying:
17508 			 * ESP-in-UDP SA and Raw ESP packet --> drop
17509 			 *    OR
17510 			 * ESP SA and ESP-in-UDP packet --> drop
17511 			 */
17512 			if (esp_in_udp_sa != esp_in_udp_packet) {
17513 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17514 				ip_drop_packet(first_mp, B_TRUE, ill, NULL,
17515 				    DROPPER(ns->netstack_ipsec, ipds_esp_no_sa),
17516 				    &ns->netstack_ipsec->ipsec_dropper);
17517 				return;
17518 			}
17519 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17520 			    first_mp, esph);
17521 		} else {
17522 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
17523 			if (ah == NULL)
17524 				return;
17525 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17526 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17527 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17528 			    first_mp, ah);
17529 		}
17530 
17531 		switch (ipsec_rc) {
17532 		case IPSEC_STATUS_SUCCESS:
17533 			break;
17534 		case IPSEC_STATUS_FAILED:
17535 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17536 			/* FALLTHRU */
17537 		case IPSEC_STATUS_PENDING:
17538 			return;
17539 		}
17540 		/* we're done with IPsec processing, send it up */
17541 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17542 		return;
17543 	}
17544 	default:
17545 		break;
17546 	}
17547 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17548 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17549 		    ire->ire_zoneid));
17550 		goto drop_pkt;
17551 	}
17552 	/*
17553 	 * Handle protocols with which IP is less intimate.  There
17554 	 * can be more than one stream bound to a particular
17555 	 * protocol.  When this is the case, each one gets a copy
17556 	 * of any incoming packets.
17557 	 */
17558 	ip_fanout_proto(q, first_mp, ill, ipha,
17559 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17560 	    B_TRUE, recv_ill, ire->ire_zoneid);
17561 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17562 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17563 	return;
17564 
17565 drop_pkt:
17566 	freemsg(first_mp);
17567 	if (hada_mp != NULL)
17568 		freeb(hada_mp);
17569 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17570 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17571 #undef	rptr
17572 #undef  iphs
17573 
17574 }
17575 
17576 /*
17577  * Update any source route, record route or timestamp options.
17578  * Check that we are at end of strict source route.
17579  * The options have already been checked for sanity in ip_rput_options().
17580  */
17581 static boolean_t
17582 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17583     ip_stack_t *ipst)
17584 {
17585 	ipoptp_t	opts;
17586 	uchar_t		*opt;
17587 	uint8_t		optval;
17588 	uint8_t		optlen;
17589 	ipaddr_t	dst;
17590 	uint32_t	ts;
17591 	ire_t		*dst_ire;
17592 	timestruc_t	now;
17593 	zoneid_t	zoneid;
17594 	ill_t		*ill;
17595 
17596 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17597 
17598 	ip2dbg(("ip_rput_local_options\n"));
17599 
17600 	for (optval = ipoptp_first(&opts, ipha);
17601 	    optval != IPOPT_EOL;
17602 	    optval = ipoptp_next(&opts)) {
17603 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17604 		opt = opts.ipoptp_cur;
17605 		optlen = opts.ipoptp_len;
17606 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17607 		    optval, optlen));
17608 		switch (optval) {
17609 			uint32_t off;
17610 		case IPOPT_SSRR:
17611 		case IPOPT_LSRR:
17612 			off = opt[IPOPT_OFFSET];
17613 			off--;
17614 			if (optlen < IP_ADDR_LEN ||
17615 			    off > optlen - IP_ADDR_LEN) {
17616 				/* End of source route */
17617 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17618 				break;
17619 			}
17620 			/*
17621 			 * This will only happen if two consecutive entries
17622 			 * in the source route contains our address or if
17623 			 * it is a packet with a loose source route which
17624 			 * reaches us before consuming the whole source route
17625 			 */
17626 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17627 			if (optval == IPOPT_SSRR) {
17628 				goto bad_src_route;
17629 			}
17630 			/*
17631 			 * Hack: instead of dropping the packet truncate the
17632 			 * source route to what has been used by filling the
17633 			 * rest with IPOPT_NOP.
17634 			 */
17635 			opt[IPOPT_OLEN] = (uint8_t)off;
17636 			while (off < optlen) {
17637 				opt[off++] = IPOPT_NOP;
17638 			}
17639 			break;
17640 		case IPOPT_RR:
17641 			off = opt[IPOPT_OFFSET];
17642 			off--;
17643 			if (optlen < IP_ADDR_LEN ||
17644 			    off > optlen - IP_ADDR_LEN) {
17645 				/* No more room - ignore */
17646 				ip1dbg((
17647 				    "ip_rput_local_options: end of RR\n"));
17648 				break;
17649 			}
17650 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17651 			    IP_ADDR_LEN);
17652 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17653 			break;
17654 		case IPOPT_TS:
17655 			/* Insert timestamp if there is romm */
17656 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17657 			case IPOPT_TS_TSONLY:
17658 				off = IPOPT_TS_TIMELEN;
17659 				break;
17660 			case IPOPT_TS_PRESPEC:
17661 			case IPOPT_TS_PRESPEC_RFC791:
17662 				/* Verify that the address matched */
17663 				off = opt[IPOPT_OFFSET] - 1;
17664 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17665 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17666 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
17667 				    ipst);
17668 				if (dst_ire == NULL) {
17669 					/* Not for us */
17670 					break;
17671 				}
17672 				ire_refrele(dst_ire);
17673 				/* FALLTHRU */
17674 			case IPOPT_TS_TSANDADDR:
17675 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17676 				break;
17677 			default:
17678 				/*
17679 				 * ip_*put_options should have already
17680 				 * dropped this packet.
17681 				 */
17682 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17683 				    "unknown IT - bug in ip_rput_options?\n");
17684 				return (B_TRUE);	/* Keep "lint" happy */
17685 			}
17686 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17687 				/* Increase overflow counter */
17688 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17689 				opt[IPOPT_POS_OV_FLG] =
17690 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17691 				    (off << 4));
17692 				break;
17693 			}
17694 			off = opt[IPOPT_OFFSET] - 1;
17695 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17696 			case IPOPT_TS_PRESPEC:
17697 			case IPOPT_TS_PRESPEC_RFC791:
17698 			case IPOPT_TS_TSANDADDR:
17699 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17700 				    IP_ADDR_LEN);
17701 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17702 				/* FALLTHRU */
17703 			case IPOPT_TS_TSONLY:
17704 				off = opt[IPOPT_OFFSET] - 1;
17705 				/* Compute # of milliseconds since midnight */
17706 				gethrestime(&now);
17707 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17708 				    now.tv_nsec / (NANOSEC / MILLISEC);
17709 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17710 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17711 				break;
17712 			}
17713 			break;
17714 		}
17715 	}
17716 	return (B_TRUE);
17717 
17718 bad_src_route:
17719 	q = WR(q);
17720 	if (q->q_next != NULL)
17721 		ill = q->q_ptr;
17722 	else
17723 		ill = NULL;
17724 
17725 	/* make sure we clear any indication of a hardware checksum */
17726 	DB_CKSUMFLAGS(mp) = 0;
17727 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
17728 	if (zoneid == ALL_ZONES)
17729 		freemsg(mp);
17730 	else
17731 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17732 	return (B_FALSE);
17733 
17734 }
17735 
17736 /*
17737  * Process IP options in an inbound packet.  If an option affects the
17738  * effective destination address, return the next hop address via dstp.
17739  * Returns -1 if something fails in which case an ICMP error has been sent
17740  * and mp freed.
17741  */
17742 static int
17743 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
17744     ip_stack_t *ipst)
17745 {
17746 	ipoptp_t	opts;
17747 	uchar_t		*opt;
17748 	uint8_t		optval;
17749 	uint8_t		optlen;
17750 	ipaddr_t	dst;
17751 	intptr_t	code = 0;
17752 	ire_t		*ire = NULL;
17753 	zoneid_t	zoneid;
17754 	ill_t		*ill;
17755 
17756 	ip2dbg(("ip_rput_options\n"));
17757 	dst = ipha->ipha_dst;
17758 	for (optval = ipoptp_first(&opts, ipha);
17759 	    optval != IPOPT_EOL;
17760 	    optval = ipoptp_next(&opts)) {
17761 		opt = opts.ipoptp_cur;
17762 		optlen = opts.ipoptp_len;
17763 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17764 		    optval, optlen));
17765 		/*
17766 		 * Note: we need to verify the checksum before we
17767 		 * modify anything thus this routine only extracts the next
17768 		 * hop dst from any source route.
17769 		 */
17770 		switch (optval) {
17771 			uint32_t off;
17772 		case IPOPT_SSRR:
17773 		case IPOPT_LSRR:
17774 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17775 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17776 			if (ire == NULL) {
17777 				if (optval == IPOPT_SSRR) {
17778 					ip1dbg(("ip_rput_options: not next"
17779 					    " strict source route 0x%x\n",
17780 					    ntohl(dst)));
17781 					code = (char *)&ipha->ipha_dst -
17782 					    (char *)ipha;
17783 					goto param_prob; /* RouterReq's */
17784 				}
17785 				ip2dbg(("ip_rput_options: "
17786 				    "not next source route 0x%x\n",
17787 				    ntohl(dst)));
17788 				break;
17789 			}
17790 			ire_refrele(ire);
17791 
17792 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17793 				ip1dbg((
17794 				    "ip_rput_options: bad option offset\n"));
17795 				code = (char *)&opt[IPOPT_OLEN] -
17796 				    (char *)ipha;
17797 				goto param_prob;
17798 			}
17799 			off = opt[IPOPT_OFFSET];
17800 			off--;
17801 		redo_srr:
17802 			if (optlen < IP_ADDR_LEN ||
17803 			    off > optlen - IP_ADDR_LEN) {
17804 				/* End of source route */
17805 				ip1dbg(("ip_rput_options: end of SR\n"));
17806 				break;
17807 			}
17808 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17809 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
17810 			    ntohl(dst)));
17811 
17812 			/*
17813 			 * Check if our address is present more than
17814 			 * once as consecutive hops in source route.
17815 			 * XXX verify per-interface ip_forwarding
17816 			 * for source route?
17817 			 */
17818 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17819 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17820 
17821 			if (ire != NULL) {
17822 				ire_refrele(ire);
17823 				off += IP_ADDR_LEN;
17824 				goto redo_srr;
17825 			}
17826 
17827 			if (dst == htonl(INADDR_LOOPBACK)) {
17828 				ip1dbg(("ip_rput_options: loopback addr in "
17829 				    "source route!\n"));
17830 				goto bad_src_route;
17831 			}
17832 			/*
17833 			 * For strict: verify that dst is directly
17834 			 * reachable.
17835 			 */
17836 			if (optval == IPOPT_SSRR) {
17837 				ire = ire_ftable_lookup(dst, 0, 0,
17838 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
17839 				    MBLK_GETLABEL(mp),
17840 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
17841 				if (ire == NULL) {
17842 					ip1dbg(("ip_rput_options: SSRR not "
17843 					    "directly reachable: 0x%x\n",
17844 					    ntohl(dst)));
17845 					goto bad_src_route;
17846 				}
17847 				ire_refrele(ire);
17848 			}
17849 			/*
17850 			 * Defer update of the offset and the record route
17851 			 * until the packet is forwarded.
17852 			 */
17853 			break;
17854 		case IPOPT_RR:
17855 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17856 				ip1dbg((
17857 				    "ip_rput_options: bad option offset\n"));
17858 				code = (char *)&opt[IPOPT_OLEN] -
17859 				    (char *)ipha;
17860 				goto param_prob;
17861 			}
17862 			break;
17863 		case IPOPT_TS:
17864 			/*
17865 			 * Verify that length >= 5 and that there is either
17866 			 * room for another timestamp or that the overflow
17867 			 * counter is not maxed out.
17868 			 */
17869 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
17870 			if (optlen < IPOPT_MINLEN_IT) {
17871 				goto param_prob;
17872 			}
17873 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17874 				ip1dbg((
17875 				    "ip_rput_options: bad option offset\n"));
17876 				code = (char *)&opt[IPOPT_OFFSET] -
17877 				    (char *)ipha;
17878 				goto param_prob;
17879 			}
17880 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17881 			case IPOPT_TS_TSONLY:
17882 				off = IPOPT_TS_TIMELEN;
17883 				break;
17884 			case IPOPT_TS_TSANDADDR:
17885 			case IPOPT_TS_PRESPEC:
17886 			case IPOPT_TS_PRESPEC_RFC791:
17887 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17888 				break;
17889 			default:
17890 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
17891 				    (char *)ipha;
17892 				goto param_prob;
17893 			}
17894 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
17895 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
17896 				/*
17897 				 * No room and the overflow counter is 15
17898 				 * already.
17899 				 */
17900 				goto param_prob;
17901 			}
17902 			break;
17903 		}
17904 	}
17905 
17906 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
17907 		*dstp = dst;
17908 		return (0);
17909 	}
17910 
17911 	ip1dbg(("ip_rput_options: error processing IP options."));
17912 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
17913 
17914 param_prob:
17915 	q = WR(q);
17916 	if (q->q_next != NULL)
17917 		ill = q->q_ptr;
17918 	else
17919 		ill = NULL;
17920 
17921 	/* make sure we clear any indication of a hardware checksum */
17922 	DB_CKSUMFLAGS(mp) = 0;
17923 	/* Don't know whether this is for non-global or global/forwarding */
17924 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
17925 	if (zoneid == ALL_ZONES)
17926 		freemsg(mp);
17927 	else
17928 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
17929 	return (-1);
17930 
17931 bad_src_route:
17932 	q = WR(q);
17933 	if (q->q_next != NULL)
17934 		ill = q->q_ptr;
17935 	else
17936 		ill = NULL;
17937 
17938 	/* make sure we clear any indication of a hardware checksum */
17939 	DB_CKSUMFLAGS(mp) = 0;
17940 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
17941 	if (zoneid == ALL_ZONES)
17942 		freemsg(mp);
17943 	else
17944 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17945 	return (-1);
17946 }
17947 
17948 /*
17949  * IP & ICMP info in >=14 msg's ...
17950  *  - ip fixed part (mib2_ip_t)
17951  *  - icmp fixed part (mib2_icmp_t)
17952  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
17953  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
17954  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
17955  *  - ipRouteAttributeTable (ip 102)	labeled routes
17956  *  - ip multicast membership (ip_member_t)
17957  *  - ip multicast source filtering (ip_grpsrc_t)
17958  *  - igmp fixed part (struct igmpstat)
17959  *  - multicast routing stats (struct mrtstat)
17960  *  - multicast routing vifs (array of struct vifctl)
17961  *  - multicast routing routes (array of struct mfcctl)
17962  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
17963  *					One per ill plus one generic
17964  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
17965  *					One per ill plus one generic
17966  *  - ipv6RouteEntry			all IPv6 IREs
17967  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
17968  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
17969  *  - ipv6AddrEntry			all IPv6 ipifs
17970  *  - ipv6 multicast membership (ipv6_member_t)
17971  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
17972  *
17973  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
17974  *
17975  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
17976  * already filled in by the caller.
17977  * Return value of 0 indicates that no messages were sent and caller
17978  * should free mpctl.
17979  */
17980 int
17981 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level)
17982 {
17983 	ip_stack_t *ipst;
17984 	sctp_stack_t *sctps;
17985 
17986 	if (q->q_next != NULL) {
17987 		ipst = ILLQ_TO_IPST(q);
17988 	} else {
17989 		ipst = CONNQ_TO_IPST(q);
17990 	}
17991 	ASSERT(ipst != NULL);
17992 	sctps = ipst->ips_netstack->netstack_sctp;
17993 
17994 	if (mpctl == NULL || mpctl->b_cont == NULL) {
17995 		return (0);
17996 	}
17997 
17998 	/*
17999 	 * For the purposes of the (broken) packet shell use
18000 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
18001 	 * to make TCP and UDP appear first in the list of mib items.
18002 	 * TBD: We could expand this and use it in netstat so that
18003 	 * the kernel doesn't have to produce large tables (connections,
18004 	 * routes, etc) when netstat only wants the statistics or a particular
18005 	 * table.
18006 	 */
18007 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
18008 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
18009 			return (1);
18010 		}
18011 	}
18012 
18013 	if (level != MIB2_TCP) {
18014 		if ((mpctl = udp_snmp_get(q, mpctl)) == NULL) {
18015 			return (1);
18016 		}
18017 	}
18018 
18019 	if (level != MIB2_UDP) {
18020 		if ((mpctl = tcp_snmp_get(q, mpctl)) == NULL) {
18021 			return (1);
18022 		}
18023 	}
18024 
18025 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
18026 	    ipst)) == NULL) {
18027 		return (1);
18028 	}
18029 
18030 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
18031 		return (1);
18032 	}
18033 
18034 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
18035 		return (1);
18036 	}
18037 
18038 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
18039 		return (1);
18040 	}
18041 
18042 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
18043 		return (1);
18044 	}
18045 
18046 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
18047 		return (1);
18048 	}
18049 
18050 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
18051 		return (1);
18052 	}
18053 
18054 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
18055 		return (1);
18056 	}
18057 
18058 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
18059 		return (1);
18060 	}
18061 
18062 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18063 		return (1);
18064 	}
18065 
18066 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18067 		return (1);
18068 	}
18069 
18070 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18071 		return (1);
18072 	}
18073 
18074 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18075 		return (1);
18076 	}
18077 
18078 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18079 		return (1);
18080 	}
18081 
18082 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, ipst)) == NULL) {
18083 		return (1);
18084 	}
18085 
18086 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, ipst);
18087 	if (mpctl == NULL) {
18088 		return (1);
18089 	}
18090 
18091 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18092 		return (1);
18093 	}
18094 	freemsg(mpctl);
18095 	return (1);
18096 }
18097 
18098 
18099 /* Get global (legacy) IPv4 statistics */
18100 static mblk_t *
18101 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18102     ip_stack_t *ipst)
18103 {
18104 	mib2_ip_t		old_ip_mib;
18105 	struct opthdr		*optp;
18106 	mblk_t			*mp2ctl;
18107 
18108 	/*
18109 	 * make a copy of the original message
18110 	 */
18111 	mp2ctl = copymsg(mpctl);
18112 
18113 	/* fixed length IP structure... */
18114 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18115 	optp->level = MIB2_IP;
18116 	optp->name = 0;
18117 	SET_MIB(old_ip_mib.ipForwarding,
18118 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18119 	SET_MIB(old_ip_mib.ipDefaultTTL,
18120 	    (uint32_t)ipst->ips_ip_def_ttl);
18121 	SET_MIB(old_ip_mib.ipReasmTimeout,
18122 	    ipst->ips_ip_g_frag_timeout);
18123 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18124 	    sizeof (mib2_ipAddrEntry_t));
18125 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18126 	    sizeof (mib2_ipRouteEntry_t));
18127 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18128 	    sizeof (mib2_ipNetToMediaEntry_t));
18129 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18130 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18131 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18132 	    sizeof (mib2_ipAttributeEntry_t));
18133 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18134 
18135 	/*
18136 	 * Grab the statistics from the new IP MIB
18137 	 */
18138 	SET_MIB(old_ip_mib.ipInReceives,
18139 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18140 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18141 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18142 	SET_MIB(old_ip_mib.ipForwDatagrams,
18143 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18144 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18145 	    ipmib->ipIfStatsInUnknownProtos);
18146 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18147 	SET_MIB(old_ip_mib.ipInDelivers,
18148 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18149 	SET_MIB(old_ip_mib.ipOutRequests,
18150 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18151 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18152 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18153 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18154 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18155 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18156 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18157 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18158 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18159 
18160 	/* ipRoutingDiscards is not being used */
18161 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18162 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18163 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18164 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18165 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18166 	    ipmib->ipIfStatsReasmDuplicates);
18167 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18168 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18169 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18170 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18171 	SET_MIB(old_ip_mib.rawipInOverflows,
18172 	    ipmib->rawipIfStatsInOverflows);
18173 
18174 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18175 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18176 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18177 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18178 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18179 	    ipmib->ipIfStatsOutSwitchIPVersion);
18180 
18181 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18182 	    (int)sizeof (old_ip_mib))) {
18183 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18184 		    (uint_t)sizeof (old_ip_mib)));
18185 	}
18186 
18187 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18188 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18189 	    (int)optp->level, (int)optp->name, (int)optp->len));
18190 	qreply(q, mpctl);
18191 	return (mp2ctl);
18192 }
18193 
18194 /* Per interface IPv4 statistics */
18195 static mblk_t *
18196 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18197 {
18198 	struct opthdr		*optp;
18199 	mblk_t			*mp2ctl;
18200 	ill_t			*ill;
18201 	ill_walk_context_t	ctx;
18202 	mblk_t			*mp_tail = NULL;
18203 	mib2_ipIfStatsEntry_t	global_ip_mib;
18204 
18205 	/*
18206 	 * Make a copy of the original message
18207 	 */
18208 	mp2ctl = copymsg(mpctl);
18209 
18210 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18211 	optp->level = MIB2_IP;
18212 	optp->name = MIB2_IP_TRAFFIC_STATS;
18213 	/* Include "unknown interface" ip_mib */
18214 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18215 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18216 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18217 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18218 	    (ipst->ips_ip_g_forward ? 1 : 2));
18219 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18220 	    (uint32_t)ipst->ips_ip_def_ttl);
18221 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18222 	    sizeof (mib2_ipIfStatsEntry_t));
18223 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18224 	    sizeof (mib2_ipAddrEntry_t));
18225 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18226 	    sizeof (mib2_ipRouteEntry_t));
18227 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18228 	    sizeof (mib2_ipNetToMediaEntry_t));
18229 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18230 	    sizeof (ip_member_t));
18231 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18232 	    sizeof (ip_grpsrc_t));
18233 
18234 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18235 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18236 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18237 		    "failed to allocate %u bytes\n",
18238 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18239 	}
18240 
18241 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18242 
18243 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18244 	ill = ILL_START_WALK_V4(&ctx, ipst);
18245 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18246 		ill->ill_ip_mib->ipIfStatsIfIndex =
18247 		    ill->ill_phyint->phyint_ifindex;
18248 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18249 		    (ipst->ips_ip_g_forward ? 1 : 2));
18250 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18251 		    (uint32_t)ipst->ips_ip_def_ttl);
18252 
18253 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18254 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18255 		    (char *)ill->ill_ip_mib,
18256 		    (int)sizeof (*ill->ill_ip_mib))) {
18257 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18258 			    "failed to allocate %u bytes\n",
18259 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18260 		}
18261 	}
18262 	rw_exit(&ipst->ips_ill_g_lock);
18263 
18264 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18265 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18266 	    "level %d, name %d, len %d\n",
18267 	    (int)optp->level, (int)optp->name, (int)optp->len));
18268 	qreply(q, mpctl);
18269 
18270 	if (mp2ctl == NULL)
18271 		return (NULL);
18272 
18273 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18274 }
18275 
18276 /* Global IPv4 ICMP statistics */
18277 static mblk_t *
18278 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18279 {
18280 	struct opthdr		*optp;
18281 	mblk_t			*mp2ctl;
18282 
18283 	/*
18284 	 * Make a copy of the original message
18285 	 */
18286 	mp2ctl = copymsg(mpctl);
18287 
18288 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18289 	optp->level = MIB2_ICMP;
18290 	optp->name = 0;
18291 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18292 	    (int)sizeof (ipst->ips_icmp_mib))) {
18293 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18294 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18295 	}
18296 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18297 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18298 	    (int)optp->level, (int)optp->name, (int)optp->len));
18299 	qreply(q, mpctl);
18300 	return (mp2ctl);
18301 }
18302 
18303 /* Global IPv4 IGMP statistics */
18304 static mblk_t *
18305 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18306 {
18307 	struct opthdr		*optp;
18308 	mblk_t			*mp2ctl;
18309 
18310 	/*
18311 	 * make a copy of the original message
18312 	 */
18313 	mp2ctl = copymsg(mpctl);
18314 
18315 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18316 	optp->level = EXPER_IGMP;
18317 	optp->name = 0;
18318 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18319 	    (int)sizeof (ipst->ips_igmpstat))) {
18320 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18321 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18322 	}
18323 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18324 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18325 	    (int)optp->level, (int)optp->name, (int)optp->len));
18326 	qreply(q, mpctl);
18327 	return (mp2ctl);
18328 }
18329 
18330 /* Global IPv4 Multicast Routing statistics */
18331 static mblk_t *
18332 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18333 {
18334 	struct opthdr		*optp;
18335 	mblk_t			*mp2ctl;
18336 
18337 	/*
18338 	 * make a copy of the original message
18339 	 */
18340 	mp2ctl = copymsg(mpctl);
18341 
18342 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18343 	optp->level = EXPER_DVMRP;
18344 	optp->name = 0;
18345 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18346 		ip0dbg(("ip_mroute_stats: failed\n"));
18347 	}
18348 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18349 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18350 	    (int)optp->level, (int)optp->name, (int)optp->len));
18351 	qreply(q, mpctl);
18352 	return (mp2ctl);
18353 }
18354 
18355 /* IPv4 address information */
18356 static mblk_t *
18357 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18358 {
18359 	struct opthdr		*optp;
18360 	mblk_t			*mp2ctl;
18361 	mblk_t			*mp_tail = NULL;
18362 	ill_t			*ill;
18363 	ipif_t			*ipif;
18364 	uint_t			bitval;
18365 	mib2_ipAddrEntry_t	mae;
18366 	zoneid_t		zoneid;
18367 	ill_walk_context_t ctx;
18368 
18369 	/*
18370 	 * make a copy of the original message
18371 	 */
18372 	mp2ctl = copymsg(mpctl);
18373 
18374 	/* ipAddrEntryTable */
18375 
18376 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18377 	optp->level = MIB2_IP;
18378 	optp->name = MIB2_IP_ADDR;
18379 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18380 
18381 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18382 	ill = ILL_START_WALK_V4(&ctx, ipst);
18383 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18384 		for (ipif = ill->ill_ipif; ipif != NULL;
18385 		    ipif = ipif->ipif_next) {
18386 			if (ipif->ipif_zoneid != zoneid &&
18387 			    ipif->ipif_zoneid != ALL_ZONES)
18388 				continue;
18389 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18390 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18391 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18392 
18393 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
18394 			    OCTET_LENGTH);
18395 			mae.ipAdEntIfIndex.o_length =
18396 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18397 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18398 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18399 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18400 			mae.ipAdEntInfo.ae_subnet_len =
18401 			    ip_mask_to_plen(ipif->ipif_net_mask);
18402 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18403 			for (bitval = 1;
18404 			    bitval &&
18405 			    !(bitval & ipif->ipif_brd_addr);
18406 			    bitval <<= 1)
18407 				noop;
18408 			mae.ipAdEntBcastAddr = bitval;
18409 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18410 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18411 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18412 			mae.ipAdEntInfo.ae_broadcast_addr =
18413 			    ipif->ipif_brd_addr;
18414 			mae.ipAdEntInfo.ae_pp_dst_addr =
18415 			    ipif->ipif_pp_dst_addr;
18416 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18417 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18418 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18419 
18420 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18421 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18422 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18423 				    "allocate %u bytes\n",
18424 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18425 			}
18426 		}
18427 	}
18428 	rw_exit(&ipst->ips_ill_g_lock);
18429 
18430 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18431 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18432 	    (int)optp->level, (int)optp->name, (int)optp->len));
18433 	qreply(q, mpctl);
18434 	return (mp2ctl);
18435 }
18436 
18437 /* IPv6 address information */
18438 static mblk_t *
18439 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18440 {
18441 	struct opthdr		*optp;
18442 	mblk_t			*mp2ctl;
18443 	mblk_t			*mp_tail = NULL;
18444 	ill_t			*ill;
18445 	ipif_t			*ipif;
18446 	mib2_ipv6AddrEntry_t	mae6;
18447 	zoneid_t		zoneid;
18448 	ill_walk_context_t	ctx;
18449 
18450 	/*
18451 	 * make a copy of the original message
18452 	 */
18453 	mp2ctl = copymsg(mpctl);
18454 
18455 	/* ipv6AddrEntryTable */
18456 
18457 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18458 	optp->level = MIB2_IP6;
18459 	optp->name = MIB2_IP6_ADDR;
18460 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18461 
18462 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18463 	ill = ILL_START_WALK_V6(&ctx, ipst);
18464 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18465 		for (ipif = ill->ill_ipif; ipif != NULL;
18466 		    ipif = ipif->ipif_next) {
18467 			if (ipif->ipif_zoneid != zoneid &&
18468 			    ipif->ipif_zoneid != ALL_ZONES)
18469 				continue;
18470 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18471 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18472 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18473 
18474 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
18475 			    OCTET_LENGTH);
18476 			mae6.ipv6AddrIfIndex.o_length =
18477 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18478 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18479 			mae6.ipv6AddrPfxLength =
18480 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18481 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18482 			mae6.ipv6AddrInfo.ae_subnet_len =
18483 			    mae6.ipv6AddrPfxLength;
18484 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18485 
18486 			/* Type: stateless(1), stateful(2), unknown(3) */
18487 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18488 				mae6.ipv6AddrType = 1;
18489 			else
18490 				mae6.ipv6AddrType = 2;
18491 			/* Anycast: true(1), false(2) */
18492 			if (ipif->ipif_flags & IPIF_ANYCAST)
18493 				mae6.ipv6AddrAnycastFlag = 1;
18494 			else
18495 				mae6.ipv6AddrAnycastFlag = 2;
18496 
18497 			/*
18498 			 * Address status: preferred(1), deprecated(2),
18499 			 * invalid(3), inaccessible(4), unknown(5)
18500 			 */
18501 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18502 				mae6.ipv6AddrStatus = 3;
18503 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18504 				mae6.ipv6AddrStatus = 2;
18505 			else
18506 				mae6.ipv6AddrStatus = 1;
18507 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18508 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18509 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18510 			    ipif->ipif_v6pp_dst_addr;
18511 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18512 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18513 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18514 			mae6.ipv6AddrIdentifier = ill->ill_token;
18515 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18516 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18517 			mae6.ipv6AddrRetransmitTime =
18518 			    ill->ill_reachable_retrans_time;
18519 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18520 			    (char *)&mae6,
18521 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
18522 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18523 				    "allocate %u bytes\n",
18524 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18525 			}
18526 		}
18527 	}
18528 	rw_exit(&ipst->ips_ill_g_lock);
18529 
18530 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18531 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18532 	    (int)optp->level, (int)optp->name, (int)optp->len));
18533 	qreply(q, mpctl);
18534 	return (mp2ctl);
18535 }
18536 
18537 /* IPv4 multicast group membership. */
18538 static mblk_t *
18539 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18540 {
18541 	struct opthdr		*optp;
18542 	mblk_t			*mp2ctl;
18543 	ill_t			*ill;
18544 	ipif_t			*ipif;
18545 	ilm_t			*ilm;
18546 	ip_member_t		ipm;
18547 	mblk_t			*mp_tail = NULL;
18548 	ill_walk_context_t	ctx;
18549 	zoneid_t		zoneid;
18550 
18551 	/*
18552 	 * make a copy of the original message
18553 	 */
18554 	mp2ctl = copymsg(mpctl);
18555 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18556 
18557 	/* ipGroupMember table */
18558 	optp = (struct opthdr *)&mpctl->b_rptr[
18559 	    sizeof (struct T_optmgmt_ack)];
18560 	optp->level = MIB2_IP;
18561 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18562 
18563 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18564 	ill = ILL_START_WALK_V4(&ctx, ipst);
18565 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18566 		ILM_WALKER_HOLD(ill);
18567 		for (ipif = ill->ill_ipif; ipif != NULL;
18568 		    ipif = ipif->ipif_next) {
18569 			if (ipif->ipif_zoneid != zoneid &&
18570 			    ipif->ipif_zoneid != ALL_ZONES)
18571 				continue;	/* not this zone */
18572 			ipif_get_name(ipif, ipm.ipGroupMemberIfIndex.o_bytes,
18573 			    OCTET_LENGTH);
18574 			ipm.ipGroupMemberIfIndex.o_length =
18575 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18576 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18577 				ASSERT(ilm->ilm_ipif != NULL);
18578 				ASSERT(ilm->ilm_ill == NULL);
18579 				if (ilm->ilm_ipif != ipif)
18580 					continue;
18581 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18582 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18583 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18584 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18585 				    (char *)&ipm, (int)sizeof (ipm))) {
18586 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18587 					    "failed to allocate %u bytes\n",
18588 					    (uint_t)sizeof (ipm)));
18589 				}
18590 			}
18591 		}
18592 		ILM_WALKER_RELE(ill);
18593 	}
18594 	rw_exit(&ipst->ips_ill_g_lock);
18595 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18596 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18597 	    (int)optp->level, (int)optp->name, (int)optp->len));
18598 	qreply(q, mpctl);
18599 	return (mp2ctl);
18600 }
18601 
18602 /* IPv6 multicast group membership. */
18603 static mblk_t *
18604 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18605 {
18606 	struct opthdr		*optp;
18607 	mblk_t			*mp2ctl;
18608 	ill_t			*ill;
18609 	ilm_t			*ilm;
18610 	ipv6_member_t		ipm6;
18611 	mblk_t			*mp_tail = NULL;
18612 	ill_walk_context_t	ctx;
18613 	zoneid_t		zoneid;
18614 
18615 	/*
18616 	 * make a copy of the original message
18617 	 */
18618 	mp2ctl = copymsg(mpctl);
18619 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18620 
18621 	/* ip6GroupMember table */
18622 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18623 	optp->level = MIB2_IP6;
18624 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18625 
18626 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18627 	ill = ILL_START_WALK_V6(&ctx, ipst);
18628 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18629 		ILM_WALKER_HOLD(ill);
18630 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18631 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18632 			ASSERT(ilm->ilm_ipif == NULL);
18633 			ASSERT(ilm->ilm_ill != NULL);
18634 			if (ilm->ilm_zoneid != zoneid)
18635 				continue;	/* not this zone */
18636 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18637 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18638 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18639 			if (!snmp_append_data2(mpctl->b_cont,
18640 			    &mp_tail,
18641 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18642 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18643 				    "failed to allocate %u bytes\n",
18644 				    (uint_t)sizeof (ipm6)));
18645 			}
18646 		}
18647 		ILM_WALKER_RELE(ill);
18648 	}
18649 	rw_exit(&ipst->ips_ill_g_lock);
18650 
18651 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18652 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18653 	    (int)optp->level, (int)optp->name, (int)optp->len));
18654 	qreply(q, mpctl);
18655 	return (mp2ctl);
18656 }
18657 
18658 /* IP multicast filtered sources */
18659 static mblk_t *
18660 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18661 {
18662 	struct opthdr		*optp;
18663 	mblk_t			*mp2ctl;
18664 	ill_t			*ill;
18665 	ipif_t			*ipif;
18666 	ilm_t			*ilm;
18667 	ip_grpsrc_t		ips;
18668 	mblk_t			*mp_tail = NULL;
18669 	ill_walk_context_t	ctx;
18670 	zoneid_t		zoneid;
18671 	int			i;
18672 	slist_t			*sl;
18673 
18674 	/*
18675 	 * make a copy of the original message
18676 	 */
18677 	mp2ctl = copymsg(mpctl);
18678 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18679 
18680 	/* ipGroupSource table */
18681 	optp = (struct opthdr *)&mpctl->b_rptr[
18682 	    sizeof (struct T_optmgmt_ack)];
18683 	optp->level = MIB2_IP;
18684 	optp->name = EXPER_IP_GROUP_SOURCES;
18685 
18686 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18687 	ill = ILL_START_WALK_V4(&ctx, ipst);
18688 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18689 		ILM_WALKER_HOLD(ill);
18690 		for (ipif = ill->ill_ipif; ipif != NULL;
18691 		    ipif = ipif->ipif_next) {
18692 			if (ipif->ipif_zoneid != zoneid)
18693 				continue;	/* not this zone */
18694 			ipif_get_name(ipif, ips.ipGroupSourceIfIndex.o_bytes,
18695 			    OCTET_LENGTH);
18696 			ips.ipGroupSourceIfIndex.o_length =
18697 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18698 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18699 				ASSERT(ilm->ilm_ipif != NULL);
18700 				ASSERT(ilm->ilm_ill == NULL);
18701 				sl = ilm->ilm_filter;
18702 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18703 					continue;
18704 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18705 				for (i = 0; i < sl->sl_numsrc; i++) {
18706 					if (!IN6_IS_ADDR_V4MAPPED(
18707 					    &sl->sl_addr[i]))
18708 						continue;
18709 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18710 					    ips.ipGroupSourceAddress);
18711 					if (snmp_append_data2(mpctl->b_cont,
18712 					    &mp_tail, (char *)&ips,
18713 					    (int)sizeof (ips)) == 0) {
18714 						ip1dbg(("ip_snmp_get_mib2_"
18715 						    "ip_group_src: failed to "
18716 						    "allocate %u bytes\n",
18717 						    (uint_t)sizeof (ips)));
18718 					}
18719 				}
18720 			}
18721 		}
18722 		ILM_WALKER_RELE(ill);
18723 	}
18724 	rw_exit(&ipst->ips_ill_g_lock);
18725 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18726 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18727 	    (int)optp->level, (int)optp->name, (int)optp->len));
18728 	qreply(q, mpctl);
18729 	return (mp2ctl);
18730 }
18731 
18732 /* IPv6 multicast filtered sources. */
18733 static mblk_t *
18734 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18735 {
18736 	struct opthdr		*optp;
18737 	mblk_t			*mp2ctl;
18738 	ill_t			*ill;
18739 	ilm_t			*ilm;
18740 	ipv6_grpsrc_t		ips6;
18741 	mblk_t			*mp_tail = NULL;
18742 	ill_walk_context_t	ctx;
18743 	zoneid_t		zoneid;
18744 	int			i;
18745 	slist_t			*sl;
18746 
18747 	/*
18748 	 * make a copy of the original message
18749 	 */
18750 	mp2ctl = copymsg(mpctl);
18751 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18752 
18753 	/* ip6GroupMember table */
18754 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18755 	optp->level = MIB2_IP6;
18756 	optp->name = EXPER_IP6_GROUP_SOURCES;
18757 
18758 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18759 	ill = ILL_START_WALK_V6(&ctx, ipst);
18760 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18761 		ILM_WALKER_HOLD(ill);
18762 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18763 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18764 			ASSERT(ilm->ilm_ipif == NULL);
18765 			ASSERT(ilm->ilm_ill != NULL);
18766 			sl = ilm->ilm_filter;
18767 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
18768 				continue;
18769 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
18770 			for (i = 0; i < sl->sl_numsrc; i++) {
18771 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
18772 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18773 				    (char *)&ips6, (int)sizeof (ips6))) {
18774 					ip1dbg(("ip_snmp_get_mib2_ip6_"
18775 					    "group_src: failed to allocate "
18776 					    "%u bytes\n",
18777 					    (uint_t)sizeof (ips6)));
18778 				}
18779 			}
18780 		}
18781 		ILM_WALKER_RELE(ill);
18782 	}
18783 	rw_exit(&ipst->ips_ill_g_lock);
18784 
18785 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18786 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18787 	    (int)optp->level, (int)optp->name, (int)optp->len));
18788 	qreply(q, mpctl);
18789 	return (mp2ctl);
18790 }
18791 
18792 /* Multicast routing virtual interface table. */
18793 static mblk_t *
18794 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18795 {
18796 	struct opthdr		*optp;
18797 	mblk_t			*mp2ctl;
18798 
18799 	/*
18800 	 * make a copy of the original message
18801 	 */
18802 	mp2ctl = copymsg(mpctl);
18803 
18804 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18805 	optp->level = EXPER_DVMRP;
18806 	optp->name = EXPER_DVMRP_VIF;
18807 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
18808 		ip0dbg(("ip_mroute_vif: failed\n"));
18809 	}
18810 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18811 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
18812 	    (int)optp->level, (int)optp->name, (int)optp->len));
18813 	qreply(q, mpctl);
18814 	return (mp2ctl);
18815 }
18816 
18817 /* Multicast routing table. */
18818 static mblk_t *
18819 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18820 {
18821 	struct opthdr		*optp;
18822 	mblk_t			*mp2ctl;
18823 
18824 	/*
18825 	 * make a copy of the original message
18826 	 */
18827 	mp2ctl = copymsg(mpctl);
18828 
18829 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18830 	optp->level = EXPER_DVMRP;
18831 	optp->name = EXPER_DVMRP_MRT;
18832 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
18833 		ip0dbg(("ip_mroute_mrt: failed\n"));
18834 	}
18835 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18836 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
18837 	    (int)optp->level, (int)optp->name, (int)optp->len));
18838 	qreply(q, mpctl);
18839 	return (mp2ctl);
18840 }
18841 
18842 /*
18843  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
18844  * in one IRE walk.
18845  */
18846 static mblk_t *
18847 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18848 {
18849 	struct opthdr	*optp;
18850 	mblk_t		*mp2ctl;	/* Returned */
18851 	mblk_t		*mp3ctl;	/* nettomedia */
18852 	mblk_t		*mp4ctl;	/* routeattrs */
18853 	iproutedata_t	ird;
18854 	zoneid_t	zoneid;
18855 
18856 	/*
18857 	 * make copies of the original message
18858 	 *	- mp2ctl is returned unchanged to the caller for his use
18859 	 *	- mpctl is sent upstream as ipRouteEntryTable
18860 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
18861 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
18862 	 */
18863 	mp2ctl = copymsg(mpctl);
18864 	mp3ctl = copymsg(mpctl);
18865 	mp4ctl = copymsg(mpctl);
18866 	if (mp3ctl == NULL || mp4ctl == NULL) {
18867 		freemsg(mp4ctl);
18868 		freemsg(mp3ctl);
18869 		freemsg(mp2ctl);
18870 		freemsg(mpctl);
18871 		return (NULL);
18872 	}
18873 
18874 	bzero(&ird, sizeof (ird));
18875 
18876 	ird.ird_route.lp_head = mpctl->b_cont;
18877 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18878 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18879 
18880 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18881 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
18882 
18883 	/* ipRouteEntryTable in mpctl */
18884 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18885 	optp->level = MIB2_IP;
18886 	optp->name = MIB2_IP_ROUTE;
18887 	optp->len = msgdsize(ird.ird_route.lp_head);
18888 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18889 	    (int)optp->level, (int)optp->name, (int)optp->len));
18890 	qreply(q, mpctl);
18891 
18892 	/* ipNetToMediaEntryTable in mp3ctl */
18893 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18894 	optp->level = MIB2_IP;
18895 	optp->name = MIB2_IP_MEDIA;
18896 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18897 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18898 	    (int)optp->level, (int)optp->name, (int)optp->len));
18899 	qreply(q, mp3ctl);
18900 
18901 	/* ipRouteAttributeTable in mp4ctl */
18902 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18903 	optp->level = MIB2_IP;
18904 	optp->name = EXPER_IP_RTATTR;
18905 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18906 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18907 	    (int)optp->level, (int)optp->name, (int)optp->len));
18908 	if (optp->len == 0)
18909 		freemsg(mp4ctl);
18910 	else
18911 		qreply(q, mp4ctl);
18912 
18913 	return (mp2ctl);
18914 }
18915 
18916 /*
18917  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
18918  * ipv6NetToMediaEntryTable in an NDP walk.
18919  */
18920 static mblk_t *
18921 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18922 {
18923 	struct opthdr	*optp;
18924 	mblk_t		*mp2ctl;	/* Returned */
18925 	mblk_t		*mp3ctl;	/* nettomedia */
18926 	mblk_t		*mp4ctl;	/* routeattrs */
18927 	iproutedata_t	ird;
18928 	zoneid_t	zoneid;
18929 
18930 	/*
18931 	 * make copies of the original message
18932 	 *	- mp2ctl is returned unchanged to the caller for his use
18933 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
18934 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
18935 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
18936 	 */
18937 	mp2ctl = copymsg(mpctl);
18938 	mp3ctl = copymsg(mpctl);
18939 	mp4ctl = copymsg(mpctl);
18940 	if (mp3ctl == NULL || mp4ctl == NULL) {
18941 		freemsg(mp4ctl);
18942 		freemsg(mp3ctl);
18943 		freemsg(mp2ctl);
18944 		freemsg(mpctl);
18945 		return (NULL);
18946 	}
18947 
18948 	bzero(&ird, sizeof (ird));
18949 
18950 	ird.ird_route.lp_head = mpctl->b_cont;
18951 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18952 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18953 
18954 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18955 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
18956 
18957 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18958 	optp->level = MIB2_IP6;
18959 	optp->name = MIB2_IP6_ROUTE;
18960 	optp->len = msgdsize(ird.ird_route.lp_head);
18961 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18962 	    (int)optp->level, (int)optp->name, (int)optp->len));
18963 	qreply(q, mpctl);
18964 
18965 	/* ipv6NetToMediaEntryTable in mp3ctl */
18966 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
18967 
18968 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18969 	optp->level = MIB2_IP6;
18970 	optp->name = MIB2_IP6_MEDIA;
18971 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18972 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18973 	    (int)optp->level, (int)optp->name, (int)optp->len));
18974 	qreply(q, mp3ctl);
18975 
18976 	/* ipv6RouteAttributeTable in mp4ctl */
18977 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18978 	optp->level = MIB2_IP6;
18979 	optp->name = EXPER_IP_RTATTR;
18980 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18981 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18982 	    (int)optp->level, (int)optp->name, (int)optp->len));
18983 	if (optp->len == 0)
18984 		freemsg(mp4ctl);
18985 	else
18986 		qreply(q, mp4ctl);
18987 
18988 	return (mp2ctl);
18989 }
18990 
18991 /*
18992  * IPv6 mib: One per ill
18993  */
18994 static mblk_t *
18995 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18996 {
18997 	struct opthdr		*optp;
18998 	mblk_t			*mp2ctl;
18999 	ill_t			*ill;
19000 	ill_walk_context_t	ctx;
19001 	mblk_t			*mp_tail = NULL;
19002 
19003 	/*
19004 	 * Make a copy of the original message
19005 	 */
19006 	mp2ctl = copymsg(mpctl);
19007 
19008 	/* fixed length IPv6 structure ... */
19009 
19010 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19011 	optp->level = MIB2_IP6;
19012 	optp->name = 0;
19013 	/* Include "unknown interface" ip6_mib */
19014 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
19015 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
19016 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
19017 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
19018 	    ipst->ips_ipv6_forward ? 1 : 2);
19019 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
19020 	    ipst->ips_ipv6_def_hops);
19021 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
19022 	    sizeof (mib2_ipIfStatsEntry_t));
19023 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
19024 	    sizeof (mib2_ipv6AddrEntry_t));
19025 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
19026 	    sizeof (mib2_ipv6RouteEntry_t));
19027 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
19028 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19029 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
19030 	    sizeof (ipv6_member_t));
19031 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
19032 	    sizeof (ipv6_grpsrc_t));
19033 
19034 	/*
19035 	 * Synchronize 64- and 32-bit counters
19036 	 */
19037 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
19038 	    ipIfStatsHCInReceives);
19039 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
19040 	    ipIfStatsHCInDelivers);
19041 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
19042 	    ipIfStatsHCOutRequests);
19043 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
19044 	    ipIfStatsHCOutForwDatagrams);
19045 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
19046 	    ipIfStatsHCOutMcastPkts);
19047 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19048 	    ipIfStatsHCInMcastPkts);
19049 
19050 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19051 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19052 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19053 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19054 	}
19055 
19056 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19057 	ill = ILL_START_WALK_V6(&ctx, ipst);
19058 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19059 		ill->ill_ip_mib->ipIfStatsIfIndex =
19060 		    ill->ill_phyint->phyint_ifindex;
19061 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19062 		    ipst->ips_ipv6_forward ? 1 : 2);
19063 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19064 		    ill->ill_max_hops);
19065 
19066 		/*
19067 		 * Synchronize 64- and 32-bit counters
19068 		 */
19069 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19070 		    ipIfStatsHCInReceives);
19071 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19072 		    ipIfStatsHCInDelivers);
19073 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19074 		    ipIfStatsHCOutRequests);
19075 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19076 		    ipIfStatsHCOutForwDatagrams);
19077 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19078 		    ipIfStatsHCOutMcastPkts);
19079 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19080 		    ipIfStatsHCInMcastPkts);
19081 
19082 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19083 		    (char *)ill->ill_ip_mib,
19084 		    (int)sizeof (*ill->ill_ip_mib))) {
19085 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19086 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
19087 		}
19088 	}
19089 	rw_exit(&ipst->ips_ill_g_lock);
19090 
19091 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19092 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19093 	    (int)optp->level, (int)optp->name, (int)optp->len));
19094 	qreply(q, mpctl);
19095 	return (mp2ctl);
19096 }
19097 
19098 /*
19099  * ICMPv6 mib: One per ill
19100  */
19101 static mblk_t *
19102 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19103 {
19104 	struct opthdr		*optp;
19105 	mblk_t			*mp2ctl;
19106 	ill_t			*ill;
19107 	ill_walk_context_t	ctx;
19108 	mblk_t			*mp_tail = NULL;
19109 	/*
19110 	 * Make a copy of the original message
19111 	 */
19112 	mp2ctl = copymsg(mpctl);
19113 
19114 	/* fixed length ICMPv6 structure ... */
19115 
19116 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19117 	optp->level = MIB2_ICMP6;
19118 	optp->name = 0;
19119 	/* Include "unknown interface" icmp6_mib */
19120 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19121 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19122 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19123 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19124 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19125 	    (char *)&ipst->ips_icmp6_mib,
19126 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19127 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19128 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19129 	}
19130 
19131 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19132 	ill = ILL_START_WALK_V6(&ctx, ipst);
19133 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19134 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19135 		    ill->ill_phyint->phyint_ifindex;
19136 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19137 		    (char *)ill->ill_icmp6_mib,
19138 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19139 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19140 			    "%u bytes\n",
19141 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19142 		}
19143 	}
19144 	rw_exit(&ipst->ips_ill_g_lock);
19145 
19146 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19147 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19148 	    (int)optp->level, (int)optp->name, (int)optp->len));
19149 	qreply(q, mpctl);
19150 	return (mp2ctl);
19151 }
19152 
19153 /*
19154  * ire_walk routine to create both ipRouteEntryTable and
19155  * ipRouteAttributeTable in one IRE walk
19156  */
19157 static void
19158 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19159 {
19160 	ill_t				*ill;
19161 	ipif_t				*ipif;
19162 	mib2_ipRouteEntry_t		*re;
19163 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19164 	ipaddr_t			gw_addr;
19165 	tsol_ire_gw_secattr_t		*attrp;
19166 	tsol_gc_t			*gc = NULL;
19167 	tsol_gcgrp_t			*gcgrp = NULL;
19168 	uint_t				sacnt = 0;
19169 	int				i;
19170 
19171 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19172 
19173 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19174 		return;
19175 
19176 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19177 		mutex_enter(&attrp->igsa_lock);
19178 		if ((gc = attrp->igsa_gc) != NULL) {
19179 			gcgrp = gc->gc_grp;
19180 			ASSERT(gcgrp != NULL);
19181 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19182 			sacnt = 1;
19183 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19184 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19185 			gc = gcgrp->gcgrp_head;
19186 			sacnt = gcgrp->gcgrp_count;
19187 		}
19188 		mutex_exit(&attrp->igsa_lock);
19189 
19190 		/* do nothing if there's no gc to report */
19191 		if (gc == NULL) {
19192 			ASSERT(sacnt == 0);
19193 			if (gcgrp != NULL) {
19194 				/* we might as well drop the lock now */
19195 				rw_exit(&gcgrp->gcgrp_rwlock);
19196 				gcgrp = NULL;
19197 			}
19198 			attrp = NULL;
19199 		}
19200 
19201 		ASSERT(gc == NULL || (gcgrp != NULL &&
19202 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19203 	}
19204 	ASSERT(sacnt == 0 || gc != NULL);
19205 
19206 	if (sacnt != 0 &&
19207 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19208 		kmem_free(re, sizeof (*re));
19209 		rw_exit(&gcgrp->gcgrp_rwlock);
19210 		return;
19211 	}
19212 
19213 	/*
19214 	 * Return all IRE types for route table... let caller pick and choose
19215 	 */
19216 	re->ipRouteDest = ire->ire_addr;
19217 	ipif = ire->ire_ipif;
19218 	re->ipRouteIfIndex.o_length = 0;
19219 	if (ire->ire_type == IRE_CACHE) {
19220 		ill = (ill_t *)ire->ire_stq->q_ptr;
19221 		re->ipRouteIfIndex.o_length =
19222 		    ill->ill_name_length == 0 ? 0 :
19223 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19224 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19225 		    re->ipRouteIfIndex.o_length);
19226 	} else if (ipif != NULL) {
19227 		ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
19228 		re->ipRouteIfIndex.o_length =
19229 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19230 	}
19231 	re->ipRouteMetric1 = -1;
19232 	re->ipRouteMetric2 = -1;
19233 	re->ipRouteMetric3 = -1;
19234 	re->ipRouteMetric4 = -1;
19235 
19236 	gw_addr = ire->ire_gateway_addr;
19237 
19238 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19239 		re->ipRouteNextHop = ire->ire_src_addr;
19240 	else
19241 		re->ipRouteNextHop = gw_addr;
19242 	/* indirect(4), direct(3), or invalid(2) */
19243 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19244 		re->ipRouteType = 2;
19245 	else
19246 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19247 	re->ipRouteProto = -1;
19248 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19249 	re->ipRouteMask = ire->ire_mask;
19250 	re->ipRouteMetric5 = -1;
19251 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19252 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19253 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19254 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19255 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19256 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19257 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19258 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19259 
19260 	if (ire->ire_flags & RTF_DYNAMIC) {
19261 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19262 	} else {
19263 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19264 	}
19265 
19266 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19267 	    (char *)re, (int)sizeof (*re))) {
19268 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19269 		    (uint_t)sizeof (*re)));
19270 	}
19271 
19272 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19273 		iaeptr->iae_routeidx = ird->ird_idx;
19274 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19275 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19276 	}
19277 
19278 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19279 	    (char *)iae, sacnt * sizeof (*iae))) {
19280 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19281 		    (unsigned)(sacnt * sizeof (*iae))));
19282 	}
19283 
19284 	/* bump route index for next pass */
19285 	ird->ird_idx++;
19286 
19287 	kmem_free(re, sizeof (*re));
19288 	if (sacnt != 0)
19289 		kmem_free(iae, sacnt * sizeof (*iae));
19290 
19291 	if (gcgrp != NULL)
19292 		rw_exit(&gcgrp->gcgrp_rwlock);
19293 }
19294 
19295 /*
19296  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19297  */
19298 static void
19299 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19300 {
19301 	ill_t				*ill;
19302 	ipif_t				*ipif;
19303 	mib2_ipv6RouteEntry_t		*re;
19304 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19305 	in6_addr_t			gw_addr_v6;
19306 	tsol_ire_gw_secattr_t		*attrp;
19307 	tsol_gc_t			*gc = NULL;
19308 	tsol_gcgrp_t			*gcgrp = NULL;
19309 	uint_t				sacnt = 0;
19310 	int				i;
19311 
19312 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19313 
19314 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19315 		return;
19316 
19317 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19318 		mutex_enter(&attrp->igsa_lock);
19319 		if ((gc = attrp->igsa_gc) != NULL) {
19320 			gcgrp = gc->gc_grp;
19321 			ASSERT(gcgrp != NULL);
19322 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19323 			sacnt = 1;
19324 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19325 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19326 			gc = gcgrp->gcgrp_head;
19327 			sacnt = gcgrp->gcgrp_count;
19328 		}
19329 		mutex_exit(&attrp->igsa_lock);
19330 
19331 		/* do nothing if there's no gc to report */
19332 		if (gc == NULL) {
19333 			ASSERT(sacnt == 0);
19334 			if (gcgrp != NULL) {
19335 				/* we might as well drop the lock now */
19336 				rw_exit(&gcgrp->gcgrp_rwlock);
19337 				gcgrp = NULL;
19338 			}
19339 			attrp = NULL;
19340 		}
19341 
19342 		ASSERT(gc == NULL || (gcgrp != NULL &&
19343 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19344 	}
19345 	ASSERT(sacnt == 0 || gc != NULL);
19346 
19347 	if (sacnt != 0 &&
19348 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19349 		kmem_free(re, sizeof (*re));
19350 		rw_exit(&gcgrp->gcgrp_rwlock);
19351 		return;
19352 	}
19353 
19354 	/*
19355 	 * Return all IRE types for route table... let caller pick and choose
19356 	 */
19357 	re->ipv6RouteDest = ire->ire_addr_v6;
19358 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19359 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19360 	re->ipv6RouteIfIndex.o_length = 0;
19361 	ipif = ire->ire_ipif;
19362 	if (ire->ire_type == IRE_CACHE) {
19363 		ill = (ill_t *)ire->ire_stq->q_ptr;
19364 		re->ipv6RouteIfIndex.o_length =
19365 		    ill->ill_name_length == 0 ? 0 :
19366 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19367 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19368 		    re->ipv6RouteIfIndex.o_length);
19369 	} else if (ipif != NULL) {
19370 		ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
19371 		re->ipv6RouteIfIndex.o_length =
19372 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19373 	}
19374 
19375 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19376 
19377 	mutex_enter(&ire->ire_lock);
19378 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19379 	mutex_exit(&ire->ire_lock);
19380 
19381 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19382 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19383 	else
19384 		re->ipv6RouteNextHop = gw_addr_v6;
19385 
19386 	/* remote(4), local(3), or discard(2) */
19387 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19388 		re->ipv6RouteType = 2;
19389 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19390 		re->ipv6RouteType = 3;
19391 	else
19392 		re->ipv6RouteType = 4;
19393 
19394 	re->ipv6RouteProtocol	= -1;
19395 	re->ipv6RoutePolicy	= 0;
19396 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19397 	re->ipv6RouteNextHopRDI	= 0;
19398 	re->ipv6RouteWeight	= 0;
19399 	re->ipv6RouteMetric	= 0;
19400 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19401 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19402 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19403 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19404 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19405 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19406 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19407 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19408 
19409 	if (ire->ire_flags & RTF_DYNAMIC) {
19410 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19411 	} else {
19412 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19413 	}
19414 
19415 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19416 	    (char *)re, (int)sizeof (*re))) {
19417 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19418 		    (uint_t)sizeof (*re)));
19419 	}
19420 
19421 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19422 		iaeptr->iae_routeidx = ird->ird_idx;
19423 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19424 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19425 	}
19426 
19427 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19428 	    (char *)iae, sacnt * sizeof (*iae))) {
19429 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19430 		    (unsigned)(sacnt * sizeof (*iae))));
19431 	}
19432 
19433 	/* bump route index for next pass */
19434 	ird->ird_idx++;
19435 
19436 	kmem_free(re, sizeof (*re));
19437 	if (sacnt != 0)
19438 		kmem_free(iae, sacnt * sizeof (*iae));
19439 
19440 	if (gcgrp != NULL)
19441 		rw_exit(&gcgrp->gcgrp_rwlock);
19442 }
19443 
19444 /*
19445  * ndp_walk routine to create ipv6NetToMediaEntryTable
19446  */
19447 static int
19448 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19449 {
19450 	ill_t				*ill;
19451 	mib2_ipv6NetToMediaEntry_t	ntme;
19452 	dl_unitdata_req_t		*dl;
19453 
19454 	ill = nce->nce_ill;
19455 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19456 		return (0);
19457 
19458 	/*
19459 	 * Neighbor cache entry attached to IRE with on-link
19460 	 * destination.
19461 	 */
19462 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19463 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19464 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19465 	    (nce->nce_res_mp != NULL)) {
19466 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19467 		ntme.ipv6NetToMediaPhysAddress.o_length =
19468 		    dl->dl_dest_addr_length;
19469 	} else {
19470 		ntme.ipv6NetToMediaPhysAddress.o_length =
19471 		    ill->ill_phys_addr_length;
19472 	}
19473 	if (nce->nce_res_mp != NULL) {
19474 		bcopy((char *)nce->nce_res_mp->b_rptr +
19475 		    NCE_LL_ADDR_OFFSET(ill),
19476 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19477 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19478 	} else {
19479 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19480 		    ill->ill_phys_addr_length);
19481 	}
19482 	/*
19483 	 * Note: Returns ND_* states. Should be:
19484 	 * reachable(1), stale(2), delay(3), probe(4),
19485 	 * invalid(5), unknown(6)
19486 	 */
19487 	ntme.ipv6NetToMediaState = nce->nce_state;
19488 	ntme.ipv6NetToMediaLastUpdated = 0;
19489 
19490 	/* other(1), dynamic(2), static(3), local(4) */
19491 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19492 		ntme.ipv6NetToMediaType = 4;
19493 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19494 		ntme.ipv6NetToMediaType = 1;
19495 	} else {
19496 		ntme.ipv6NetToMediaType = 2;
19497 	}
19498 
19499 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19500 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19501 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19502 		    (uint_t)sizeof (ntme)));
19503 	}
19504 	return (0);
19505 }
19506 
19507 /*
19508  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19509  */
19510 /* ARGSUSED */
19511 int
19512 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19513 {
19514 	switch (level) {
19515 	case MIB2_IP:
19516 	case MIB2_ICMP:
19517 		switch (name) {
19518 		default:
19519 			break;
19520 		}
19521 		return (1);
19522 	default:
19523 		return (1);
19524 	}
19525 }
19526 
19527 /*
19528  * When there exists both a 64- and 32-bit counter of a particular type
19529  * (i.e., InReceives), only the 64-bit counters are added.
19530  */
19531 void
19532 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19533 {
19534 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19535 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19536 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19537 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19538 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19539 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19540 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19541 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19542 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19543 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19544 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19545 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19546 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19547 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19548 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
19549 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
19550 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
19551 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
19552 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
19553 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
19554 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
19555 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
19556 	    o2->ipIfStatsInWrongIPVersion);
19557 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
19558 	    o2->ipIfStatsInWrongIPVersion);
19559 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
19560 	    o2->ipIfStatsOutSwitchIPVersion);
19561 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
19562 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
19563 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
19564 	    o2->ipIfStatsHCInForwDatagrams);
19565 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
19566 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
19567 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
19568 	    o2->ipIfStatsHCOutForwDatagrams);
19569 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
19570 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
19571 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
19572 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
19573 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
19574 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
19575 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
19576 	    o2->ipIfStatsHCOutMcastOctets);
19577 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
19578 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
19579 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
19580 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
19581 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
19582 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
19583 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
19584 }
19585 
19586 void
19587 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
19588 {
19589 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
19590 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
19591 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
19592 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
19593 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
19594 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
19595 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
19596 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
19597 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
19598 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
19599 	    o2->ipv6IfIcmpInRouterSolicits);
19600 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
19601 	    o2->ipv6IfIcmpInRouterAdvertisements);
19602 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
19603 	    o2->ipv6IfIcmpInNeighborSolicits);
19604 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
19605 	    o2->ipv6IfIcmpInNeighborAdvertisements);
19606 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
19607 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
19608 	    o2->ipv6IfIcmpInGroupMembQueries);
19609 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
19610 	    o2->ipv6IfIcmpInGroupMembResponses);
19611 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
19612 	    o2->ipv6IfIcmpInGroupMembReductions);
19613 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
19614 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
19615 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
19616 	    o2->ipv6IfIcmpOutDestUnreachs);
19617 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
19618 	    o2->ipv6IfIcmpOutAdminProhibs);
19619 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
19620 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
19621 	    o2->ipv6IfIcmpOutParmProblems);
19622 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
19623 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
19624 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
19625 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
19626 	    o2->ipv6IfIcmpOutRouterSolicits);
19627 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
19628 	    o2->ipv6IfIcmpOutRouterAdvertisements);
19629 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
19630 	    o2->ipv6IfIcmpOutNeighborSolicits);
19631 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
19632 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
19633 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
19634 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
19635 	    o2->ipv6IfIcmpOutGroupMembQueries);
19636 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
19637 	    o2->ipv6IfIcmpOutGroupMembResponses);
19638 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
19639 	    o2->ipv6IfIcmpOutGroupMembReductions);
19640 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
19641 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
19642 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
19643 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
19644 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
19645 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
19646 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
19647 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
19648 	    o2->ipv6IfIcmpInGroupMembTotal);
19649 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
19650 	    o2->ipv6IfIcmpInGroupMembBadQueries);
19651 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
19652 	    o2->ipv6IfIcmpInGroupMembBadReports);
19653 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
19654 	    o2->ipv6IfIcmpInGroupMembOurReports);
19655 }
19656 
19657 /*
19658  * Called before the options are updated to check if this packet will
19659  * be source routed from here.
19660  * This routine assumes that the options are well formed i.e. that they
19661  * have already been checked.
19662  */
19663 static boolean_t
19664 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
19665 {
19666 	ipoptp_t	opts;
19667 	uchar_t		*opt;
19668 	uint8_t		optval;
19669 	uint8_t		optlen;
19670 	ipaddr_t	dst;
19671 	ire_t		*ire;
19672 
19673 	if (IS_SIMPLE_IPH(ipha)) {
19674 		ip2dbg(("not source routed\n"));
19675 		return (B_FALSE);
19676 	}
19677 	dst = ipha->ipha_dst;
19678 	for (optval = ipoptp_first(&opts, ipha);
19679 	    optval != IPOPT_EOL;
19680 	    optval = ipoptp_next(&opts)) {
19681 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19682 		opt = opts.ipoptp_cur;
19683 		optlen = opts.ipoptp_len;
19684 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19685 		    optval, optlen));
19686 		switch (optval) {
19687 			uint32_t off;
19688 		case IPOPT_SSRR:
19689 		case IPOPT_LSRR:
19690 			/*
19691 			 * If dst is one of our addresses and there are some
19692 			 * entries left in the source route return (true).
19693 			 */
19694 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19695 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
19696 			if (ire == NULL) {
19697 				ip2dbg(("ip_source_routed: not next"
19698 				    " source route 0x%x\n",
19699 				    ntohl(dst)));
19700 				return (B_FALSE);
19701 			}
19702 			ire_refrele(ire);
19703 			off = opt[IPOPT_OFFSET];
19704 			off--;
19705 			if (optlen < IP_ADDR_LEN ||
19706 			    off > optlen - IP_ADDR_LEN) {
19707 				/* End of source route */
19708 				ip1dbg(("ip_source_routed: end of SR\n"));
19709 				return (B_FALSE);
19710 			}
19711 			return (B_TRUE);
19712 		}
19713 	}
19714 	ip2dbg(("not source routed\n"));
19715 	return (B_FALSE);
19716 }
19717 
19718 /*
19719  * Check if the packet contains any source route.
19720  */
19721 static boolean_t
19722 ip_source_route_included(ipha_t *ipha)
19723 {
19724 	ipoptp_t	opts;
19725 	uint8_t		optval;
19726 
19727 	if (IS_SIMPLE_IPH(ipha))
19728 		return (B_FALSE);
19729 	for (optval = ipoptp_first(&opts, ipha);
19730 	    optval != IPOPT_EOL;
19731 	    optval = ipoptp_next(&opts)) {
19732 		switch (optval) {
19733 		case IPOPT_SSRR:
19734 		case IPOPT_LSRR:
19735 			return (B_TRUE);
19736 		}
19737 	}
19738 	return (B_FALSE);
19739 }
19740 
19741 /*
19742  * Called when the IRE expiration timer fires.
19743  */
19744 void
19745 ip_trash_timer_expire(void *args)
19746 {
19747 	int			flush_flag = 0;
19748 	ire_expire_arg_t	iea;
19749 	ip_stack_t		*ipst = (ip_stack_t *)args;
19750 
19751 	iea.iea_ipst = ipst;	/* No netstack_hold */
19752 
19753 	/*
19754 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
19755 	 * This lock makes sure that a new invocation of this function
19756 	 * that occurs due to an almost immediate timer firing will not
19757 	 * progress beyond this point until the current invocation is done
19758 	 */
19759 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19760 	ipst->ips_ip_ire_expire_id = 0;
19761 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19762 
19763 	/* Periodic timer */
19764 	if (ipst->ips_ip_ire_arp_time_elapsed >=
19765 	    ipst->ips_ip_ire_arp_interval) {
19766 		/*
19767 		 * Remove all IRE_CACHE entries since they might
19768 		 * contain arp information.
19769 		 */
19770 		flush_flag |= FLUSH_ARP_TIME;
19771 		ipst->ips_ip_ire_arp_time_elapsed = 0;
19772 		IP_STAT(ipst, ip_ire_arp_timer_expired);
19773 	}
19774 	if (ipst->ips_ip_ire_rd_time_elapsed >=
19775 	    ipst->ips_ip_ire_redir_interval) {
19776 		/* Remove all redirects */
19777 		flush_flag |= FLUSH_REDIRECT_TIME;
19778 		ipst->ips_ip_ire_rd_time_elapsed = 0;
19779 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
19780 	}
19781 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
19782 	    ipst->ips_ip_ire_pathmtu_interval) {
19783 		/* Increase path mtu */
19784 		flush_flag |= FLUSH_MTU_TIME;
19785 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
19786 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
19787 	}
19788 
19789 	/*
19790 	 * Optimize for the case when there are no redirects in the
19791 	 * ftable, that is, no need to walk the ftable in that case.
19792 	 */
19793 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
19794 		iea.iea_flush_flag = flush_flag;
19795 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
19796 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
19797 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
19798 		    NULL, ALL_ZONES, ipst);
19799 	}
19800 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
19801 	    ipst->ips_ip_redirect_cnt > 0) {
19802 		iea.iea_flush_flag = flush_flag;
19803 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
19804 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
19805 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
19806 	}
19807 	if (flush_flag & FLUSH_MTU_TIME) {
19808 		/*
19809 		 * Walk all IPv6 IRE's and update them
19810 		 * Note that ARP and redirect timers are not
19811 		 * needed since NUD handles stale entries.
19812 		 */
19813 		flush_flag = FLUSH_MTU_TIME;
19814 		iea.iea_flush_flag = flush_flag;
19815 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
19816 		    ALL_ZONES, ipst);
19817 	}
19818 
19819 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
19820 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
19821 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
19822 
19823 	/*
19824 	 * Hold the lock to serialize timeout calls and prevent
19825 	 * stale values in ip_ire_expire_id. Otherwise it is possible
19826 	 * for the timer to fire and a new invocation of this function
19827 	 * to start before the return value of timeout has been stored
19828 	 * in ip_ire_expire_id by the current invocation.
19829 	 */
19830 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19831 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
19832 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
19833 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19834 }
19835 
19836 /*
19837  * Called by the memory allocator subsystem directly, when the system
19838  * is running low on memory.
19839  */
19840 /* ARGSUSED */
19841 void
19842 ip_trash_ire_reclaim(void *args)
19843 {
19844 	netstack_handle_t nh;
19845 	netstack_t *ns;
19846 
19847 	netstack_next_init(&nh);
19848 	while ((ns = netstack_next(&nh)) != NULL) {
19849 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
19850 		netstack_rele(ns);
19851 	}
19852 	netstack_next_fini(&nh);
19853 }
19854 
19855 static void
19856 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
19857 {
19858 	ire_cache_count_t icc;
19859 	ire_cache_reclaim_t icr;
19860 	ncc_cache_count_t ncc;
19861 	nce_cache_reclaim_t ncr;
19862 	uint_t delete_cnt;
19863 	/*
19864 	 * Memory reclaim call back.
19865 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
19866 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
19867 	 * entries, determine what fraction to free for
19868 	 * each category of IRE_CACHE entries giving absolute priority
19869 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
19870 	 * entry will be freed unless all offlink entries are freed).
19871 	 */
19872 	icc.icc_total = 0;
19873 	icc.icc_unused = 0;
19874 	icc.icc_offlink = 0;
19875 	icc.icc_pmtu = 0;
19876 	icc.icc_onlink = 0;
19877 	ire_walk(ire_cache_count, (char *)&icc, ipst);
19878 
19879 	/*
19880 	 * Free NCEs for IPv6 like the onlink ires.
19881 	 */
19882 	ncc.ncc_total = 0;
19883 	ncc.ncc_host = 0;
19884 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
19885 
19886 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
19887 	    icc.icc_pmtu + icc.icc_onlink);
19888 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
19889 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
19890 	if (delete_cnt == 0)
19891 		return;
19892 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
19893 	/* Always delete all unused offlink entries */
19894 	icr.icr_ipst = ipst;
19895 	icr.icr_unused = 1;
19896 	if (delete_cnt <= icc.icc_unused) {
19897 		/*
19898 		 * Only need to free unused entries.  In other words,
19899 		 * there are enough unused entries to free to meet our
19900 		 * target number of freed ire cache entries.
19901 		 */
19902 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
19903 		ncr.ncr_host = 0;
19904 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
19905 		/*
19906 		 * Only need to free unused entries, plus a fraction of offlink
19907 		 * entries.  It follows from the first if statement that
19908 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
19909 		 */
19910 		delete_cnt -= icc.icc_unused;
19911 		/* Round up # deleted by truncating fraction */
19912 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
19913 		icr.icr_pmtu = icr.icr_onlink = 0;
19914 		ncr.ncr_host = 0;
19915 	} else if (delete_cnt <=
19916 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
19917 		/*
19918 		 * Free all unused and offlink entries, plus a fraction of
19919 		 * pmtu entries.  It follows from the previous if statement
19920 		 * that icc_pmtu is non-zero, and that
19921 		 * delete_cnt != icc_unused + icc_offlink.
19922 		 */
19923 		icr.icr_offlink = 1;
19924 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
19925 		/* Round up # deleted by truncating fraction */
19926 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
19927 		icr.icr_onlink = 0;
19928 		ncr.ncr_host = 0;
19929 	} else {
19930 		/*
19931 		 * Free all unused, offlink, and pmtu entries, plus a fraction
19932 		 * of onlink entries.  If we're here, then we know that
19933 		 * icc_onlink is non-zero, and that
19934 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
19935 		 */
19936 		icr.icr_offlink = icr.icr_pmtu = 1;
19937 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
19938 		    icc.icc_pmtu;
19939 		/* Round up # deleted by truncating fraction */
19940 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
19941 		/* Using the same delete fraction as for onlink IREs */
19942 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
19943 	}
19944 #ifdef DEBUG
19945 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
19946 	    "fractions %d/%d/%d/%d\n",
19947 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
19948 	    icc.icc_unused, icc.icc_offlink,
19949 	    icc.icc_pmtu, icc.icc_onlink,
19950 	    icr.icr_unused, icr.icr_offlink,
19951 	    icr.icr_pmtu, icr.icr_onlink));
19952 #endif
19953 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
19954 	if (ncr.ncr_host != 0)
19955 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
19956 		    (uchar_t *)&ncr, ipst);
19957 #ifdef DEBUG
19958 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
19959 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
19960 	ire_walk(ire_cache_count, (char *)&icc, ipst);
19961 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
19962 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
19963 	    icc.icc_pmtu, icc.icc_onlink));
19964 #endif
19965 }
19966 
19967 /*
19968  * ip_unbind is called when a copy of an unbind request is received from the
19969  * upper level protocol.  We remove this conn from any fanout hash list it is
19970  * on, and zero out the bind information.  No reply is expected up above.
19971  */
19972 mblk_t *
19973 ip_unbind(queue_t *q, mblk_t *mp)
19974 {
19975 	conn_t	*connp = Q_TO_CONN(q);
19976 
19977 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
19978 
19979 	if (is_system_labeled() && connp->conn_anon_port) {
19980 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
19981 		    connp->conn_mlp_type, connp->conn_ulp,
19982 		    ntohs(connp->conn_lport), B_FALSE);
19983 		connp->conn_anon_port = 0;
19984 	}
19985 	connp->conn_mlp_type = mlptSingle;
19986 
19987 	ipcl_hash_remove(connp);
19988 
19989 	ASSERT(mp->b_cont == NULL);
19990 	/*
19991 	 * Convert mp into a T_OK_ACK
19992 	 */
19993 	mp = mi_tpi_ok_ack_alloc(mp);
19994 
19995 	/*
19996 	 * should not happen in practice... T_OK_ACK is smaller than the
19997 	 * original message.
19998 	 */
19999 	if (mp == NULL)
20000 		return (NULL);
20001 
20002 	return (mp);
20003 }
20004 
20005 /*
20006  * Write side put procedure.  Outbound data, IOCTLs, responses from
20007  * resolvers, etc, come down through here.
20008  *
20009  * arg2 is always a queue_t *.
20010  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
20011  * the zoneid.
20012  * When that queue is not an ill_t, then arg must be a conn_t pointer.
20013  */
20014 void
20015 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
20016 {
20017 	ip_output_options(arg, mp, arg2, caller, &zero_info);
20018 }
20019 
20020 void
20021 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20022     ip_opt_info_t *infop)
20023 {
20024 	conn_t		*connp = NULL;
20025 	queue_t		*q = (queue_t *)arg2;
20026 	ipha_t		*ipha;
20027 #define	rptr	((uchar_t *)ipha)
20028 	ire_t		*ire = NULL;
20029 	ire_t		*sctp_ire = NULL;
20030 	uint32_t	v_hlen_tos_len;
20031 	ipaddr_t	dst;
20032 	mblk_t		*first_mp = NULL;
20033 	boolean_t	mctl_present;
20034 	ipsec_out_t	*io;
20035 	int		match_flags;
20036 	ill_t		*attach_ill = NULL;
20037 					/* Bind to IPIF_NOFAILOVER ill etc. */
20038 	ill_t		*xmit_ill = NULL;	/* IP_PKTINFO etc. */
20039 	ipif_t		*dst_ipif;
20040 	boolean_t	multirt_need_resolve = B_FALSE;
20041 	mblk_t		*copy_mp = NULL;
20042 	int		err;
20043 	zoneid_t	zoneid;
20044 	int	adjust;
20045 	uint16_t iplen;
20046 	boolean_t	need_decref = B_FALSE;
20047 	boolean_t	ignore_dontroute = B_FALSE;
20048 	boolean_t	ignore_nexthop = B_FALSE;
20049 	boolean_t	ip_nexthop = B_FALSE;
20050 	ipaddr_t	nexthop_addr;
20051 	ip_stack_t	*ipst;
20052 
20053 #ifdef	_BIG_ENDIAN
20054 #define	V_HLEN	(v_hlen_tos_len >> 24)
20055 #else
20056 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20057 #endif
20058 
20059 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20060 	    "ip_wput_start: q %p", q);
20061 
20062 	/*
20063 	 * ip_wput fast path
20064 	 */
20065 
20066 	/* is packet from ARP ? */
20067 	if (q->q_next != NULL) {
20068 		zoneid = (zoneid_t)(uintptr_t)arg;
20069 		goto qnext;
20070 	}
20071 
20072 	connp = (conn_t *)arg;
20073 	ASSERT(connp != NULL);
20074 	zoneid = connp->conn_zoneid;
20075 	ipst = connp->conn_netstack->netstack_ip;
20076 
20077 	/* is queue flow controlled? */
20078 	if ((q->q_first != NULL || connp->conn_draining) &&
20079 	    (caller == IP_WPUT)) {
20080 		ASSERT(!need_decref);
20081 		(void) putq(q, mp);
20082 		return;
20083 	}
20084 
20085 	/* Multidata transmit? */
20086 	if (DB_TYPE(mp) == M_MULTIDATA) {
20087 		/*
20088 		 * We should never get here, since all Multidata messages
20089 		 * originating from tcp should have been directed over to
20090 		 * tcp_multisend() in the first place.
20091 		 */
20092 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20093 		freemsg(mp);
20094 		return;
20095 	} else if (DB_TYPE(mp) != M_DATA)
20096 		goto notdata;
20097 
20098 	if (mp->b_flag & MSGHASREF) {
20099 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20100 		mp->b_flag &= ~MSGHASREF;
20101 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20102 		need_decref = B_TRUE;
20103 	}
20104 	ipha = (ipha_t *)mp->b_rptr;
20105 
20106 	/* is IP header non-aligned or mblk smaller than basic IP header */
20107 #ifndef SAFETY_BEFORE_SPEED
20108 	if (!OK_32PTR(rptr) ||
20109 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20110 		goto hdrtoosmall;
20111 #endif
20112 
20113 	ASSERT(OK_32PTR(ipha));
20114 
20115 	/*
20116 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20117 	 * wrong version, we'll catch it again in ip_output_v6.
20118 	 *
20119 	 * Note that this is *only* locally-generated output here, and never
20120 	 * forwarded data, and that we need to deal only with transports that
20121 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20122 	 * label.)
20123 	 */
20124 	if (is_system_labeled() &&
20125 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20126 	    !connp->conn_ulp_labeled) {
20127 		err = tsol_check_label(BEST_CRED(mp, connp), &mp, &adjust,
20128 		    connp->conn_mac_exempt, ipst);
20129 		ipha = (ipha_t *)mp->b_rptr;
20130 		if (err != 0) {
20131 			first_mp = mp;
20132 			if (err == EINVAL)
20133 				goto icmp_parameter_problem;
20134 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20135 			goto discard_pkt;
20136 		}
20137 		iplen = ntohs(ipha->ipha_length) + adjust;
20138 		ipha->ipha_length = htons(iplen);
20139 	}
20140 
20141 	ASSERT(infop != NULL);
20142 
20143 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20144 		/*
20145 		 * IP_PKTINFO ancillary option is present.
20146 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20147 		 * allows using address of any zone as the source address.
20148 		 */
20149 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20150 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20151 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20152 		if (ire == NULL)
20153 			goto drop_pkt;
20154 		ire_refrele(ire);
20155 		ire = NULL;
20156 	}
20157 
20158 	/*
20159 	 * IP_DONTFAILOVER_IF and IP_BOUND_IF have precedence over ill index
20160 	 * passed in IP_PKTINFO.
20161 	 */
20162 	if (infop->ip_opt_ill_index != 0 &&
20163 	    connp->conn_outgoing_ill == NULL &&
20164 	    connp->conn_nofailover_ill == NULL) {
20165 
20166 		xmit_ill = ill_lookup_on_ifindex(
20167 		    infop->ip_opt_ill_index, B_FALSE, NULL, NULL, NULL, NULL,
20168 		    ipst);
20169 
20170 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20171 			goto drop_pkt;
20172 		/*
20173 		 * check that there is an ipif belonging
20174 		 * to our zone. IPCL_ZONEID is not used because
20175 		 * IP_ALLZONES option is valid only when the ill is
20176 		 * accessible from all zones i.e has a valid ipif in
20177 		 * all zones.
20178 		 */
20179 		if (!ipif_lookup_zoneid_group(xmit_ill, zoneid, 0, NULL)) {
20180 			goto drop_pkt;
20181 		}
20182 	}
20183 
20184 	/*
20185 	 * If there is a policy, try to attach an ipsec_out in
20186 	 * the front. At the end, first_mp either points to a
20187 	 * M_DATA message or IPSEC_OUT message linked to a
20188 	 * M_DATA message. We have to do it now as we might
20189 	 * lose the "conn" if we go through ip_newroute.
20190 	 */
20191 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20192 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
20193 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20194 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20195 			if (need_decref)
20196 				CONN_DEC_REF(connp);
20197 			return;
20198 		} else {
20199 			ASSERT(mp->b_datap->db_type == M_CTL);
20200 			first_mp = mp;
20201 			mp = mp->b_cont;
20202 			mctl_present = B_TRUE;
20203 		}
20204 	} else {
20205 		first_mp = mp;
20206 		mctl_present = B_FALSE;
20207 	}
20208 
20209 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20210 
20211 	/* is wrong version or IP options present */
20212 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20213 		goto version_hdrlen_check;
20214 	dst = ipha->ipha_dst;
20215 
20216 	if (connp->conn_nofailover_ill != NULL) {
20217 		attach_ill = conn_get_held_ill(connp,
20218 		    &connp->conn_nofailover_ill, &err);
20219 		if (err == ILL_LOOKUP_FAILED) {
20220 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20221 			if (need_decref)
20222 				CONN_DEC_REF(connp);
20223 			freemsg(first_mp);
20224 			return;
20225 		}
20226 	}
20227 
20228 	/* If IP_BOUND_IF has been set, use that ill. */
20229 	if (connp->conn_outgoing_ill != NULL) {
20230 		xmit_ill = conn_get_held_ill(connp,
20231 		    &connp->conn_outgoing_ill, &err);
20232 		if (err == ILL_LOOKUP_FAILED)
20233 			goto drop_pkt;
20234 
20235 		goto send_from_ill;
20236 	}
20237 
20238 	/* is packet multicast? */
20239 	if (CLASSD(dst))
20240 		goto multicast;
20241 
20242 	/*
20243 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20244 	 * takes precedence over conn_dontroute and conn_nexthop_set
20245 	 */
20246 	if (xmit_ill != NULL)
20247 		goto send_from_ill;
20248 
20249 	if (connp->conn_dontroute || connp->conn_nexthop_set) {
20250 		/*
20251 		 * If the destination is a broadcast, local, or loopback
20252 		 * address, SO_DONTROUTE and IP_NEXTHOP go through the
20253 		 * standard path.
20254 		 */
20255 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20256 		if ((ire == NULL) || (ire->ire_type &
20257 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK)) == 0) {
20258 			if (ire != NULL) {
20259 				ire_refrele(ire);
20260 				/* No more access to ire */
20261 				ire = NULL;
20262 			}
20263 			/*
20264 			 * bypass routing checks and go directly to interface.
20265 			 */
20266 			if (connp->conn_dontroute)
20267 				goto dontroute;
20268 
20269 			ASSERT(connp->conn_nexthop_set);
20270 			ip_nexthop = B_TRUE;
20271 			nexthop_addr = connp->conn_nexthop_v4;
20272 			goto send_from_ill;
20273 		}
20274 
20275 		/* Must be a broadcast, a loopback or a local ire */
20276 		ire_refrele(ire);
20277 		/* No more access to ire */
20278 		ire = NULL;
20279 	}
20280 
20281 	if (attach_ill != NULL)
20282 		goto send_from_ill;
20283 
20284 	/*
20285 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20286 	 * this for the tcp global queue and listen end point
20287 	 * as it does not really have a real destination to
20288 	 * talk to.  This is also true for SCTP.
20289 	 */
20290 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20291 	    !connp->conn_fully_bound) {
20292 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20293 		if (ire == NULL)
20294 			goto noirefound;
20295 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20296 		    "ip_wput_end: q %p (%S)", q, "end");
20297 
20298 		/*
20299 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20300 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20301 		 */
20302 		if (ire->ire_flags & RTF_MULTIRT) {
20303 
20304 			/*
20305 			 * Force the TTL of multirouted packets if required.
20306 			 * The TTL of such packets is bounded by the
20307 			 * ip_multirt_ttl ndd variable.
20308 			 */
20309 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20310 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20311 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20312 				    "(was %d), dst 0x%08x\n",
20313 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20314 				    ntohl(ire->ire_addr)));
20315 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20316 			}
20317 			/*
20318 			 * We look at this point if there are pending
20319 			 * unresolved routes. ire_multirt_resolvable()
20320 			 * checks in O(n) that all IRE_OFFSUBNET ire
20321 			 * entries for the packet's destination and
20322 			 * flagged RTF_MULTIRT are currently resolved.
20323 			 * If some remain unresolved, we make a copy
20324 			 * of the current message. It will be used
20325 			 * to initiate additional route resolutions.
20326 			 */
20327 			multirt_need_resolve =
20328 			    ire_multirt_need_resolve(ire->ire_addr,
20329 			    MBLK_GETLABEL(first_mp), ipst);
20330 			ip2dbg(("ip_wput[TCP]: ire %p, "
20331 			    "multirt_need_resolve %d, first_mp %p\n",
20332 			    (void *)ire, multirt_need_resolve,
20333 			    (void *)first_mp));
20334 			if (multirt_need_resolve) {
20335 				copy_mp = copymsg(first_mp);
20336 				if (copy_mp != NULL) {
20337 					MULTIRT_DEBUG_TAG(copy_mp);
20338 				}
20339 			}
20340 		}
20341 
20342 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20343 
20344 		/*
20345 		 * Try to resolve another multiroute if
20346 		 * ire_multirt_need_resolve() deemed it necessary.
20347 		 */
20348 		if (copy_mp != NULL)
20349 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20350 		if (need_decref)
20351 			CONN_DEC_REF(connp);
20352 		return;
20353 	}
20354 
20355 	/*
20356 	 * Access to conn_ire_cache. (protected by conn_lock)
20357 	 *
20358 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20359 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20360 	 * send a packet or two with the IRE_CACHE that is going away.
20361 	 * Access to the ire requires an ire refhold on the ire prior to
20362 	 * its use since an interface unplumb thread may delete the cached
20363 	 * ire and release the refhold at any time.
20364 	 *
20365 	 * Caching an ire in the conn_ire_cache
20366 	 *
20367 	 * o Caching an ire pointer in the conn requires a strict check for
20368 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20369 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20370 	 * in the conn is done after making sure under the bucket lock that the
20371 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20372 	 * caching an ire after the unplumb thread has cleaned up the conn.
20373 	 * If the conn does not send a packet subsequently the unplumb thread
20374 	 * will be hanging waiting for the ire count to drop to zero.
20375 	 *
20376 	 * o We also need to atomically test for a null conn_ire_cache and
20377 	 * set the conn_ire_cache under the the protection of the conn_lock
20378 	 * to avoid races among concurrent threads trying to simultaneously
20379 	 * cache an ire in the conn_ire_cache.
20380 	 */
20381 	mutex_enter(&connp->conn_lock);
20382 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20383 
20384 	if (ire != NULL && ire->ire_addr == dst &&
20385 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20386 
20387 		IRE_REFHOLD(ire);
20388 		mutex_exit(&connp->conn_lock);
20389 
20390 	} else {
20391 		boolean_t cached = B_FALSE;
20392 		connp->conn_ire_cache = NULL;
20393 		mutex_exit(&connp->conn_lock);
20394 		/* Release the old ire */
20395 		if (ire != NULL && sctp_ire == NULL)
20396 			IRE_REFRELE_NOTR(ire);
20397 
20398 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20399 		if (ire == NULL)
20400 			goto noirefound;
20401 		IRE_REFHOLD_NOTR(ire);
20402 
20403 		mutex_enter(&connp->conn_lock);
20404 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20405 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20406 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20407 				if (connp->conn_ulp == IPPROTO_TCP)
20408 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20409 				connp->conn_ire_cache = ire;
20410 				cached = B_TRUE;
20411 			}
20412 			rw_exit(&ire->ire_bucket->irb_lock);
20413 		}
20414 		mutex_exit(&connp->conn_lock);
20415 
20416 		/*
20417 		 * We can continue to use the ire but since it was
20418 		 * not cached, we should drop the extra reference.
20419 		 */
20420 		if (!cached)
20421 			IRE_REFRELE_NOTR(ire);
20422 	}
20423 
20424 
20425 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20426 	    "ip_wput_end: q %p (%S)", q, "end");
20427 
20428 	/*
20429 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20430 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20431 	 */
20432 	if (ire->ire_flags & RTF_MULTIRT) {
20433 
20434 		/*
20435 		 * Force the TTL of multirouted packets if required.
20436 		 * The TTL of such packets is bounded by the
20437 		 * ip_multirt_ttl ndd variable.
20438 		 */
20439 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20440 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20441 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20442 			    "(was %d), dst 0x%08x\n",
20443 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20444 			    ntohl(ire->ire_addr)));
20445 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20446 		}
20447 
20448 		/*
20449 		 * At this point, we check to see if there are any pending
20450 		 * unresolved routes. ire_multirt_resolvable()
20451 		 * checks in O(n) that all IRE_OFFSUBNET ire
20452 		 * entries for the packet's destination and
20453 		 * flagged RTF_MULTIRT are currently resolved.
20454 		 * If some remain unresolved, we make a copy
20455 		 * of the current message. It will be used
20456 		 * to initiate additional route resolutions.
20457 		 */
20458 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20459 		    MBLK_GETLABEL(first_mp), ipst);
20460 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20461 		    "multirt_need_resolve %d, first_mp %p\n",
20462 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20463 		if (multirt_need_resolve) {
20464 			copy_mp = copymsg(first_mp);
20465 			if (copy_mp != NULL) {
20466 				MULTIRT_DEBUG_TAG(copy_mp);
20467 			}
20468 		}
20469 	}
20470 
20471 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20472 
20473 	/*
20474 	 * Try to resolve another multiroute if
20475 	 * ire_multirt_resolvable() deemed it necessary
20476 	 */
20477 	if (copy_mp != NULL)
20478 		ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20479 	if (need_decref)
20480 		CONN_DEC_REF(connp);
20481 	return;
20482 
20483 qnext:
20484 	/*
20485 	 * Upper Level Protocols pass down complete IP datagrams
20486 	 * as M_DATA messages.	Everything else is a sideshow.
20487 	 *
20488 	 * 1) We could be re-entering ip_wput because of ip_neworute
20489 	 *    in which case we could have a IPSEC_OUT message. We
20490 	 *    need to pass through ip_wput like other datagrams and
20491 	 *    hence cannot branch to ip_wput_nondata.
20492 	 *
20493 	 * 2) ARP, AH, ESP, and other clients who are on the module
20494 	 *    instance of IP stream, give us something to deal with.
20495 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20496 	 *
20497 	 * 3) ICMP replies also could come here.
20498 	 */
20499 	ipst = ILLQ_TO_IPST(q);
20500 
20501 	if (DB_TYPE(mp) != M_DATA) {
20502 notdata:
20503 		if (DB_TYPE(mp) == M_CTL) {
20504 			/*
20505 			 * M_CTL messages are used by ARP, AH and ESP to
20506 			 * communicate with IP. We deal with IPSEC_IN and
20507 			 * IPSEC_OUT here. ip_wput_nondata handles other
20508 			 * cases.
20509 			 */
20510 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20511 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20512 				first_mp = mp->b_cont;
20513 				first_mp->b_flag &= ~MSGHASREF;
20514 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20515 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20516 				CONN_DEC_REF(connp);
20517 				connp = NULL;
20518 			}
20519 			if (ii->ipsec_info_type == IPSEC_IN) {
20520 				/*
20521 				 * Either this message goes back to
20522 				 * IPsec for further processing or to
20523 				 * ULP after policy checks.
20524 				 */
20525 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20526 				return;
20527 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20528 				io = (ipsec_out_t *)ii;
20529 				if (io->ipsec_out_proc_begin) {
20530 					/*
20531 					 * IPsec processing has already started.
20532 					 * Complete it.
20533 					 * IPQoS notes: We don't care what is
20534 					 * in ipsec_out_ill_index since this
20535 					 * won't be processed for IPQoS policies
20536 					 * in ipsec_out_process.
20537 					 */
20538 					ipsec_out_process(q, mp, NULL,
20539 					    io->ipsec_out_ill_index);
20540 					return;
20541 				} else {
20542 					connp = (q->q_next != NULL) ?
20543 					    NULL : Q_TO_CONN(q);
20544 					first_mp = mp;
20545 					mp = mp->b_cont;
20546 					mctl_present = B_TRUE;
20547 				}
20548 				zoneid = io->ipsec_out_zoneid;
20549 				ASSERT(zoneid != ALL_ZONES);
20550 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20551 				/*
20552 				 * It's an IPsec control message requesting
20553 				 * an SADB update to be sent to the IPsec
20554 				 * hardware acceleration capable ills.
20555 				 */
20556 				ipsec_ctl_t *ipsec_ctl =
20557 				    (ipsec_ctl_t *)mp->b_rptr;
20558 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20559 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20560 				mblk_t *cmp = mp->b_cont;
20561 
20562 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20563 				ASSERT(cmp != NULL);
20564 
20565 				freeb(mp);
20566 				ill_ipsec_capab_send_all(satype, cmp, sa,
20567 				    ipst->ips_netstack);
20568 				return;
20569 			} else {
20570 				/*
20571 				 * This must be ARP or special TSOL signaling.
20572 				 */
20573 				ip_wput_nondata(NULL, q, mp, NULL);
20574 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20575 				    "ip_wput_end: q %p (%S)", q, "nondata");
20576 				return;
20577 			}
20578 		} else {
20579 			/*
20580 			 * This must be non-(ARP/AH/ESP) messages.
20581 			 */
20582 			ASSERT(!need_decref);
20583 			ip_wput_nondata(NULL, q, mp, NULL);
20584 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20585 			    "ip_wput_end: q %p (%S)", q, "nondata");
20586 			return;
20587 		}
20588 	} else {
20589 		first_mp = mp;
20590 		mctl_present = B_FALSE;
20591 	}
20592 
20593 	ASSERT(first_mp != NULL);
20594 	/*
20595 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
20596 	 * to make sure that this packet goes out on the same interface it
20597 	 * came in. We handle that here.
20598 	 */
20599 	if (mctl_present) {
20600 		uint_t ifindex;
20601 
20602 		io = (ipsec_out_t *)first_mp->b_rptr;
20603 		if (io->ipsec_out_attach_if || io->ipsec_out_ip_nexthop) {
20604 			/*
20605 			 * We may have lost the conn context if we are
20606 			 * coming here from ip_newroute(). Copy the
20607 			 * nexthop information.
20608 			 */
20609 			if (io->ipsec_out_ip_nexthop) {
20610 				ip_nexthop = B_TRUE;
20611 				nexthop_addr = io->ipsec_out_nexthop_addr;
20612 
20613 				ipha = (ipha_t *)mp->b_rptr;
20614 				dst = ipha->ipha_dst;
20615 				goto send_from_ill;
20616 			} else {
20617 				ASSERT(io->ipsec_out_ill_index != 0);
20618 				ifindex = io->ipsec_out_ill_index;
20619 				attach_ill = ill_lookup_on_ifindex(ifindex,
20620 				    B_FALSE, NULL, NULL, NULL, NULL, ipst);
20621 				if (attach_ill == NULL) {
20622 					ASSERT(xmit_ill == NULL);
20623 					ip1dbg(("ip_output: bad ifindex for "
20624 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
20625 					    ifindex));
20626 					freemsg(first_mp);
20627 					BUMP_MIB(&ipst->ips_ip_mib,
20628 					    ipIfStatsOutDiscards);
20629 					ASSERT(!need_decref);
20630 					return;
20631 				}
20632 			}
20633 		}
20634 	}
20635 
20636 	ASSERT(xmit_ill == NULL);
20637 
20638 	/* We have a complete IP datagram heading outbound. */
20639 	ipha = (ipha_t *)mp->b_rptr;
20640 
20641 #ifndef SPEED_BEFORE_SAFETY
20642 	/*
20643 	 * Make sure we have a full-word aligned message and that at least
20644 	 * a simple IP header is accessible in the first message.  If not,
20645 	 * try a pullup.
20646 	 */
20647 	if (!OK_32PTR(rptr) ||
20648 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
20649 hdrtoosmall:
20650 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20651 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20652 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20653 			if (first_mp == NULL)
20654 				first_mp = mp;
20655 			goto discard_pkt;
20656 		}
20657 
20658 		/* This function assumes that mp points to an IPv4 packet. */
20659 		if (is_system_labeled() && q->q_next == NULL &&
20660 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20661 		    !connp->conn_ulp_labeled) {
20662 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20663 			    &adjust, connp->conn_mac_exempt, ipst);
20664 			ipha = (ipha_t *)mp->b_rptr;
20665 			if (first_mp != NULL)
20666 				first_mp->b_cont = mp;
20667 			if (err != 0) {
20668 				if (first_mp == NULL)
20669 					first_mp = mp;
20670 				if (err == EINVAL)
20671 					goto icmp_parameter_problem;
20672 				ip2dbg(("ip_wput: label check failed (%d)\n",
20673 				    err));
20674 				goto discard_pkt;
20675 			}
20676 			iplen = ntohs(ipha->ipha_length) + adjust;
20677 			ipha->ipha_length = htons(iplen);
20678 		}
20679 
20680 		ipha = (ipha_t *)mp->b_rptr;
20681 		if (first_mp == NULL) {
20682 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
20683 			/*
20684 			 * If we got here because of "goto hdrtoosmall"
20685 			 * We need to attach a IPSEC_OUT.
20686 			 */
20687 			if (connp->conn_out_enforce_policy) {
20688 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
20689 				    NULL, ipha->ipha_protocol,
20690 				    ipst->ips_netstack)) == NULL)) {
20691 					BUMP_MIB(&ipst->ips_ip_mib,
20692 					    ipIfStatsOutDiscards);
20693 					if (need_decref)
20694 						CONN_DEC_REF(connp);
20695 					return;
20696 				} else {
20697 					ASSERT(mp->b_datap->db_type == M_CTL);
20698 					first_mp = mp;
20699 					mp = mp->b_cont;
20700 					mctl_present = B_TRUE;
20701 				}
20702 			} else {
20703 				first_mp = mp;
20704 				mctl_present = B_FALSE;
20705 			}
20706 		}
20707 	}
20708 #endif
20709 
20710 	/* Most of the code below is written for speed, not readability */
20711 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20712 
20713 	/*
20714 	 * If ip_newroute() fails, we're going to need a full
20715 	 * header for the icmp wraparound.
20716 	 */
20717 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
20718 		uint_t	v_hlen;
20719 version_hdrlen_check:
20720 		ASSERT(first_mp != NULL);
20721 		v_hlen = V_HLEN;
20722 		/*
20723 		 * siphon off IPv6 packets coming down from transport
20724 		 * layer modules here.
20725 		 * Note: high-order bit carries NUD reachability confirmation
20726 		 */
20727 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
20728 			/*
20729 			 * FIXME: assume that callers of ip_output* call
20730 			 * the right version?
20731 			 */
20732 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
20733 			ASSERT(xmit_ill == NULL);
20734 			if (attach_ill != NULL)
20735 				ill_refrele(attach_ill);
20736 			if (need_decref)
20737 				mp->b_flag |= MSGHASREF;
20738 			(void) ip_output_v6(arg, first_mp, arg2, caller);
20739 			return;
20740 		}
20741 
20742 		if ((v_hlen >> 4) != IP_VERSION) {
20743 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20744 			    "ip_wput_end: q %p (%S)", q, "badvers");
20745 			goto discard_pkt;
20746 		}
20747 		/*
20748 		 * Is the header length at least 20 bytes?
20749 		 *
20750 		 * Are there enough bytes accessible in the header?  If
20751 		 * not, try a pullup.
20752 		 */
20753 		v_hlen &= 0xF;
20754 		v_hlen <<= 2;
20755 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
20756 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20757 			    "ip_wput_end: q %p (%S)", q, "badlen");
20758 			goto discard_pkt;
20759 		}
20760 		if (v_hlen > (mp->b_wptr - rptr)) {
20761 			if (!pullupmsg(mp, v_hlen)) {
20762 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20763 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
20764 				goto discard_pkt;
20765 			}
20766 			ipha = (ipha_t *)mp->b_rptr;
20767 		}
20768 		/*
20769 		 * Move first entry from any source route into ipha_dst and
20770 		 * verify the options
20771 		 */
20772 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
20773 		    zoneid, ipst)) {
20774 			ASSERT(xmit_ill == NULL);
20775 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20776 			if (attach_ill != NULL)
20777 				ill_refrele(attach_ill);
20778 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20779 			    "ip_wput_end: q %p (%S)", q, "badopts");
20780 			if (need_decref)
20781 				CONN_DEC_REF(connp);
20782 			return;
20783 		}
20784 	}
20785 	dst = ipha->ipha_dst;
20786 
20787 	/*
20788 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
20789 	 * we have to run the packet through ip_newroute which will take
20790 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
20791 	 * a resolver, or assigning a default gateway, etc.
20792 	 */
20793 	if (CLASSD(dst)) {
20794 		ipif_t	*ipif;
20795 		uint32_t setsrc = 0;
20796 
20797 multicast:
20798 		ASSERT(first_mp != NULL);
20799 		ip2dbg(("ip_wput: CLASSD\n"));
20800 		if (connp == NULL) {
20801 			/*
20802 			 * Use the first good ipif on the ill.
20803 			 * XXX Should this ever happen? (Appears
20804 			 * to show up with just ppp and no ethernet due
20805 			 * to in.rdisc.)
20806 			 * However, ire_send should be able to
20807 			 * call ip_wput_ire directly.
20808 			 *
20809 			 * XXX Also, this can happen for ICMP and other packets
20810 			 * with multicast source addresses.  Perhaps we should
20811 			 * fix things so that we drop the packet in question,
20812 			 * but for now, just run with it.
20813 			 */
20814 			ill_t *ill = (ill_t *)q->q_ptr;
20815 
20816 			/*
20817 			 * Don't honor attach_if for this case. If ill
20818 			 * is part of the group, ipif could belong to
20819 			 * any ill and we cannot maintain attach_ill
20820 			 * and ipif_ill same anymore and the assert
20821 			 * below would fail.
20822 			 */
20823 			if (mctl_present && io->ipsec_out_attach_if) {
20824 				io->ipsec_out_ill_index = 0;
20825 				io->ipsec_out_attach_if = B_FALSE;
20826 				ASSERT(attach_ill != NULL);
20827 				ill_refrele(attach_ill);
20828 				attach_ill = NULL;
20829 			}
20830 
20831 			ASSERT(attach_ill == NULL);
20832 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
20833 			if (ipif == NULL) {
20834 				if (need_decref)
20835 					CONN_DEC_REF(connp);
20836 				freemsg(first_mp);
20837 				return;
20838 			}
20839 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
20840 			    ntohl(dst), ill->ill_name));
20841 		} else {
20842 			/*
20843 			 * The order of precedence is IP_BOUND_IF, IP_PKTINFO
20844 			 * and IP_MULTICAST_IF.  The block comment above this
20845 			 * function explains the locking mechanism used here.
20846 			 */
20847 			if (xmit_ill == NULL) {
20848 				xmit_ill = conn_get_held_ill(connp,
20849 				    &connp->conn_outgoing_ill, &err);
20850 				if (err == ILL_LOOKUP_FAILED) {
20851 					ip1dbg(("ip_wput: No ill for "
20852 					    "IP_BOUND_IF\n"));
20853 					BUMP_MIB(&ipst->ips_ip_mib,
20854 					    ipIfStatsOutNoRoutes);
20855 					goto drop_pkt;
20856 				}
20857 			}
20858 
20859 			if (xmit_ill == NULL) {
20860 				ipif = conn_get_held_ipif(connp,
20861 				    &connp->conn_multicast_ipif, &err);
20862 				if (err == IPIF_LOOKUP_FAILED) {
20863 					ip1dbg(("ip_wput: No ipif for "
20864 					    "multicast\n"));
20865 					BUMP_MIB(&ipst->ips_ip_mib,
20866 					    ipIfStatsOutNoRoutes);
20867 					goto drop_pkt;
20868 				}
20869 			}
20870 			if (xmit_ill != NULL) {
20871 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
20872 				if (ipif == NULL) {
20873 					ip1dbg(("ip_wput: No ipif for "
20874 					    "xmit_ill\n"));
20875 					BUMP_MIB(&ipst->ips_ip_mib,
20876 					    ipIfStatsOutNoRoutes);
20877 					goto drop_pkt;
20878 				}
20879 			} else if (ipif == NULL || ipif->ipif_isv6) {
20880 				/*
20881 				 * We must do this ipif determination here
20882 				 * else we could pass through ip_newroute
20883 				 * and come back here without the conn context.
20884 				 *
20885 				 * Note: we do late binding i.e. we bind to
20886 				 * the interface when the first packet is sent.
20887 				 * For performance reasons we do not rebind on
20888 				 * each packet but keep the binding until the
20889 				 * next IP_MULTICAST_IF option.
20890 				 *
20891 				 * conn_multicast_{ipif,ill} are shared between
20892 				 * IPv4 and IPv6 and AF_INET6 sockets can
20893 				 * send both IPv4 and IPv6 packets. Hence
20894 				 * we have to check that "isv6" matches above.
20895 				 */
20896 				if (ipif != NULL)
20897 					ipif_refrele(ipif);
20898 				ipif = ipif_lookup_group(dst, zoneid, ipst);
20899 				if (ipif == NULL) {
20900 					ip1dbg(("ip_wput: No ipif for "
20901 					    "multicast\n"));
20902 					BUMP_MIB(&ipst->ips_ip_mib,
20903 					    ipIfStatsOutNoRoutes);
20904 					goto drop_pkt;
20905 				}
20906 				err = conn_set_held_ipif(connp,
20907 				    &connp->conn_multicast_ipif, ipif);
20908 				if (err == IPIF_LOOKUP_FAILED) {
20909 					ipif_refrele(ipif);
20910 					ip1dbg(("ip_wput: No ipif for "
20911 					    "multicast\n"));
20912 					BUMP_MIB(&ipst->ips_ip_mib,
20913 					    ipIfStatsOutNoRoutes);
20914 					goto drop_pkt;
20915 				}
20916 			}
20917 		}
20918 		ASSERT(!ipif->ipif_isv6);
20919 		/*
20920 		 * As we may lose the conn by the time we reach ip_wput_ire,
20921 		 * we copy conn_multicast_loop and conn_dontroute on to an
20922 		 * ipsec_out. In case if this datagram goes out secure,
20923 		 * we need the ill_index also. Copy that also into the
20924 		 * ipsec_out.
20925 		 */
20926 		if (mctl_present) {
20927 			io = (ipsec_out_t *)first_mp->b_rptr;
20928 			ASSERT(first_mp->b_datap->db_type == M_CTL);
20929 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
20930 		} else {
20931 			ASSERT(mp == first_mp);
20932 			if ((first_mp = allocb(sizeof (ipsec_info_t),
20933 			    BPRI_HI)) == NULL) {
20934 				ipif_refrele(ipif);
20935 				first_mp = mp;
20936 				goto discard_pkt;
20937 			}
20938 			first_mp->b_datap->db_type = M_CTL;
20939 			first_mp->b_wptr += sizeof (ipsec_info_t);
20940 			/* ipsec_out_secure is B_FALSE now */
20941 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
20942 			io = (ipsec_out_t *)first_mp->b_rptr;
20943 			io->ipsec_out_type = IPSEC_OUT;
20944 			io->ipsec_out_len = sizeof (ipsec_out_t);
20945 			io->ipsec_out_use_global_policy = B_TRUE;
20946 			io->ipsec_out_ns = ipst->ips_netstack;
20947 			first_mp->b_cont = mp;
20948 			mctl_present = B_TRUE;
20949 		}
20950 		if (attach_ill != NULL) {
20951 			ASSERT(attach_ill == ipif->ipif_ill);
20952 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
20953 
20954 			/*
20955 			 * Check if we need an ire that will not be
20956 			 * looked up by anybody else i.e. HIDDEN.
20957 			 */
20958 			if (ill_is_probeonly(attach_ill)) {
20959 				match_flags |= MATCH_IRE_MARK_HIDDEN;
20960 			}
20961 			io->ipsec_out_ill_index =
20962 			    attach_ill->ill_phyint->phyint_ifindex;
20963 			io->ipsec_out_attach_if = B_TRUE;
20964 		} else {
20965 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
20966 			io->ipsec_out_ill_index =
20967 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
20968 		}
20969 		if (connp != NULL) {
20970 			io->ipsec_out_multicast_loop =
20971 			    connp->conn_multicast_loop;
20972 			io->ipsec_out_dontroute = connp->conn_dontroute;
20973 			io->ipsec_out_zoneid = connp->conn_zoneid;
20974 		}
20975 		/*
20976 		 * If the application uses IP_MULTICAST_IF with
20977 		 * different logical addresses of the same ILL, we
20978 		 * need to make sure that the soruce address of
20979 		 * the packet matches the logical IP address used
20980 		 * in the option. We do it by initializing ipha_src
20981 		 * here. This should keep IPsec also happy as
20982 		 * when we return from IPsec processing, we don't
20983 		 * have to worry about getting the right address on
20984 		 * the packet. Thus it is sufficient to look for
20985 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
20986 		 * MATCH_IRE_IPIF.
20987 		 *
20988 		 * NOTE : We need to do it for non-secure case also as
20989 		 * this might go out secure if there is a global policy
20990 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
20991 		 * address, the source should be initialized already and
20992 		 * hence we won't be initializing here.
20993 		 *
20994 		 * As we do not have the ire yet, it is possible that
20995 		 * we set the source address here and then later discover
20996 		 * that the ire implies the source address to be assigned
20997 		 * through the RTF_SETSRC flag.
20998 		 * In that case, the setsrc variable will remind us
20999 		 * that overwritting the source address by the one
21000 		 * of the RTF_SETSRC-flagged ire is allowed.
21001 		 */
21002 		if (ipha->ipha_src == INADDR_ANY &&
21003 		    (connp == NULL || !connp->conn_unspec_src)) {
21004 			ipha->ipha_src = ipif->ipif_src_addr;
21005 			setsrc = RTF_SETSRC;
21006 		}
21007 		/*
21008 		 * Find an IRE which matches the destination and the outgoing
21009 		 * queue (i.e. the outgoing interface.)
21010 		 * For loopback use a unicast IP address for
21011 		 * the ire lookup.
21012 		 */
21013 		if (IS_LOOPBACK(ipif->ipif_ill))
21014 			dst = ipif->ipif_lcl_addr;
21015 
21016 		/*
21017 		 * If xmit_ill is set, we branch out to ip_newroute_ipif.
21018 		 * We don't need to lookup ire in ctable as the packet
21019 		 * needs to be sent to the destination through the specified
21020 		 * ill irrespective of ires in the cache table.
21021 		 */
21022 		ire = NULL;
21023 		if (xmit_ill == NULL) {
21024 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21025 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21026 		}
21027 
21028 		/*
21029 		 * refrele attach_ill as its not needed anymore.
21030 		 */
21031 		if (attach_ill != NULL) {
21032 			ill_refrele(attach_ill);
21033 			attach_ill = NULL;
21034 		}
21035 
21036 		if (ire == NULL) {
21037 			/*
21038 			 * Multicast loopback and multicast forwarding is
21039 			 * done in ip_wput_ire.
21040 			 *
21041 			 * Mark this packet to make it be delivered to
21042 			 * ip_wput_ire after the new ire has been
21043 			 * created.
21044 			 *
21045 			 * The call to ip_newroute_ipif takes into account
21046 			 * the setsrc reminder. In any case, we take care
21047 			 * of the RTF_MULTIRT flag.
21048 			 */
21049 			mp->b_prev = mp->b_next = NULL;
21050 			if (xmit_ill == NULL ||
21051 			    xmit_ill->ill_ipif_up_count > 0) {
21052 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21053 				    setsrc | RTF_MULTIRT, zoneid, infop);
21054 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21055 				    "ip_wput_end: q %p (%S)", q, "noire");
21056 			} else {
21057 				freemsg(first_mp);
21058 			}
21059 			ipif_refrele(ipif);
21060 			if (xmit_ill != NULL)
21061 				ill_refrele(xmit_ill);
21062 			if (need_decref)
21063 				CONN_DEC_REF(connp);
21064 			return;
21065 		}
21066 
21067 		ipif_refrele(ipif);
21068 		ipif = NULL;
21069 		ASSERT(xmit_ill == NULL);
21070 
21071 		/*
21072 		 * Honor the RTF_SETSRC flag for multicast packets,
21073 		 * if allowed by the setsrc reminder.
21074 		 */
21075 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21076 			ipha->ipha_src = ire->ire_src_addr;
21077 		}
21078 
21079 		/*
21080 		 * Unconditionally force the TTL to 1 for
21081 		 * multirouted multicast packets:
21082 		 * multirouted multicast should not cross
21083 		 * multicast routers.
21084 		 */
21085 		if (ire->ire_flags & RTF_MULTIRT) {
21086 			if (ipha->ipha_ttl > 1) {
21087 				ip2dbg(("ip_wput: forcing multicast "
21088 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21089 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21090 				ipha->ipha_ttl = 1;
21091 			}
21092 		}
21093 	} else {
21094 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
21095 		if ((ire != NULL) && (ire->ire_type &
21096 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21097 			ignore_dontroute = B_TRUE;
21098 			ignore_nexthop = B_TRUE;
21099 		}
21100 		if (ire != NULL) {
21101 			ire_refrele(ire);
21102 			ire = NULL;
21103 		}
21104 		/*
21105 		 * Guard against coming in from arp in which case conn is NULL.
21106 		 * Also guard against non M_DATA with dontroute set but
21107 		 * destined to local, loopback or broadcast addresses.
21108 		 */
21109 		if (connp != NULL && connp->conn_dontroute &&
21110 		    !ignore_dontroute) {
21111 dontroute:
21112 			/*
21113 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21114 			 * routing protocols from seeing false direct
21115 			 * connectivity.
21116 			 */
21117 			ipha->ipha_ttl = 1;
21118 
21119 			/* If suitable ipif not found, drop packet */
21120 			dst_ipif = ipif_lookup_onlink_addr(dst, zoneid, ipst);
21121 			if (dst_ipif == NULL) {
21122 noroute:
21123 				ip1dbg(("ip_wput: no route for dst using"
21124 				    " SO_DONTROUTE\n"));
21125 				BUMP_MIB(&ipst->ips_ip_mib,
21126 				    ipIfStatsOutNoRoutes);
21127 				mp->b_prev = mp->b_next = NULL;
21128 				if (first_mp == NULL)
21129 					first_mp = mp;
21130 				goto drop_pkt;
21131 			} else {
21132 				/*
21133 				 * If suitable ipif has been found, set
21134 				 * xmit_ill to the corresponding
21135 				 * ipif_ill because we'll be using the
21136 				 * send_from_ill logic below.
21137 				 */
21138 				ASSERT(xmit_ill == NULL);
21139 				xmit_ill = dst_ipif->ipif_ill;
21140 				mutex_enter(&xmit_ill->ill_lock);
21141 				if (!ILL_CAN_LOOKUP(xmit_ill)) {
21142 					mutex_exit(&xmit_ill->ill_lock);
21143 					xmit_ill = NULL;
21144 					ipif_refrele(dst_ipif);
21145 					goto noroute;
21146 				}
21147 				ill_refhold_locked(xmit_ill);
21148 				mutex_exit(&xmit_ill->ill_lock);
21149 				ipif_refrele(dst_ipif);
21150 			}
21151 		}
21152 		/*
21153 		 * If we are bound to IPIF_NOFAILOVER address, look for
21154 		 * an IRE_CACHE matching the ill.
21155 		 */
21156 send_from_ill:
21157 		if (attach_ill != NULL) {
21158 			ipif_t	*attach_ipif;
21159 
21160 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21161 
21162 			/*
21163 			 * Check if we need an ire that will not be
21164 			 * looked up by anybody else i.e. HIDDEN.
21165 			 */
21166 			if (ill_is_probeonly(attach_ill)) {
21167 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21168 			}
21169 
21170 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
21171 			if (attach_ipif == NULL) {
21172 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
21173 				goto discard_pkt;
21174 			}
21175 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
21176 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21177 			ipif_refrele(attach_ipif);
21178 		} else if (xmit_ill != NULL) {
21179 			ipif_t *ipif;
21180 
21181 			/*
21182 			 * Mark this packet as originated locally
21183 			 */
21184 			mp->b_prev = mp->b_next = NULL;
21185 
21186 			/*
21187 			 * Could be SO_DONTROUTE case also.
21188 			 * Verify that at least one ipif is up on the ill.
21189 			 */
21190 			if (xmit_ill->ill_ipif_up_count == 0) {
21191 				ip1dbg(("ip_output: xmit_ill %s is down\n",
21192 				    xmit_ill->ill_name));
21193 				goto drop_pkt;
21194 			}
21195 
21196 			ipif = ipif_get_next_ipif(NULL, xmit_ill);
21197 			if (ipif == NULL) {
21198 				ip1dbg(("ip_output: xmit_ill %s NULL ipif\n",
21199 				    xmit_ill->ill_name));
21200 				goto drop_pkt;
21201 			}
21202 
21203 			/*
21204 			 * Look for a ire that is part of the group,
21205 			 * if found use it else call ip_newroute_ipif.
21206 			 * IPCL_ZONEID is not used for matching because
21207 			 * IP_ALLZONES option is valid only when the
21208 			 * ill is accessible from all zones i.e has a
21209 			 * valid ipif in all zones.
21210 			 */
21211 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
21212 			ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21213 			    MBLK_GETLABEL(mp), match_flags, ipst);
21214 			/*
21215 			 * If an ire exists use it or else create
21216 			 * an ire but don't add it to the cache.
21217 			 * Adding an ire may cause issues with
21218 			 * asymmetric routing.
21219 			 * In case of multiroute always act as if
21220 			 * ire does not exist.
21221 			 */
21222 			if (ire == NULL || ire->ire_flags & RTF_MULTIRT) {
21223 				if (ire != NULL)
21224 					ire_refrele(ire);
21225 				ip_newroute_ipif(q, first_mp, ipif,
21226 				    dst, connp, 0, zoneid, infop);
21227 				ipif_refrele(ipif);
21228 				ip1dbg(("ip_output: xmit_ill via %s\n",
21229 				    xmit_ill->ill_name));
21230 				ill_refrele(xmit_ill);
21231 				if (need_decref)
21232 					CONN_DEC_REF(connp);
21233 				return;
21234 			}
21235 			ipif_refrele(ipif);
21236 		} else if (ip_nexthop || (connp != NULL &&
21237 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21238 			if (!ip_nexthop) {
21239 				ip_nexthop = B_TRUE;
21240 				nexthop_addr = connp->conn_nexthop_v4;
21241 			}
21242 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21243 			    MATCH_IRE_GW;
21244 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21245 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21246 		} else {
21247 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp),
21248 			    ipst);
21249 		}
21250 		if (!ire) {
21251 			/*
21252 			 * Make sure we don't load spread if this
21253 			 * is IPIF_NOFAILOVER case.
21254 			 */
21255 			if ((attach_ill != NULL) ||
21256 			    (ip_nexthop && !ignore_nexthop)) {
21257 				if (mctl_present) {
21258 					io = (ipsec_out_t *)first_mp->b_rptr;
21259 					ASSERT(first_mp->b_datap->db_type ==
21260 					    M_CTL);
21261 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21262 				} else {
21263 					ASSERT(mp == first_mp);
21264 					first_mp = allocb(
21265 					    sizeof (ipsec_info_t), BPRI_HI);
21266 					if (first_mp == NULL) {
21267 						first_mp = mp;
21268 						goto discard_pkt;
21269 					}
21270 					first_mp->b_datap->db_type = M_CTL;
21271 					first_mp->b_wptr +=
21272 					    sizeof (ipsec_info_t);
21273 					/* ipsec_out_secure is B_FALSE now */
21274 					bzero(first_mp->b_rptr,
21275 					    sizeof (ipsec_info_t));
21276 					io = (ipsec_out_t *)first_mp->b_rptr;
21277 					io->ipsec_out_type = IPSEC_OUT;
21278 					io->ipsec_out_len =
21279 					    sizeof (ipsec_out_t);
21280 					io->ipsec_out_use_global_policy =
21281 					    B_TRUE;
21282 					io->ipsec_out_ns = ipst->ips_netstack;
21283 					first_mp->b_cont = mp;
21284 					mctl_present = B_TRUE;
21285 				}
21286 				if (attach_ill != NULL) {
21287 					io->ipsec_out_ill_index = attach_ill->
21288 					    ill_phyint->phyint_ifindex;
21289 					io->ipsec_out_attach_if = B_TRUE;
21290 				} else {
21291 					io->ipsec_out_ip_nexthop = ip_nexthop;
21292 					io->ipsec_out_nexthop_addr =
21293 					    nexthop_addr;
21294 				}
21295 			}
21296 noirefound:
21297 			/*
21298 			 * Mark this packet as having originated on
21299 			 * this machine.  This will be noted in
21300 			 * ire_add_then_send, which needs to know
21301 			 * whether to run it back through ip_wput or
21302 			 * ip_rput following successful resolution.
21303 			 */
21304 			mp->b_prev = NULL;
21305 			mp->b_next = NULL;
21306 			ip_newroute(q, first_mp, dst, connp, zoneid, ipst);
21307 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21308 			    "ip_wput_end: q %p (%S)", q, "newroute");
21309 			if (attach_ill != NULL)
21310 				ill_refrele(attach_ill);
21311 			if (xmit_ill != NULL)
21312 				ill_refrele(xmit_ill);
21313 			if (need_decref)
21314 				CONN_DEC_REF(connp);
21315 			return;
21316 		}
21317 	}
21318 
21319 	/* We now know where we are going with it. */
21320 
21321 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21322 	    "ip_wput_end: q %p (%S)", q, "end");
21323 
21324 	/*
21325 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21326 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21327 	 */
21328 	if (ire->ire_flags & RTF_MULTIRT) {
21329 		/*
21330 		 * Force the TTL of multirouted packets if required.
21331 		 * The TTL of such packets is bounded by the
21332 		 * ip_multirt_ttl ndd variable.
21333 		 */
21334 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21335 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21336 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21337 			    "(was %d), dst 0x%08x\n",
21338 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21339 			    ntohl(ire->ire_addr)));
21340 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21341 		}
21342 		/*
21343 		 * At this point, we check to see if there are any pending
21344 		 * unresolved routes. ire_multirt_resolvable()
21345 		 * checks in O(n) that all IRE_OFFSUBNET ire
21346 		 * entries for the packet's destination and
21347 		 * flagged RTF_MULTIRT are currently resolved.
21348 		 * If some remain unresolved, we make a copy
21349 		 * of the current message. It will be used
21350 		 * to initiate additional route resolutions.
21351 		 */
21352 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21353 		    MBLK_GETLABEL(first_mp), ipst);
21354 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21355 		    "multirt_need_resolve %d, first_mp %p\n",
21356 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21357 		if (multirt_need_resolve) {
21358 			copy_mp = copymsg(first_mp);
21359 			if (copy_mp != NULL) {
21360 				MULTIRT_DEBUG_TAG(copy_mp);
21361 			}
21362 		}
21363 	}
21364 
21365 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21366 	/*
21367 	 * Try to resolve another multiroute if
21368 	 * ire_multirt_resolvable() deemed it necessary.
21369 	 * At this point, we need to distinguish
21370 	 * multicasts from other packets. For multicasts,
21371 	 * we call ip_newroute_ipif() and request that both
21372 	 * multirouting and setsrc flags are checked.
21373 	 */
21374 	if (copy_mp != NULL) {
21375 		if (CLASSD(dst)) {
21376 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21377 			if (ipif) {
21378 				ASSERT(infop->ip_opt_ill_index == 0);
21379 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21380 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21381 				ipif_refrele(ipif);
21382 			} else {
21383 				MULTIRT_DEBUG_UNTAG(copy_mp);
21384 				freemsg(copy_mp);
21385 				copy_mp = NULL;
21386 			}
21387 		} else {
21388 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
21389 		}
21390 	}
21391 	if (attach_ill != NULL)
21392 		ill_refrele(attach_ill);
21393 	if (xmit_ill != NULL)
21394 		ill_refrele(xmit_ill);
21395 	if (need_decref)
21396 		CONN_DEC_REF(connp);
21397 	return;
21398 
21399 icmp_parameter_problem:
21400 	/* could not have originated externally */
21401 	ASSERT(mp->b_prev == NULL);
21402 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21403 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21404 		/* it's the IP header length that's in trouble */
21405 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21406 		first_mp = NULL;
21407 	}
21408 
21409 discard_pkt:
21410 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21411 drop_pkt:
21412 	ip1dbg(("ip_wput: dropped packet\n"));
21413 	if (ire != NULL)
21414 		ire_refrele(ire);
21415 	if (need_decref)
21416 		CONN_DEC_REF(connp);
21417 	freemsg(first_mp);
21418 	if (attach_ill != NULL)
21419 		ill_refrele(attach_ill);
21420 	if (xmit_ill != NULL)
21421 		ill_refrele(xmit_ill);
21422 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21423 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21424 }
21425 
21426 /*
21427  * If this is a conn_t queue, then we pass in the conn. This includes the
21428  * zoneid.
21429  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21430  * in which case we use the global zoneid since those are all part of
21431  * the global zone.
21432  */
21433 void
21434 ip_wput(queue_t *q, mblk_t *mp)
21435 {
21436 	if (CONN_Q(q))
21437 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21438 	else
21439 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21440 }
21441 
21442 /*
21443  *
21444  * The following rules must be observed when accessing any ipif or ill
21445  * that has been cached in the conn. Typically conn_nofailover_ill,
21446  * conn_outgoing_ill, conn_multicast_ipif and conn_multicast_ill.
21447  *
21448  * Access: The ipif or ill pointed to from the conn can be accessed under
21449  * the protection of the conn_lock or after it has been refheld under the
21450  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21451  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21452  * The reason for this is that a concurrent unplumb could actually be
21453  * cleaning up these cached pointers by walking the conns and might have
21454  * finished cleaning up the conn in question. The macros check that an
21455  * unplumb has not yet started on the ipif or ill.
21456  *
21457  * Caching: An ipif or ill pointer may be cached in the conn only after
21458  * making sure that an unplumb has not started. So the caching is done
21459  * while holding both the conn_lock and the ill_lock and after using the
21460  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21461  * flag before starting the cleanup of conns.
21462  *
21463  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21464  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21465  * or a reference to the ipif or a reference to an ire that references the
21466  * ipif. An ipif does not change its ill except for failover/failback. Since
21467  * failover/failback happens only after bringing down the ipif and making sure
21468  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
21469  * the above holds.
21470  */
21471 ipif_t *
21472 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21473 {
21474 	ipif_t	*ipif;
21475 	ill_t	*ill;
21476 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21477 
21478 	*err = 0;
21479 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21480 	mutex_enter(&connp->conn_lock);
21481 	ipif = *ipifp;
21482 	if (ipif != NULL) {
21483 		ill = ipif->ipif_ill;
21484 		mutex_enter(&ill->ill_lock);
21485 		if (IPIF_CAN_LOOKUP(ipif)) {
21486 			ipif_refhold_locked(ipif);
21487 			mutex_exit(&ill->ill_lock);
21488 			mutex_exit(&connp->conn_lock);
21489 			rw_exit(&ipst->ips_ill_g_lock);
21490 			return (ipif);
21491 		} else {
21492 			*err = IPIF_LOOKUP_FAILED;
21493 		}
21494 		mutex_exit(&ill->ill_lock);
21495 	}
21496 	mutex_exit(&connp->conn_lock);
21497 	rw_exit(&ipst->ips_ill_g_lock);
21498 	return (NULL);
21499 }
21500 
21501 ill_t *
21502 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21503 {
21504 	ill_t	*ill;
21505 
21506 	*err = 0;
21507 	mutex_enter(&connp->conn_lock);
21508 	ill = *illp;
21509 	if (ill != NULL) {
21510 		mutex_enter(&ill->ill_lock);
21511 		if (ILL_CAN_LOOKUP(ill)) {
21512 			ill_refhold_locked(ill);
21513 			mutex_exit(&ill->ill_lock);
21514 			mutex_exit(&connp->conn_lock);
21515 			return (ill);
21516 		} else {
21517 			*err = ILL_LOOKUP_FAILED;
21518 		}
21519 		mutex_exit(&ill->ill_lock);
21520 	}
21521 	mutex_exit(&connp->conn_lock);
21522 	return (NULL);
21523 }
21524 
21525 static int
21526 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21527 {
21528 	ill_t	*ill;
21529 
21530 	ill = ipif->ipif_ill;
21531 	mutex_enter(&connp->conn_lock);
21532 	mutex_enter(&ill->ill_lock);
21533 	if (IPIF_CAN_LOOKUP(ipif)) {
21534 		*ipifp = ipif;
21535 		mutex_exit(&ill->ill_lock);
21536 		mutex_exit(&connp->conn_lock);
21537 		return (0);
21538 	}
21539 	mutex_exit(&ill->ill_lock);
21540 	mutex_exit(&connp->conn_lock);
21541 	return (IPIF_LOOKUP_FAILED);
21542 }
21543 
21544 /*
21545  * This is called if the outbound datagram needs fragmentation.
21546  *
21547  * NOTE : This function does not ire_refrele the ire argument passed in.
21548  */
21549 static void
21550 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21551     ip_stack_t *ipst)
21552 {
21553 	ipha_t		*ipha;
21554 	mblk_t		*mp;
21555 	uint32_t	v_hlen_tos_len;
21556 	uint32_t	max_frag;
21557 	uint32_t	frag_flag;
21558 	boolean_t	dont_use;
21559 
21560 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21561 		mp = ipsec_mp->b_cont;
21562 	} else {
21563 		mp = ipsec_mp;
21564 	}
21565 
21566 	ipha = (ipha_t *)mp->b_rptr;
21567 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21568 
21569 #ifdef	_BIG_ENDIAN
21570 #define	V_HLEN	(v_hlen_tos_len >> 24)
21571 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21572 #else
21573 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21574 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21575 #endif
21576 
21577 #ifndef SPEED_BEFORE_SAFETY
21578 	/*
21579 	 * Check that ipha_length is consistent with
21580 	 * the mblk length
21581 	 */
21582 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21583 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21584 		    LENGTH, msgdsize(mp)));
21585 		freemsg(ipsec_mp);
21586 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21587 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21588 		    "packet length mismatch");
21589 		return;
21590 	}
21591 #endif
21592 	/*
21593 	 * Don't use frag_flag if pre-built packet or source
21594 	 * routed or if multicast (since multicast packets do not solicit
21595 	 * ICMP "packet too big" messages). Get the values of
21596 	 * max_frag and frag_flag atomically by acquiring the
21597 	 * ire_lock.
21598 	 */
21599 	mutex_enter(&ire->ire_lock);
21600 	max_frag = ire->ire_max_frag;
21601 	frag_flag = ire->ire_frag_flag;
21602 	mutex_exit(&ire->ire_lock);
21603 
21604 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21605 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21606 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21607 
21608 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21609 	    (dont_use ? 0 : frag_flag), zoneid, ipst);
21610 }
21611 
21612 /*
21613  * Used for deciding the MSS size for the upper layer. Thus
21614  * we need to check the outbound policy values in the conn.
21615  */
21616 int
21617 conn_ipsec_length(conn_t *connp)
21618 {
21619 	ipsec_latch_t *ipl;
21620 
21621 	ipl = connp->conn_latch;
21622 	if (ipl == NULL)
21623 		return (0);
21624 
21625 	if (ipl->ipl_out_policy == NULL)
21626 		return (0);
21627 
21628 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21629 }
21630 
21631 /*
21632  * Returns an estimate of the IPsec headers size. This is used if
21633  * we don't want to call into IPsec to get the exact size.
21634  */
21635 int
21636 ipsec_out_extra_length(mblk_t *ipsec_mp)
21637 {
21638 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21639 	ipsec_action_t *a;
21640 
21641 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21642 	if (!io->ipsec_out_secure)
21643 		return (0);
21644 
21645 	a = io->ipsec_out_act;
21646 
21647 	if (a == NULL) {
21648 		ASSERT(io->ipsec_out_policy != NULL);
21649 		a = io->ipsec_out_policy->ipsp_act;
21650 	}
21651 	ASSERT(a != NULL);
21652 
21653 	return (a->ipa_ovhd);
21654 }
21655 
21656 /*
21657  * Returns an estimate of the IPsec headers size. This is used if
21658  * we don't want to call into IPsec to get the exact size.
21659  */
21660 int
21661 ipsec_in_extra_length(mblk_t *ipsec_mp)
21662 {
21663 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21664 	ipsec_action_t *a;
21665 
21666 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21667 
21668 	a = ii->ipsec_in_action;
21669 	return (a == NULL ? 0 : a->ipa_ovhd);
21670 }
21671 
21672 /*
21673  * If there are any source route options, return the true final
21674  * destination. Otherwise, return the destination.
21675  */
21676 ipaddr_t
21677 ip_get_dst(ipha_t *ipha)
21678 {
21679 	ipoptp_t	opts;
21680 	uchar_t		*opt;
21681 	uint8_t		optval;
21682 	uint8_t		optlen;
21683 	ipaddr_t	dst;
21684 	uint32_t off;
21685 
21686 	dst = ipha->ipha_dst;
21687 
21688 	if (IS_SIMPLE_IPH(ipha))
21689 		return (dst);
21690 
21691 	for (optval = ipoptp_first(&opts, ipha);
21692 	    optval != IPOPT_EOL;
21693 	    optval = ipoptp_next(&opts)) {
21694 		opt = opts.ipoptp_cur;
21695 		optlen = opts.ipoptp_len;
21696 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
21697 		switch (optval) {
21698 		case IPOPT_SSRR:
21699 		case IPOPT_LSRR:
21700 			off = opt[IPOPT_OFFSET];
21701 			/*
21702 			 * If one of the conditions is true, it means
21703 			 * end of options and dst already has the right
21704 			 * value.
21705 			 */
21706 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
21707 				off = optlen - IP_ADDR_LEN;
21708 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
21709 			}
21710 			return (dst);
21711 		default:
21712 			break;
21713 		}
21714 	}
21715 
21716 	return (dst);
21717 }
21718 
21719 mblk_t *
21720 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
21721     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
21722 {
21723 	ipsec_out_t	*io;
21724 	mblk_t		*first_mp;
21725 	boolean_t policy_present;
21726 	ip_stack_t	*ipst;
21727 	ipsec_stack_t	*ipss;
21728 
21729 	ASSERT(ire != NULL);
21730 	ipst = ire->ire_ipst;
21731 	ipss = ipst->ips_netstack->netstack_ipsec;
21732 
21733 	first_mp = mp;
21734 	if (mp->b_datap->db_type == M_CTL) {
21735 		io = (ipsec_out_t *)first_mp->b_rptr;
21736 		/*
21737 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
21738 		 *
21739 		 * 1) There is per-socket policy (including cached global
21740 		 *    policy) or a policy on the IP-in-IP tunnel.
21741 		 * 2) There is no per-socket policy, but it is
21742 		 *    a multicast packet that needs to go out
21743 		 *    on a specific interface. This is the case
21744 		 *    where (ip_wput and ip_wput_multicast) attaches
21745 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
21746 		 *
21747 		 * In case (2) we check with global policy to
21748 		 * see if there is a match and set the ill_index
21749 		 * appropriately so that we can lookup the ire
21750 		 * properly in ip_wput_ipsec_out.
21751 		 */
21752 
21753 		/*
21754 		 * ipsec_out_use_global_policy is set to B_FALSE
21755 		 * in ipsec_in_to_out(). Refer to that function for
21756 		 * details.
21757 		 */
21758 		if ((io->ipsec_out_latch == NULL) &&
21759 		    (io->ipsec_out_use_global_policy)) {
21760 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
21761 			    ire, connp, unspec_src, zoneid));
21762 		}
21763 		if (!io->ipsec_out_secure) {
21764 			/*
21765 			 * If this is not a secure packet, drop
21766 			 * the IPSEC_OUT mp and treat it as a clear
21767 			 * packet. This happens when we are sending
21768 			 * a ICMP reply back to a clear packet. See
21769 			 * ipsec_in_to_out() for details.
21770 			 */
21771 			mp = first_mp->b_cont;
21772 			freeb(first_mp);
21773 		}
21774 		return (mp);
21775 	}
21776 	/*
21777 	 * See whether we need to attach a global policy here. We
21778 	 * don't depend on the conn (as it could be null) for deciding
21779 	 * what policy this datagram should go through because it
21780 	 * should have happened in ip_wput if there was some
21781 	 * policy. This normally happens for connections which are not
21782 	 * fully bound preventing us from caching policies in
21783 	 * ip_bind. Packets coming from the TCP listener/global queue
21784 	 * - which are non-hard_bound - could also be affected by
21785 	 * applying policy here.
21786 	 *
21787 	 * If this packet is coming from tcp global queue or listener,
21788 	 * we will be applying policy here.  This may not be *right*
21789 	 * if these packets are coming from the detached connection as
21790 	 * it could have gone in clear before. This happens only if a
21791 	 * TCP connection started when there is no policy and somebody
21792 	 * added policy before it became detached. Thus packets of the
21793 	 * detached connection could go out secure and the other end
21794 	 * would drop it because it will be expecting in clear. The
21795 	 * converse is not true i.e if somebody starts a TCP
21796 	 * connection and deletes the policy, all the packets will
21797 	 * still go out with the policy that existed before deleting
21798 	 * because ip_unbind sends up policy information which is used
21799 	 * by TCP on subsequent ip_wputs. The right solution is to fix
21800 	 * TCP to attach a dummy IPSEC_OUT and set
21801 	 * ipsec_out_use_global_policy to B_FALSE. As this might
21802 	 * affect performance for normal cases, we are not doing it.
21803 	 * Thus, set policy before starting any TCP connections.
21804 	 *
21805 	 * NOTE - We might apply policy even for a hard bound connection
21806 	 * - for which we cached policy in ip_bind - if somebody added
21807 	 * global policy after we inherited the policy in ip_bind.
21808 	 * This means that the packets that were going out in clear
21809 	 * previously would start going secure and hence get dropped
21810 	 * on the other side. To fix this, TCP attaches a dummy
21811 	 * ipsec_out and make sure that we don't apply global policy.
21812 	 */
21813 	if (ipha != NULL)
21814 		policy_present = ipss->ipsec_outbound_v4_policy_present;
21815 	else
21816 		policy_present = ipss->ipsec_outbound_v6_policy_present;
21817 	if (!policy_present)
21818 		return (mp);
21819 
21820 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
21821 	    zoneid));
21822 }
21823 
21824 ire_t *
21825 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
21826 {
21827 	ipaddr_t addr;
21828 	ire_t *save_ire;
21829 	irb_t *irb;
21830 	ill_group_t *illgrp;
21831 	int	err;
21832 
21833 	save_ire = ire;
21834 	addr = ire->ire_addr;
21835 
21836 	ASSERT(ire->ire_type == IRE_BROADCAST);
21837 
21838 	illgrp = connp->conn_outgoing_ill->ill_group;
21839 	if (illgrp == NULL) {
21840 		*conn_outgoing_ill = conn_get_held_ill(connp,
21841 		    &connp->conn_outgoing_ill, &err);
21842 		if (err == ILL_LOOKUP_FAILED) {
21843 			ire_refrele(save_ire);
21844 			return (NULL);
21845 		}
21846 		return (save_ire);
21847 	}
21848 	/*
21849 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
21850 	 * If it is part of the group, we need to send on the ire
21851 	 * that has been cleared of IRE_MARK_NORECV and that belongs
21852 	 * to this group. This is okay as IP_BOUND_IF really means
21853 	 * any ill in the group. We depend on the fact that the
21854 	 * first ire in the group is always cleared of IRE_MARK_NORECV
21855 	 * if such an ire exists. This is possible only if you have
21856 	 * at least one ill in the group that has not failed.
21857 	 *
21858 	 * First get to the ire that matches the address and group.
21859 	 *
21860 	 * We don't look for an ire with a matching zoneid because a given zone
21861 	 * won't always have broadcast ires on all ills in the group.
21862 	 */
21863 	irb = ire->ire_bucket;
21864 	rw_enter(&irb->irb_lock, RW_READER);
21865 	if (ire->ire_marks & IRE_MARK_NORECV) {
21866 		/*
21867 		 * If the current zone only has an ire broadcast for this
21868 		 * address marked NORECV, the ire we want is ahead in the
21869 		 * bucket, so we look it up deliberately ignoring the zoneid.
21870 		 */
21871 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
21872 			if (ire->ire_addr != addr)
21873 				continue;
21874 			/* skip over deleted ires */
21875 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
21876 				continue;
21877 		}
21878 	}
21879 	while (ire != NULL) {
21880 		/*
21881 		 * If a new interface is coming up, we could end up
21882 		 * seeing the loopback ire and the non-loopback ire
21883 		 * may not have been added yet. So check for ire_stq
21884 		 */
21885 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
21886 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
21887 			break;
21888 		}
21889 		ire = ire->ire_next;
21890 	}
21891 	if (ire != NULL && ire->ire_addr == addr &&
21892 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
21893 		IRE_REFHOLD(ire);
21894 		rw_exit(&irb->irb_lock);
21895 		ire_refrele(save_ire);
21896 		*conn_outgoing_ill = ire_to_ill(ire);
21897 		/*
21898 		 * Refhold the ill to make the conn_outgoing_ill
21899 		 * independent of the ire. ip_wput_ire goes in a loop
21900 		 * and may refrele the ire. Since we have an ire at this
21901 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
21902 		 */
21903 		ill_refhold(*conn_outgoing_ill);
21904 		return (ire);
21905 	}
21906 	rw_exit(&irb->irb_lock);
21907 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
21908 	/*
21909 	 * If we can't find a suitable ire, return the original ire.
21910 	 */
21911 	return (save_ire);
21912 }
21913 
21914 /*
21915  * This function does the ire_refrele of the ire passed in as the
21916  * argument. As this function looks up more ires i.e broadcast ires,
21917  * it needs to REFRELE them. Currently, for simplicity we don't
21918  * differentiate the one passed in and looked up here. We always
21919  * REFRELE.
21920  * IPQoS Notes:
21921  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
21922  * IPsec packets are done in ipsec_out_process.
21923  *
21924  */
21925 void
21926 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
21927     zoneid_t zoneid)
21928 {
21929 	ipha_t		*ipha;
21930 #define	rptr	((uchar_t *)ipha)
21931 	queue_t		*stq;
21932 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
21933 	uint32_t	v_hlen_tos_len;
21934 	uint32_t	ttl_protocol;
21935 	ipaddr_t	src;
21936 	ipaddr_t	dst;
21937 	uint32_t	cksum;
21938 	ipaddr_t	orig_src;
21939 	ire_t		*ire1;
21940 	mblk_t		*next_mp;
21941 	uint_t		hlen;
21942 	uint16_t	*up;
21943 	uint32_t	max_frag = ire->ire_max_frag;
21944 	ill_t		*ill = ire_to_ill(ire);
21945 	int		clusterwide;
21946 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
21947 	int		ipsec_len;
21948 	mblk_t		*first_mp;
21949 	ipsec_out_t	*io;
21950 	boolean_t	conn_dontroute;		/* conn value for multicast */
21951 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
21952 	boolean_t	multicast_forward;	/* Should we forward ? */
21953 	boolean_t	unspec_src;
21954 	ill_t		*conn_outgoing_ill = NULL;
21955 	ill_t		*ire_ill;
21956 	ill_t		*ire1_ill;
21957 	ill_t		*out_ill;
21958 	uint32_t 	ill_index = 0;
21959 	boolean_t	multirt_send = B_FALSE;
21960 	int		err;
21961 	ipxmit_state_t	pktxmit_state;
21962 	ip_stack_t	*ipst = ire->ire_ipst;
21963 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
21964 
21965 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
21966 	    "ip_wput_ire_start: q %p", q);
21967 
21968 	multicast_forward = B_FALSE;
21969 	unspec_src = (connp != NULL && connp->conn_unspec_src);
21970 
21971 	if (ire->ire_flags & RTF_MULTIRT) {
21972 		/*
21973 		 * Multirouting case. The bucket where ire is stored
21974 		 * probably holds other RTF_MULTIRT flagged ire
21975 		 * to the destination. In this call to ip_wput_ire,
21976 		 * we attempt to send the packet through all
21977 		 * those ires. Thus, we first ensure that ire is the
21978 		 * first RTF_MULTIRT ire in the bucket,
21979 		 * before walking the ire list.
21980 		 */
21981 		ire_t *first_ire;
21982 		irb_t *irb = ire->ire_bucket;
21983 		ASSERT(irb != NULL);
21984 
21985 		/* Make sure we do not omit any multiroute ire. */
21986 		IRB_REFHOLD(irb);
21987 		for (first_ire = irb->irb_ire;
21988 		    first_ire != NULL;
21989 		    first_ire = first_ire->ire_next) {
21990 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
21991 			    (first_ire->ire_addr == ire->ire_addr) &&
21992 			    !(first_ire->ire_marks &
21993 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
21994 				break;
21995 			}
21996 		}
21997 
21998 		if ((first_ire != NULL) && (first_ire != ire)) {
21999 			IRE_REFHOLD(first_ire);
22000 			ire_refrele(ire);
22001 			ire = first_ire;
22002 			ill = ire_to_ill(ire);
22003 		}
22004 		IRB_REFRELE(irb);
22005 	}
22006 
22007 	/*
22008 	 * conn_outgoing_ill variable is used only in the broadcast loop.
22009 	 * for performance we don't grab the mutexs in the fastpath
22010 	 */
22011 	if ((connp != NULL) &&
22012 	    (ire->ire_type == IRE_BROADCAST) &&
22013 	    ((connp->conn_nofailover_ill != NULL) ||
22014 	    (connp->conn_outgoing_ill != NULL))) {
22015 		/*
22016 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
22017 		 * option. So, see if this endpoint is bound to a
22018 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
22019 		 * that if the interface is failed, we will still send
22020 		 * the packet on the same ill which is what we want.
22021 		 */
22022 		conn_outgoing_ill = conn_get_held_ill(connp,
22023 		    &connp->conn_nofailover_ill, &err);
22024 		if (err == ILL_LOOKUP_FAILED) {
22025 			ire_refrele(ire);
22026 			freemsg(mp);
22027 			return;
22028 		}
22029 		if (conn_outgoing_ill == NULL) {
22030 			/*
22031 			 * Choose a good ill in the group to send the
22032 			 * packets on.
22033 			 */
22034 			ire = conn_set_outgoing_ill(connp, ire,
22035 			    &conn_outgoing_ill);
22036 			if (ire == NULL) {
22037 				freemsg(mp);
22038 				return;
22039 			}
22040 		}
22041 	}
22042 
22043 	if (mp->b_datap->db_type != M_CTL) {
22044 		ipha = (ipha_t *)mp->b_rptr;
22045 	} else {
22046 		io = (ipsec_out_t *)mp->b_rptr;
22047 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22048 		ASSERT(zoneid == io->ipsec_out_zoneid);
22049 		ASSERT(zoneid != ALL_ZONES);
22050 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22051 		dst = ipha->ipha_dst;
22052 		/*
22053 		 * For the multicast case, ipsec_out carries conn_dontroute and
22054 		 * conn_multicast_loop as conn may not be available here. We
22055 		 * need this for multicast loopback and forwarding which is done
22056 		 * later in the code.
22057 		 */
22058 		if (CLASSD(dst)) {
22059 			conn_dontroute = io->ipsec_out_dontroute;
22060 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22061 			/*
22062 			 * If conn_dontroute is not set or conn_multicast_loop
22063 			 * is set, we need to do forwarding/loopback. For
22064 			 * datagrams from ip_wput_multicast, conn_dontroute is
22065 			 * set to B_TRUE and conn_multicast_loop is set to
22066 			 * B_FALSE so that we neither do forwarding nor
22067 			 * loopback.
22068 			 */
22069 			if (!conn_dontroute || conn_multicast_loop)
22070 				multicast_forward = B_TRUE;
22071 		}
22072 	}
22073 
22074 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22075 	    ire->ire_zoneid != ALL_ZONES) {
22076 		/*
22077 		 * When a zone sends a packet to another zone, we try to deliver
22078 		 * the packet under the same conditions as if the destination
22079 		 * was a real node on the network. To do so, we look for a
22080 		 * matching route in the forwarding table.
22081 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22082 		 * ip_newroute() does.
22083 		 * Note that IRE_LOCAL are special, since they are used
22084 		 * when the zoneid doesn't match in some cases. This means that
22085 		 * we need to handle ipha_src differently since ire_src_addr
22086 		 * belongs to the receiving zone instead of the sending zone.
22087 		 * When ip_restrict_interzone_loopback is set, then
22088 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22089 		 * for loopback between zones when the logical "Ethernet" would
22090 		 * have looped them back.
22091 		 */
22092 		ire_t *src_ire;
22093 
22094 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22095 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22096 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22097 		if (src_ire != NULL &&
22098 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22099 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22100 		    ire_local_same_ill_group(ire, src_ire))) {
22101 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22102 				ipha->ipha_src = src_ire->ire_src_addr;
22103 			ire_refrele(src_ire);
22104 		} else {
22105 			ire_refrele(ire);
22106 			if (conn_outgoing_ill != NULL)
22107 				ill_refrele(conn_outgoing_ill);
22108 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22109 			if (src_ire != NULL) {
22110 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22111 					ire_refrele(src_ire);
22112 					freemsg(mp);
22113 					return;
22114 				}
22115 				ire_refrele(src_ire);
22116 			}
22117 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22118 				/* Failed */
22119 				freemsg(mp);
22120 				return;
22121 			}
22122 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22123 			    ipst);
22124 			return;
22125 		}
22126 	}
22127 
22128 	if (mp->b_datap->db_type == M_CTL ||
22129 	    ipss->ipsec_outbound_v4_policy_present) {
22130 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22131 		    unspec_src, zoneid);
22132 		if (mp == NULL) {
22133 			ire_refrele(ire);
22134 			if (conn_outgoing_ill != NULL)
22135 				ill_refrele(conn_outgoing_ill);
22136 			return;
22137 		}
22138 	}
22139 
22140 	first_mp = mp;
22141 	ipsec_len = 0;
22142 
22143 	if (first_mp->b_datap->db_type == M_CTL) {
22144 		io = (ipsec_out_t *)first_mp->b_rptr;
22145 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22146 		mp = first_mp->b_cont;
22147 		ipsec_len = ipsec_out_extra_length(first_mp);
22148 		ASSERT(ipsec_len >= 0);
22149 		/* We already picked up the zoneid from the M_CTL above */
22150 		ASSERT(zoneid == io->ipsec_out_zoneid);
22151 		ASSERT(zoneid != ALL_ZONES);
22152 
22153 		/*
22154 		 * Drop M_CTL here if IPsec processing is not needed.
22155 		 * (Non-IPsec use of M_CTL extracted any information it
22156 		 * needed above).
22157 		 */
22158 		if (ipsec_len == 0) {
22159 			freeb(first_mp);
22160 			first_mp = mp;
22161 		}
22162 	}
22163 
22164 	/*
22165 	 * Fast path for ip_wput_ire
22166 	 */
22167 
22168 	ipha = (ipha_t *)mp->b_rptr;
22169 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22170 	dst = ipha->ipha_dst;
22171 
22172 	/*
22173 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22174 	 * if the socket is a SOCK_RAW type. The transport checksum should
22175 	 * be provided in the pre-built packet, so we don't need to compute it.
22176 	 * Also, other application set flags, like DF, should not be altered.
22177 	 * Other transport MUST pass down zero.
22178 	 */
22179 	ip_hdr_included = ipha->ipha_ident;
22180 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22181 
22182 	if (CLASSD(dst)) {
22183 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22184 		    ntohl(dst),
22185 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22186 		    ntohl(ire->ire_addr)));
22187 	}
22188 
22189 /* Macros to extract header fields from data already in registers */
22190 #ifdef	_BIG_ENDIAN
22191 #define	V_HLEN	(v_hlen_tos_len >> 24)
22192 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22193 #define	PROTO	(ttl_protocol & 0xFF)
22194 #else
22195 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22196 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22197 #define	PROTO	(ttl_protocol >> 8)
22198 #endif
22199 
22200 
22201 	orig_src = src = ipha->ipha_src;
22202 	/* (The loop back to "another" is explained down below.) */
22203 another:;
22204 	/*
22205 	 * Assign an ident value for this packet.  We assign idents on
22206 	 * a per destination basis out of the IRE.  There could be
22207 	 * other threads targeting the same destination, so we have to
22208 	 * arrange for a atomic increment.  Note that we use a 32-bit
22209 	 * atomic add because it has better performance than its
22210 	 * 16-bit sibling.
22211 	 *
22212 	 * If running in cluster mode and if the source address
22213 	 * belongs to a replicated service then vector through
22214 	 * cl_inet_ipident vector to allocate ip identifier
22215 	 * NOTE: This is a contract private interface with the
22216 	 * clustering group.
22217 	 */
22218 	clusterwide = 0;
22219 	if (cl_inet_ipident) {
22220 		ASSERT(cl_inet_isclusterwide);
22221 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
22222 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
22223 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
22224 			    AF_INET, (uint8_t *)(uintptr_t)src,
22225 			    (uint8_t *)(uintptr_t)dst);
22226 			clusterwide = 1;
22227 		}
22228 	}
22229 	if (!clusterwide) {
22230 		ipha->ipha_ident =
22231 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22232 	}
22233 
22234 #ifndef _BIG_ENDIAN
22235 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22236 #endif
22237 
22238 	/*
22239 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22240 	 * This is needed to obey conn_unspec_src when packets go through
22241 	 * ip_newroute + arp.
22242 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22243 	 */
22244 	if (src == INADDR_ANY && !unspec_src) {
22245 		/*
22246 		 * Assign the appropriate source address from the IRE if none
22247 		 * was specified.
22248 		 */
22249 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22250 
22251 		/*
22252 		 * With IP multipathing, broadcast packets are sent on the ire
22253 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
22254 		 * the group. However, this ire might not be in the same zone so
22255 		 * we can't always use its source address. We look for a
22256 		 * broadcast ire in the same group and in the right zone.
22257 		 */
22258 		if (ire->ire_type == IRE_BROADCAST &&
22259 		    ire->ire_zoneid != zoneid) {
22260 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
22261 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
22262 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
22263 			if (src_ire != NULL) {
22264 				src = src_ire->ire_src_addr;
22265 				ire_refrele(src_ire);
22266 			} else {
22267 				ire_refrele(ire);
22268 				if (conn_outgoing_ill != NULL)
22269 					ill_refrele(conn_outgoing_ill);
22270 				freemsg(first_mp);
22271 				if (ill != NULL) {
22272 					BUMP_MIB(ill->ill_ip_mib,
22273 					    ipIfStatsOutDiscards);
22274 				} else {
22275 					BUMP_MIB(&ipst->ips_ip_mib,
22276 					    ipIfStatsOutDiscards);
22277 				}
22278 				return;
22279 			}
22280 		} else {
22281 			src = ire->ire_src_addr;
22282 		}
22283 
22284 		if (connp == NULL) {
22285 			ip1dbg(("ip_wput_ire: no connp and no src "
22286 			    "address for dst 0x%x, using src 0x%x\n",
22287 			    ntohl(dst),
22288 			    ntohl(src)));
22289 		}
22290 		ipha->ipha_src = src;
22291 	}
22292 	stq = ire->ire_stq;
22293 
22294 	/*
22295 	 * We only allow ire chains for broadcasts since there will
22296 	 * be multiple IRE_CACHE entries for the same multicast
22297 	 * address (one per ipif).
22298 	 */
22299 	next_mp = NULL;
22300 
22301 	/* broadcast packet */
22302 	if (ire->ire_type == IRE_BROADCAST)
22303 		goto broadcast;
22304 
22305 	/* loopback ? */
22306 	if (stq == NULL)
22307 		goto nullstq;
22308 
22309 	/* The ill_index for outbound ILL */
22310 	ill_index = Q_TO_INDEX(stq);
22311 
22312 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22313 	ttl_protocol = ((uint16_t *)ipha)[4];
22314 
22315 	/* pseudo checksum (do it in parts for IP header checksum) */
22316 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22317 
22318 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22319 		queue_t *dev_q = stq->q_next;
22320 
22321 		/* flow controlled */
22322 		if ((dev_q->q_next || dev_q->q_first) &&
22323 		    !canput(dev_q))
22324 			goto blocked;
22325 		if ((PROTO == IPPROTO_UDP) &&
22326 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22327 			hlen = (V_HLEN & 0xF) << 2;
22328 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22329 			if (*up != 0) {
22330 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22331 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22332 				/* Software checksum? */
22333 				if (DB_CKSUMFLAGS(mp) == 0) {
22334 					IP_STAT(ipst, ip_out_sw_cksum);
22335 					IP_STAT_UPDATE(ipst,
22336 					    ip_udp_out_sw_cksum_bytes,
22337 					    LENGTH - hlen);
22338 				}
22339 			}
22340 		}
22341 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22342 		hlen = (V_HLEN & 0xF) << 2;
22343 		if (PROTO == IPPROTO_TCP) {
22344 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22345 			/*
22346 			 * The packet header is processed once and for all, even
22347 			 * in the multirouting case. We disable hardware
22348 			 * checksum if the packet is multirouted, as it will be
22349 			 * replicated via several interfaces, and not all of
22350 			 * them may have this capability.
22351 			 */
22352 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22353 			    LENGTH, max_frag, ipsec_len, cksum);
22354 			/* Software checksum? */
22355 			if (DB_CKSUMFLAGS(mp) == 0) {
22356 				IP_STAT(ipst, ip_out_sw_cksum);
22357 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22358 				    LENGTH - hlen);
22359 			}
22360 		} else {
22361 			sctp_hdr_t	*sctph;
22362 
22363 			ASSERT(PROTO == IPPROTO_SCTP);
22364 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22365 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22366 			/*
22367 			 * Zero out the checksum field to ensure proper
22368 			 * checksum calculation.
22369 			 */
22370 			sctph->sh_chksum = 0;
22371 #ifdef	DEBUG
22372 			if (!skip_sctp_cksum)
22373 #endif
22374 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22375 		}
22376 	}
22377 
22378 	/*
22379 	 * If this is a multicast packet and originated from ip_wput
22380 	 * we need to do loopback and forwarding checks. If it comes
22381 	 * from ip_wput_multicast, we SHOULD not do this.
22382 	 */
22383 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22384 
22385 	/* checksum */
22386 	cksum += ttl_protocol;
22387 
22388 	/* fragment the packet */
22389 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22390 		goto fragmentit;
22391 	/*
22392 	 * Don't use frag_flag if packet is pre-built or source
22393 	 * routed or if multicast (since multicast packets do
22394 	 * not solicit ICMP "packet too big" messages).
22395 	 */
22396 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22397 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22398 	    !ip_source_route_included(ipha)) &&
22399 	    !CLASSD(ipha->ipha_dst))
22400 		ipha->ipha_fragment_offset_and_flags |=
22401 		    htons(ire->ire_frag_flag);
22402 
22403 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22404 		/* calculate IP header checksum */
22405 		cksum += ipha->ipha_ident;
22406 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22407 		cksum += ipha->ipha_fragment_offset_and_flags;
22408 
22409 		/* IP options present */
22410 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22411 		if (hlen)
22412 			goto checksumoptions;
22413 
22414 		/* calculate hdr checksum */
22415 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22416 		cksum = ~(cksum + (cksum >> 16));
22417 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22418 	}
22419 	if (ipsec_len != 0) {
22420 		/*
22421 		 * We will do the rest of the processing after
22422 		 * we come back from IPsec in ip_wput_ipsec_out().
22423 		 */
22424 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22425 
22426 		io = (ipsec_out_t *)first_mp->b_rptr;
22427 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
22428 		    ill_phyint->phyint_ifindex;
22429 
22430 		ipsec_out_process(q, first_mp, ire, ill_index);
22431 		ire_refrele(ire);
22432 		if (conn_outgoing_ill != NULL)
22433 			ill_refrele(conn_outgoing_ill);
22434 		return;
22435 	}
22436 
22437 	/*
22438 	 * In most cases, the emission loop below is entered only
22439 	 * once. Only in the case where the ire holds the
22440 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22441 	 * flagged ires in the bucket, and send the packet
22442 	 * through all crossed RTF_MULTIRT routes.
22443 	 */
22444 	if (ire->ire_flags & RTF_MULTIRT) {
22445 		multirt_send = B_TRUE;
22446 	}
22447 	do {
22448 		if (multirt_send) {
22449 			irb_t *irb;
22450 			/*
22451 			 * We are in a multiple send case, need to get
22452 			 * the next ire and make a duplicate of the packet.
22453 			 * ire1 holds here the next ire to process in the
22454 			 * bucket. If multirouting is expected,
22455 			 * any non-RTF_MULTIRT ire that has the
22456 			 * right destination address is ignored.
22457 			 */
22458 			irb = ire->ire_bucket;
22459 			ASSERT(irb != NULL);
22460 
22461 			IRB_REFHOLD(irb);
22462 			for (ire1 = ire->ire_next;
22463 			    ire1 != NULL;
22464 			    ire1 = ire1->ire_next) {
22465 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22466 					continue;
22467 				if (ire1->ire_addr != ire->ire_addr)
22468 					continue;
22469 				if (ire1->ire_marks &
22470 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
22471 					continue;
22472 
22473 				/* Got one */
22474 				IRE_REFHOLD(ire1);
22475 				break;
22476 			}
22477 			IRB_REFRELE(irb);
22478 
22479 			if (ire1 != NULL) {
22480 				next_mp = copyb(mp);
22481 				if ((next_mp == NULL) ||
22482 				    ((mp->b_cont != NULL) &&
22483 				    ((next_mp->b_cont =
22484 				    dupmsg(mp->b_cont)) == NULL))) {
22485 					freemsg(next_mp);
22486 					next_mp = NULL;
22487 					ire_refrele(ire1);
22488 					ire1 = NULL;
22489 				}
22490 			}
22491 
22492 			/* Last multiroute ire; don't loop anymore. */
22493 			if (ire1 == NULL) {
22494 				multirt_send = B_FALSE;
22495 			}
22496 		}
22497 
22498 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22499 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22500 		    mblk_t *, mp);
22501 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22502 		    ipst->ips_ipv4firewall_physical_out,
22503 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, ipst);
22504 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22505 		if (mp == NULL)
22506 			goto release_ire_and_ill;
22507 
22508 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22509 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22510 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE);
22511 		if ((pktxmit_state == SEND_FAILED) ||
22512 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22513 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22514 			    "- packet dropped\n"));
22515 release_ire_and_ill:
22516 			ire_refrele(ire);
22517 			if (next_mp != NULL) {
22518 				freemsg(next_mp);
22519 				ire_refrele(ire1);
22520 			}
22521 			if (conn_outgoing_ill != NULL)
22522 				ill_refrele(conn_outgoing_ill);
22523 			return;
22524 		}
22525 
22526 		if (CLASSD(dst)) {
22527 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22528 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22529 			    LENGTH);
22530 		}
22531 
22532 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22533 		    "ip_wput_ire_end: q %p (%S)",
22534 		    q, "last copy out");
22535 		IRE_REFRELE(ire);
22536 
22537 		if (multirt_send) {
22538 			ASSERT(ire1);
22539 			/*
22540 			 * Proceed with the next RTF_MULTIRT ire,
22541 			 * Also set up the send-to queue accordingly.
22542 			 */
22543 			ire = ire1;
22544 			ire1 = NULL;
22545 			stq = ire->ire_stq;
22546 			mp = next_mp;
22547 			next_mp = NULL;
22548 			ipha = (ipha_t *)mp->b_rptr;
22549 			ill_index = Q_TO_INDEX(stq);
22550 			ill = (ill_t *)stq->q_ptr;
22551 		}
22552 	} while (multirt_send);
22553 	if (conn_outgoing_ill != NULL)
22554 		ill_refrele(conn_outgoing_ill);
22555 	return;
22556 
22557 	/*
22558 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22559 	 */
22560 broadcast:
22561 	{
22562 		/*
22563 		 * Avoid broadcast storms by setting the ttl to 1
22564 		 * for broadcasts. This parameter can be set
22565 		 * via ndd, so make sure that for the SO_DONTROUTE
22566 		 * case that ipha_ttl is always set to 1.
22567 		 * In the event that we are replying to incoming
22568 		 * ICMP packets, conn could be NULL.
22569 		 */
22570 		if ((connp != NULL) && connp->conn_dontroute)
22571 			ipha->ipha_ttl = 1;
22572 		else
22573 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22574 
22575 		/*
22576 		 * Note that we are not doing a IRB_REFHOLD here.
22577 		 * Actually we don't care if the list changes i.e
22578 		 * if somebody deletes an IRE from the list while
22579 		 * we drop the lock, the next time we come around
22580 		 * ire_next will be NULL and hence we won't send
22581 		 * out multiple copies which is fine.
22582 		 */
22583 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22584 		ire1 = ire->ire_next;
22585 		if (conn_outgoing_ill != NULL) {
22586 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22587 				ASSERT(ire1 == ire->ire_next);
22588 				if (ire1 != NULL && ire1->ire_addr == dst) {
22589 					ire_refrele(ire);
22590 					ire = ire1;
22591 					IRE_REFHOLD(ire);
22592 					ire1 = ire->ire_next;
22593 					continue;
22594 				}
22595 				rw_exit(&ire->ire_bucket->irb_lock);
22596 				/* Did not find a matching ill */
22597 				ip1dbg(("ip_wput_ire: broadcast with no "
22598 				    "matching IP_BOUND_IF ill %s dst %x\n",
22599 				    conn_outgoing_ill->ill_name, dst));
22600 				freemsg(first_mp);
22601 				if (ire != NULL)
22602 					ire_refrele(ire);
22603 				ill_refrele(conn_outgoing_ill);
22604 				return;
22605 			}
22606 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22607 			/*
22608 			 * If the next IRE has the same address and is not one
22609 			 * of the two copies that we need to send, try to see
22610 			 * whether this copy should be sent at all. This
22611 			 * assumes that we insert loopbacks first and then
22612 			 * non-loopbacks. This is acheived by inserting the
22613 			 * loopback always before non-loopback.
22614 			 * This is used to send a single copy of a broadcast
22615 			 * packet out all physical interfaces that have an
22616 			 * matching IRE_BROADCAST while also looping
22617 			 * back one copy (to ip_wput_local) for each
22618 			 * matching physical interface. However, we avoid
22619 			 * sending packets out different logical that match by
22620 			 * having ipif_up/ipif_down supress duplicate
22621 			 * IRE_BROADCASTS.
22622 			 *
22623 			 * This feature is currently used to get broadcasts
22624 			 * sent to multiple interfaces, when the broadcast
22625 			 * address being used applies to multiple interfaces.
22626 			 * For example, a whole net broadcast will be
22627 			 * replicated on every connected subnet of
22628 			 * the target net.
22629 			 *
22630 			 * Each zone has its own set of IRE_BROADCASTs, so that
22631 			 * we're able to distribute inbound packets to multiple
22632 			 * zones who share a broadcast address. We avoid looping
22633 			 * back outbound packets in different zones but on the
22634 			 * same ill, as the application would see duplicates.
22635 			 *
22636 			 * If the interfaces are part of the same group,
22637 			 * we would want to send only one copy out for
22638 			 * whole group.
22639 			 *
22640 			 * This logic assumes that ire_add_v4() groups the
22641 			 * IRE_BROADCAST entries so that those with the same
22642 			 * ire_addr and ill_group are kept together.
22643 			 */
22644 			ire_ill = ire->ire_ipif->ipif_ill;
22645 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
22646 				if (ire_ill->ill_group != NULL &&
22647 				    (ire->ire_marks & IRE_MARK_NORECV)) {
22648 					/*
22649 					 * If the current zone only has an ire
22650 					 * broadcast for this address marked
22651 					 * NORECV, the ire we want is ahead in
22652 					 * the bucket, so we look it up
22653 					 * deliberately ignoring the zoneid.
22654 					 */
22655 					for (ire1 = ire->ire_bucket->irb_ire;
22656 					    ire1 != NULL;
22657 					    ire1 = ire1->ire_next) {
22658 						ire1_ill =
22659 						    ire1->ire_ipif->ipif_ill;
22660 						if (ire1->ire_addr != dst)
22661 							continue;
22662 						/* skip over the current ire */
22663 						if (ire1 == ire)
22664 							continue;
22665 						/* skip over deleted ires */
22666 						if (ire1->ire_marks &
22667 						    IRE_MARK_CONDEMNED)
22668 							continue;
22669 						/*
22670 						 * non-loopback ire in our
22671 						 * group: use it for the next
22672 						 * pass in the loop
22673 						 */
22674 						if (ire1->ire_stq != NULL &&
22675 						    ire1_ill->ill_group ==
22676 						    ire_ill->ill_group)
22677 							break;
22678 					}
22679 				}
22680 			} else {
22681 				while (ire1 != NULL && ire1->ire_addr == dst) {
22682 					ire1_ill = ire1->ire_ipif->ipif_ill;
22683 					/*
22684 					 * We can have two broadcast ires on the
22685 					 * same ill in different zones; here
22686 					 * we'll send a copy of the packet on
22687 					 * each ill and the fanout code will
22688 					 * call conn_wantpacket() to check that
22689 					 * the zone has the broadcast address
22690 					 * configured on the ill. If the two
22691 					 * ires are in the same group we only
22692 					 * send one copy up.
22693 					 */
22694 					if (ire1_ill != ire_ill &&
22695 					    (ire1_ill->ill_group == NULL ||
22696 					    ire_ill->ill_group == NULL ||
22697 					    ire1_ill->ill_group !=
22698 					    ire_ill->ill_group)) {
22699 						break;
22700 					}
22701 					ire1 = ire1->ire_next;
22702 				}
22703 			}
22704 		}
22705 		ASSERT(multirt_send == B_FALSE);
22706 		if (ire1 != NULL && ire1->ire_addr == dst) {
22707 			if ((ire->ire_flags & RTF_MULTIRT) &&
22708 			    (ire1->ire_flags & RTF_MULTIRT)) {
22709 				/*
22710 				 * We are in the multirouting case.
22711 				 * The message must be sent at least
22712 				 * on both ires. These ires have been
22713 				 * inserted AFTER the standard ones
22714 				 * in ip_rt_add(). There are thus no
22715 				 * other ire entries for the destination
22716 				 * address in the rest of the bucket
22717 				 * that do not have the RTF_MULTIRT
22718 				 * flag. We don't process a copy
22719 				 * of the message here. This will be
22720 				 * done in the final sending loop.
22721 				 */
22722 				multirt_send = B_TRUE;
22723 			} else {
22724 				next_mp = ip_copymsg(first_mp);
22725 				if (next_mp != NULL)
22726 					IRE_REFHOLD(ire1);
22727 			}
22728 		}
22729 		rw_exit(&ire->ire_bucket->irb_lock);
22730 	}
22731 
22732 	if (stq) {
22733 		/*
22734 		 * A non-NULL send-to queue means this packet is going
22735 		 * out of this machine.
22736 		 */
22737 		out_ill = (ill_t *)stq->q_ptr;
22738 
22739 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
22740 		ttl_protocol = ((uint16_t *)ipha)[4];
22741 		/*
22742 		 * We accumulate the pseudo header checksum in cksum.
22743 		 * This is pretty hairy code, so watch close.  One
22744 		 * thing to keep in mind is that UDP and TCP have
22745 		 * stored their respective datagram lengths in their
22746 		 * checksum fields.  This lines things up real nice.
22747 		 */
22748 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22749 		    (src >> 16) + (src & 0xFFFF);
22750 		/*
22751 		 * We assume the udp checksum field contains the
22752 		 * length, so to compute the pseudo header checksum,
22753 		 * all we need is the protocol number and src/dst.
22754 		 */
22755 		/* Provide the checksums for UDP and TCP. */
22756 		if ((PROTO == IPPROTO_TCP) &&
22757 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22758 			/* hlen gets the number of uchar_ts in the IP header */
22759 			hlen = (V_HLEN & 0xF) << 2;
22760 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22761 			IP_STAT(ipst, ip_out_sw_cksum);
22762 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22763 			    LENGTH - hlen);
22764 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22765 		} else if (PROTO == IPPROTO_SCTP &&
22766 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22767 			sctp_hdr_t	*sctph;
22768 
22769 			hlen = (V_HLEN & 0xF) << 2;
22770 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22771 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22772 			sctph->sh_chksum = 0;
22773 #ifdef	DEBUG
22774 			if (!skip_sctp_cksum)
22775 #endif
22776 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22777 		} else {
22778 			queue_t *dev_q = stq->q_next;
22779 
22780 			if ((dev_q->q_next || dev_q->q_first) &&
22781 			    !canput(dev_q)) {
22782 blocked:
22783 				ipha->ipha_ident = ip_hdr_included;
22784 				/*
22785 				 * If we don't have a conn to apply
22786 				 * backpressure, free the message.
22787 				 * In the ire_send path, we don't know
22788 				 * the position to requeue the packet. Rather
22789 				 * than reorder packets, we just drop this
22790 				 * packet.
22791 				 */
22792 				if (ipst->ips_ip_output_queue &&
22793 				    connp != NULL &&
22794 				    caller != IRE_SEND) {
22795 					if (caller == IP_WSRV) {
22796 						connp->conn_did_putbq = 1;
22797 						(void) putbq(connp->conn_wq,
22798 						    first_mp);
22799 						conn_drain_insert(connp);
22800 						/*
22801 						 * This is the service thread,
22802 						 * and the queue is already
22803 						 * noenabled. The check for
22804 						 * canput and the putbq is not
22805 						 * atomic. So we need to check
22806 						 * again.
22807 						 */
22808 						if (canput(stq->q_next))
22809 							connp->conn_did_putbq
22810 							    = 0;
22811 						IP_STAT(ipst, ip_conn_flputbq);
22812 					} else {
22813 						/*
22814 						 * We are not the service proc.
22815 						 * ip_wsrv will be scheduled or
22816 						 * is already running.
22817 						 */
22818 						(void) putq(connp->conn_wq,
22819 						    first_mp);
22820 					}
22821 				} else {
22822 					out_ill = (ill_t *)stq->q_ptr;
22823 					BUMP_MIB(out_ill->ill_ip_mib,
22824 					    ipIfStatsOutDiscards);
22825 					freemsg(first_mp);
22826 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22827 					    "ip_wput_ire_end: q %p (%S)",
22828 					    q, "discard");
22829 				}
22830 				ire_refrele(ire);
22831 				if (next_mp) {
22832 					ire_refrele(ire1);
22833 					freemsg(next_mp);
22834 				}
22835 				if (conn_outgoing_ill != NULL)
22836 					ill_refrele(conn_outgoing_ill);
22837 				return;
22838 			}
22839 			if ((PROTO == IPPROTO_UDP) &&
22840 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
22841 				/*
22842 				 * hlen gets the number of uchar_ts in the
22843 				 * IP header
22844 				 */
22845 				hlen = (V_HLEN & 0xF) << 2;
22846 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22847 				max_frag = ire->ire_max_frag;
22848 				if (*up != 0) {
22849 					IP_CKSUM_XMIT(out_ill, ire, mp, ipha,
22850 					    up, PROTO, hlen, LENGTH, max_frag,
22851 					    ipsec_len, cksum);
22852 					/* Software checksum? */
22853 					if (DB_CKSUMFLAGS(mp) == 0) {
22854 						IP_STAT(ipst, ip_out_sw_cksum);
22855 						IP_STAT_UPDATE(ipst,
22856 						    ip_udp_out_sw_cksum_bytes,
22857 						    LENGTH - hlen);
22858 					}
22859 				}
22860 			}
22861 		}
22862 		/*
22863 		 * Need to do this even when fragmenting. The local
22864 		 * loopback can be done without computing checksums
22865 		 * but forwarding out other interface must be done
22866 		 * after the IP checksum (and ULP checksums) have been
22867 		 * computed.
22868 		 *
22869 		 * NOTE : multicast_forward is set only if this packet
22870 		 * originated from ip_wput. For packets originating from
22871 		 * ip_wput_multicast, it is not set.
22872 		 */
22873 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
22874 multi_loopback:
22875 			ip2dbg(("ip_wput: multicast, loop %d\n",
22876 			    conn_multicast_loop));
22877 
22878 			/*  Forget header checksum offload */
22879 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
22880 
22881 			/*
22882 			 * Local loopback of multicasts?  Check the
22883 			 * ill.
22884 			 *
22885 			 * Note that the loopback function will not come
22886 			 * in through ip_rput - it will only do the
22887 			 * client fanout thus we need to do an mforward
22888 			 * as well.  The is different from the BSD
22889 			 * logic.
22890 			 */
22891 			if (ill != NULL) {
22892 				ilm_t	*ilm;
22893 
22894 				ILM_WALKER_HOLD(ill);
22895 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
22896 				    ALL_ZONES);
22897 				ILM_WALKER_RELE(ill);
22898 				if (ilm != NULL) {
22899 					/*
22900 					 * Pass along the virtual output q.
22901 					 * ip_wput_local() will distribute the
22902 					 * packet to all the matching zones,
22903 					 * except the sending zone when
22904 					 * IP_MULTICAST_LOOP is false.
22905 					 */
22906 					ip_multicast_loopback(q, ill, first_mp,
22907 					    conn_multicast_loop ? 0 :
22908 					    IP_FF_NO_MCAST_LOOP, zoneid);
22909 				}
22910 			}
22911 			if (ipha->ipha_ttl == 0) {
22912 				/*
22913 				 * 0 => only to this host i.e. we are
22914 				 * done. We are also done if this was the
22915 				 * loopback interface since it is sufficient
22916 				 * to loopback one copy of a multicast packet.
22917 				 */
22918 				freemsg(first_mp);
22919 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22920 				    "ip_wput_ire_end: q %p (%S)",
22921 				    q, "loopback");
22922 				ire_refrele(ire);
22923 				if (conn_outgoing_ill != NULL)
22924 					ill_refrele(conn_outgoing_ill);
22925 				return;
22926 			}
22927 			/*
22928 			 * ILLF_MULTICAST is checked in ip_newroute
22929 			 * i.e. we don't need to check it here since
22930 			 * all IRE_CACHEs come from ip_newroute.
22931 			 * For multicast traffic, SO_DONTROUTE is interpreted
22932 			 * to mean only send the packet out the interface
22933 			 * (optionally specified with IP_MULTICAST_IF)
22934 			 * and do not forward it out additional interfaces.
22935 			 * RSVP and the rsvp daemon is an example of a
22936 			 * protocol and user level process that
22937 			 * handles it's own routing. Hence, it uses the
22938 			 * SO_DONTROUTE option to accomplish this.
22939 			 */
22940 
22941 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
22942 			    ill != NULL) {
22943 				/* Unconditionally redo the checksum */
22944 				ipha->ipha_hdr_checksum = 0;
22945 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22946 
22947 				/*
22948 				 * If this needs to go out secure, we need
22949 				 * to wait till we finish the IPsec
22950 				 * processing.
22951 				 */
22952 				if (ipsec_len == 0 &&
22953 				    ip_mforward(ill, ipha, mp)) {
22954 					freemsg(first_mp);
22955 					ip1dbg(("ip_wput: mforward failed\n"));
22956 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22957 					    "ip_wput_ire_end: q %p (%S)",
22958 					    q, "mforward failed");
22959 					ire_refrele(ire);
22960 					if (conn_outgoing_ill != NULL)
22961 						ill_refrele(conn_outgoing_ill);
22962 					return;
22963 				}
22964 			}
22965 		}
22966 		max_frag = ire->ire_max_frag;
22967 		cksum += ttl_protocol;
22968 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
22969 			/* No fragmentation required for this one. */
22970 			/*
22971 			 * Don't use frag_flag if packet is pre-built or source
22972 			 * routed or if multicast (since multicast packets do
22973 			 * not solicit ICMP "packet too big" messages).
22974 			 */
22975 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22976 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22977 			    !ip_source_route_included(ipha)) &&
22978 			    !CLASSD(ipha->ipha_dst))
22979 				ipha->ipha_fragment_offset_and_flags |=
22980 				    htons(ire->ire_frag_flag);
22981 
22982 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22983 				/* Complete the IP header checksum. */
22984 				cksum += ipha->ipha_ident;
22985 				cksum += (v_hlen_tos_len >> 16)+
22986 				    (v_hlen_tos_len & 0xFFFF);
22987 				cksum += ipha->ipha_fragment_offset_and_flags;
22988 				hlen = (V_HLEN & 0xF) -
22989 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22990 				if (hlen) {
22991 checksumoptions:
22992 					/*
22993 					 * Account for the IP Options in the IP
22994 					 * header checksum.
22995 					 */
22996 					up = (uint16_t *)(rptr+
22997 					    IP_SIMPLE_HDR_LENGTH);
22998 					do {
22999 						cksum += up[0];
23000 						cksum += up[1];
23001 						up += 2;
23002 					} while (--hlen);
23003 				}
23004 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
23005 				cksum = ~(cksum + (cksum >> 16));
23006 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
23007 			}
23008 			if (ipsec_len != 0) {
23009 				ipsec_out_process(q, first_mp, ire, ill_index);
23010 				if (!next_mp) {
23011 					ire_refrele(ire);
23012 					if (conn_outgoing_ill != NULL)
23013 						ill_refrele(conn_outgoing_ill);
23014 					return;
23015 				}
23016 				goto next;
23017 			}
23018 
23019 			/*
23020 			 * multirt_send has already been handled
23021 			 * for broadcast, but not yet for multicast
23022 			 * or IP options.
23023 			 */
23024 			if (next_mp == NULL) {
23025 				if (ire->ire_flags & RTF_MULTIRT) {
23026 					multirt_send = B_TRUE;
23027 				}
23028 			}
23029 
23030 			/*
23031 			 * In most cases, the emission loop below is
23032 			 * entered only once. Only in the case where
23033 			 * the ire holds the RTF_MULTIRT flag, do we loop
23034 			 * to process all RTF_MULTIRT ires in the bucket,
23035 			 * and send the packet through all crossed
23036 			 * RTF_MULTIRT routes.
23037 			 */
23038 			do {
23039 				if (multirt_send) {
23040 					irb_t *irb;
23041 
23042 					irb = ire->ire_bucket;
23043 					ASSERT(irb != NULL);
23044 					/*
23045 					 * We are in a multiple send case,
23046 					 * need to get the next IRE and make
23047 					 * a duplicate of the packet.
23048 					 */
23049 					IRB_REFHOLD(irb);
23050 					for (ire1 = ire->ire_next;
23051 					    ire1 != NULL;
23052 					    ire1 = ire1->ire_next) {
23053 						if (!(ire1->ire_flags &
23054 						    RTF_MULTIRT)) {
23055 							continue;
23056 						}
23057 						if (ire1->ire_addr !=
23058 						    ire->ire_addr) {
23059 							continue;
23060 						}
23061 						if (ire1->ire_marks &
23062 						    (IRE_MARK_CONDEMNED|
23063 						    IRE_MARK_HIDDEN)) {
23064 							continue;
23065 						}
23066 
23067 						/* Got one */
23068 						IRE_REFHOLD(ire1);
23069 						break;
23070 					}
23071 					IRB_REFRELE(irb);
23072 
23073 					if (ire1 != NULL) {
23074 						next_mp = copyb(mp);
23075 						if ((next_mp == NULL) ||
23076 						    ((mp->b_cont != NULL) &&
23077 						    ((next_mp->b_cont =
23078 						    dupmsg(mp->b_cont))
23079 						    == NULL))) {
23080 							freemsg(next_mp);
23081 							next_mp = NULL;
23082 							ire_refrele(ire1);
23083 							ire1 = NULL;
23084 						}
23085 					}
23086 
23087 					/*
23088 					 * Last multiroute ire; don't loop
23089 					 * anymore. The emission is over
23090 					 * and next_mp is NULL.
23091 					 */
23092 					if (ire1 == NULL) {
23093 						multirt_send = B_FALSE;
23094 					}
23095 				}
23096 
23097 				out_ill = ire_to_ill(ire);
23098 				DTRACE_PROBE4(ip4__physical__out__start,
23099 				    ill_t *, NULL,
23100 				    ill_t *, out_ill,
23101 				    ipha_t *, ipha, mblk_t *, mp);
23102 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23103 				    ipst->ips_ipv4firewall_physical_out,
23104 				    NULL, out_ill, ipha, mp, mp, ipst);
23105 				DTRACE_PROBE1(ip4__physical__out__end,
23106 				    mblk_t *, mp);
23107 				if (mp == NULL)
23108 					goto release_ire_and_ill_2;
23109 
23110 				ASSERT(ipsec_len == 0);
23111 				mp->b_prev =
23112 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23113 				DTRACE_PROBE2(ip__xmit__2,
23114 				    mblk_t *, mp, ire_t *, ire);
23115 				pktxmit_state = ip_xmit_v4(mp, ire,
23116 				    NULL, B_TRUE);
23117 				if ((pktxmit_state == SEND_FAILED) ||
23118 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23119 release_ire_and_ill_2:
23120 					if (next_mp) {
23121 						freemsg(next_mp);
23122 						ire_refrele(ire1);
23123 					}
23124 					ire_refrele(ire);
23125 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23126 					    "ip_wput_ire_end: q %p (%S)",
23127 					    q, "discard MDATA");
23128 					if (conn_outgoing_ill != NULL)
23129 						ill_refrele(conn_outgoing_ill);
23130 					return;
23131 				}
23132 
23133 				if (CLASSD(dst)) {
23134 					BUMP_MIB(out_ill->ill_ip_mib,
23135 					    ipIfStatsHCOutMcastPkts);
23136 					UPDATE_MIB(out_ill->ill_ip_mib,
23137 					    ipIfStatsHCOutMcastOctets,
23138 					    LENGTH);
23139 				} else if (ire->ire_type == IRE_BROADCAST) {
23140 					BUMP_MIB(out_ill->ill_ip_mib,
23141 					    ipIfStatsHCOutBcastPkts);
23142 				}
23143 
23144 				if (multirt_send) {
23145 					/*
23146 					 * We are in a multiple send case,
23147 					 * need to re-enter the sending loop
23148 					 * using the next ire.
23149 					 */
23150 					ire_refrele(ire);
23151 					ire = ire1;
23152 					stq = ire->ire_stq;
23153 					mp = next_mp;
23154 					next_mp = NULL;
23155 					ipha = (ipha_t *)mp->b_rptr;
23156 					ill_index = Q_TO_INDEX(stq);
23157 				}
23158 			} while (multirt_send);
23159 
23160 			if (!next_mp) {
23161 				/*
23162 				 * Last copy going out (the ultra-common
23163 				 * case).  Note that we intentionally replicate
23164 				 * the putnext rather than calling it before
23165 				 * the next_mp check in hopes of a little
23166 				 * tail-call action out of the compiler.
23167 				 */
23168 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23169 				    "ip_wput_ire_end: q %p (%S)",
23170 				    q, "last copy out(1)");
23171 				ire_refrele(ire);
23172 				if (conn_outgoing_ill != NULL)
23173 					ill_refrele(conn_outgoing_ill);
23174 				return;
23175 			}
23176 			/* More copies going out below. */
23177 		} else {
23178 			int offset;
23179 fragmentit:
23180 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23181 			/*
23182 			 * If this would generate a icmp_frag_needed message,
23183 			 * we need to handle it before we do the IPsec
23184 			 * processing. Otherwise, we need to strip the IPsec
23185 			 * headers before we send up the message to the ULPs
23186 			 * which becomes messy and difficult.
23187 			 */
23188 			if (ipsec_len != 0) {
23189 				if ((max_frag < (unsigned int)(LENGTH +
23190 				    ipsec_len)) && (offset & IPH_DF)) {
23191 					out_ill = (ill_t *)stq->q_ptr;
23192 					BUMP_MIB(out_ill->ill_ip_mib,
23193 					    ipIfStatsOutFragFails);
23194 					BUMP_MIB(out_ill->ill_ip_mib,
23195 					    ipIfStatsOutFragReqds);
23196 					ipha->ipha_hdr_checksum = 0;
23197 					ipha->ipha_hdr_checksum =
23198 					    (uint16_t)ip_csum_hdr(ipha);
23199 					icmp_frag_needed(ire->ire_stq, first_mp,
23200 					    max_frag, zoneid, ipst);
23201 					if (!next_mp) {
23202 						ire_refrele(ire);
23203 						if (conn_outgoing_ill != NULL) {
23204 							ill_refrele(
23205 							    conn_outgoing_ill);
23206 						}
23207 						return;
23208 					}
23209 				} else {
23210 					/*
23211 					 * This won't cause a icmp_frag_needed
23212 					 * message. to be generated. Send it on
23213 					 * the wire. Note that this could still
23214 					 * cause fragmentation and all we
23215 					 * do is the generation of the message
23216 					 * to the ULP if needed before IPsec.
23217 					 */
23218 					if (!next_mp) {
23219 						ipsec_out_process(q, first_mp,
23220 						    ire, ill_index);
23221 						TRACE_2(TR_FAC_IP,
23222 						    TR_IP_WPUT_IRE_END,
23223 						    "ip_wput_ire_end: q %p "
23224 						    "(%S)", q,
23225 						    "last ipsec_out_process");
23226 						ire_refrele(ire);
23227 						if (conn_outgoing_ill != NULL) {
23228 							ill_refrele(
23229 							    conn_outgoing_ill);
23230 						}
23231 						return;
23232 					}
23233 					ipsec_out_process(q, first_mp,
23234 					    ire, ill_index);
23235 				}
23236 			} else {
23237 				/*
23238 				 * Initiate IPPF processing. For
23239 				 * fragmentable packets we finish
23240 				 * all QOS packet processing before
23241 				 * calling:
23242 				 * ip_wput_ire_fragmentit->ip_wput_frag
23243 				 */
23244 
23245 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23246 					ip_process(IPP_LOCAL_OUT, &mp,
23247 					    ill_index);
23248 					if (mp == NULL) {
23249 						out_ill = (ill_t *)stq->q_ptr;
23250 						BUMP_MIB(out_ill->ill_ip_mib,
23251 						    ipIfStatsOutDiscards);
23252 						if (next_mp != NULL) {
23253 							freemsg(next_mp);
23254 							ire_refrele(ire1);
23255 						}
23256 						ire_refrele(ire);
23257 						TRACE_2(TR_FAC_IP,
23258 						    TR_IP_WPUT_IRE_END,
23259 						    "ip_wput_ire: q %p (%S)",
23260 						    q, "discard MDATA");
23261 						if (conn_outgoing_ill != NULL) {
23262 							ill_refrele(
23263 							    conn_outgoing_ill);
23264 						}
23265 						return;
23266 					}
23267 				}
23268 				if (!next_mp) {
23269 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23270 					    "ip_wput_ire_end: q %p (%S)",
23271 					    q, "last fragmentation");
23272 					ip_wput_ire_fragmentit(mp, ire,
23273 					    zoneid, ipst);
23274 					ire_refrele(ire);
23275 					if (conn_outgoing_ill != NULL)
23276 						ill_refrele(conn_outgoing_ill);
23277 					return;
23278 				}
23279 				ip_wput_ire_fragmentit(mp, ire, zoneid, ipst);
23280 			}
23281 		}
23282 	} else {
23283 nullstq:
23284 		/* A NULL stq means the destination address is local. */
23285 		UPDATE_OB_PKT_COUNT(ire);
23286 		ire->ire_last_used_time = lbolt;
23287 		ASSERT(ire->ire_ipif != NULL);
23288 		if (!next_mp) {
23289 			/*
23290 			 * Is there an "in" and "out" for traffic local
23291 			 * to a host (loopback)?  The code in Solaris doesn't
23292 			 * explicitly draw a line in its code for in vs out,
23293 			 * so we've had to draw a line in the sand: ip_wput_ire
23294 			 * is considered to be the "output" side and
23295 			 * ip_wput_local to be the "input" side.
23296 			 */
23297 			out_ill = ire_to_ill(ire);
23298 
23299 			DTRACE_PROBE4(ip4__loopback__out__start,
23300 			    ill_t *, NULL, ill_t *, out_ill,
23301 			    ipha_t *, ipha, mblk_t *, first_mp);
23302 
23303 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23304 			    ipst->ips_ipv4firewall_loopback_out,
23305 			    NULL, out_ill, ipha, first_mp, mp, ipst);
23306 
23307 			DTRACE_PROBE1(ip4__loopback__out_end,
23308 			    mblk_t *, first_mp);
23309 
23310 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23311 			    "ip_wput_ire_end: q %p (%S)",
23312 			    q, "local address");
23313 
23314 			if (first_mp != NULL)
23315 				ip_wput_local(q, out_ill, ipha,
23316 				    first_mp, ire, 0, ire->ire_zoneid);
23317 			ire_refrele(ire);
23318 			if (conn_outgoing_ill != NULL)
23319 				ill_refrele(conn_outgoing_ill);
23320 			return;
23321 		}
23322 
23323 		out_ill = ire_to_ill(ire);
23324 
23325 		DTRACE_PROBE4(ip4__loopback__out__start,
23326 		    ill_t *, NULL, ill_t *, out_ill,
23327 		    ipha_t *, ipha, mblk_t *, first_mp);
23328 
23329 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23330 		    ipst->ips_ipv4firewall_loopback_out,
23331 		    NULL, out_ill, ipha, first_mp, mp, ipst);
23332 
23333 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23334 
23335 		if (first_mp != NULL)
23336 			ip_wput_local(q, out_ill, ipha,
23337 			    first_mp, ire, 0, ire->ire_zoneid);
23338 	}
23339 next:
23340 	/*
23341 	 * More copies going out to additional interfaces.
23342 	 * ire1 has already been held. We don't need the
23343 	 * "ire" anymore.
23344 	 */
23345 	ire_refrele(ire);
23346 	ire = ire1;
23347 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23348 	mp = next_mp;
23349 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23350 	ill = ire_to_ill(ire);
23351 	first_mp = mp;
23352 	if (ipsec_len != 0) {
23353 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23354 		mp = mp->b_cont;
23355 	}
23356 	dst = ire->ire_addr;
23357 	ipha = (ipha_t *)mp->b_rptr;
23358 	/*
23359 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23360 	 * Restore ipha_ident "no checksum" flag.
23361 	 */
23362 	src = orig_src;
23363 	ipha->ipha_ident = ip_hdr_included;
23364 	goto another;
23365 
23366 #undef	rptr
23367 #undef	Q_TO_INDEX
23368 }
23369 
23370 /*
23371  * Routine to allocate a message that is used to notify the ULP about MDT.
23372  * The caller may provide a pointer to the link-layer MDT capabilities,
23373  * or NULL if MDT is to be disabled on the stream.
23374  */
23375 mblk_t *
23376 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23377 {
23378 	mblk_t *mp;
23379 	ip_mdt_info_t *mdti;
23380 	ill_mdt_capab_t *idst;
23381 
23382 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23383 		DB_TYPE(mp) = M_CTL;
23384 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23385 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23386 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23387 		idst = &(mdti->mdt_capab);
23388 
23389 		/*
23390 		 * If the caller provides us with the capability, copy
23391 		 * it over into our notification message; otherwise
23392 		 * we zero out the capability portion.
23393 		 */
23394 		if (isrc != NULL)
23395 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23396 		else
23397 			bzero((caddr_t)idst, sizeof (*idst));
23398 	}
23399 	return (mp);
23400 }
23401 
23402 /*
23403  * Routine which determines whether MDT can be enabled on the destination
23404  * IRE and IPC combination, and if so, allocates and returns the MDT
23405  * notification mblk that may be used by ULP.  We also check if we need to
23406  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23407  * MDT usage in the past have been lifted.  This gets called during IP
23408  * and ULP binding.
23409  */
23410 mblk_t *
23411 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23412     ill_mdt_capab_t *mdt_cap)
23413 {
23414 	mblk_t *mp;
23415 	boolean_t rc = B_FALSE;
23416 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23417 
23418 	ASSERT(dst_ire != NULL);
23419 	ASSERT(connp != NULL);
23420 	ASSERT(mdt_cap != NULL);
23421 
23422 	/*
23423 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23424 	 * Multidata, which is handled in tcp_multisend().  This
23425 	 * is the reason why we do all these checks here, to ensure
23426 	 * that we don't enable Multidata for the cases which we
23427 	 * can't handle at the moment.
23428 	 */
23429 	do {
23430 		/* Only do TCP at the moment */
23431 		if (connp->conn_ulp != IPPROTO_TCP)
23432 			break;
23433 
23434 		/*
23435 		 * IPsec outbound policy present?  Note that we get here
23436 		 * after calling ipsec_conn_cache_policy() where the global
23437 		 * policy checking is performed.  conn_latch will be
23438 		 * non-NULL as long as there's a policy defined,
23439 		 * i.e. conn_out_enforce_policy may be NULL in such case
23440 		 * when the connection is non-secure, and hence we check
23441 		 * further if the latch refers to an outbound policy.
23442 		 */
23443 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23444 			break;
23445 
23446 		/* CGTP (multiroute) is enabled? */
23447 		if (dst_ire->ire_flags & RTF_MULTIRT)
23448 			break;
23449 
23450 		/* Outbound IPQoS enabled? */
23451 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23452 			/*
23453 			 * In this case, we disable MDT for this and all
23454 			 * future connections going over the interface.
23455 			 */
23456 			mdt_cap->ill_mdt_on = 0;
23457 			break;
23458 		}
23459 
23460 		/* socket option(s) present? */
23461 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23462 			break;
23463 
23464 		rc = B_TRUE;
23465 	/* CONSTCOND */
23466 	} while (0);
23467 
23468 	/* Remember the result */
23469 	connp->conn_mdt_ok = rc;
23470 
23471 	if (!rc)
23472 		return (NULL);
23473 	else if (!mdt_cap->ill_mdt_on) {
23474 		/*
23475 		 * If MDT has been previously turned off in the past, and we
23476 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23477 		 * then enable it for this interface.
23478 		 */
23479 		mdt_cap->ill_mdt_on = 1;
23480 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23481 		    "interface %s\n", ill_name));
23482 	}
23483 
23484 	/* Allocate the MDT info mblk */
23485 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23486 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23487 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23488 		return (NULL);
23489 	}
23490 	return (mp);
23491 }
23492 
23493 /*
23494  * Routine to allocate a message that is used to notify the ULP about LSO.
23495  * The caller may provide a pointer to the link-layer LSO capabilities,
23496  * or NULL if LSO is to be disabled on the stream.
23497  */
23498 mblk_t *
23499 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23500 {
23501 	mblk_t *mp;
23502 	ip_lso_info_t *lsoi;
23503 	ill_lso_capab_t *idst;
23504 
23505 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23506 		DB_TYPE(mp) = M_CTL;
23507 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23508 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23509 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23510 		idst = &(lsoi->lso_capab);
23511 
23512 		/*
23513 		 * If the caller provides us with the capability, copy
23514 		 * it over into our notification message; otherwise
23515 		 * we zero out the capability portion.
23516 		 */
23517 		if (isrc != NULL)
23518 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23519 		else
23520 			bzero((caddr_t)idst, sizeof (*idst));
23521 	}
23522 	return (mp);
23523 }
23524 
23525 /*
23526  * Routine which determines whether LSO can be enabled on the destination
23527  * IRE and IPC combination, and if so, allocates and returns the LSO
23528  * notification mblk that may be used by ULP.  We also check if we need to
23529  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23530  * LSO usage in the past have been lifted.  This gets called during IP
23531  * and ULP binding.
23532  */
23533 mblk_t *
23534 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23535     ill_lso_capab_t *lso_cap)
23536 {
23537 	mblk_t *mp;
23538 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23539 
23540 	ASSERT(dst_ire != NULL);
23541 	ASSERT(connp != NULL);
23542 	ASSERT(lso_cap != NULL);
23543 
23544 	connp->conn_lso_ok = B_TRUE;
23545 
23546 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23547 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23548 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23549 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23550 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23551 		connp->conn_lso_ok = B_FALSE;
23552 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23553 			/*
23554 			 * Disable LSO for this and all future connections going
23555 			 * over the interface.
23556 			 */
23557 			lso_cap->ill_lso_on = 0;
23558 		}
23559 	}
23560 
23561 	if (!connp->conn_lso_ok)
23562 		return (NULL);
23563 	else if (!lso_cap->ill_lso_on) {
23564 		/*
23565 		 * If LSO has been previously turned off in the past, and we
23566 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23567 		 * then enable it for this interface.
23568 		 */
23569 		lso_cap->ill_lso_on = 1;
23570 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23571 		    ill_name));
23572 	}
23573 
23574 	/* Allocate the LSO info mblk */
23575 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23576 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23577 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23578 
23579 	return (mp);
23580 }
23581 
23582 /*
23583  * Create destination address attribute, and fill it with the physical
23584  * destination address and SAP taken from the template DL_UNITDATA_REQ
23585  * message block.
23586  */
23587 boolean_t
23588 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23589 {
23590 	dl_unitdata_req_t *dlurp;
23591 	pattr_t *pa;
23592 	pattrinfo_t pa_info;
23593 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23594 	uint_t das_len, das_off;
23595 
23596 	ASSERT(dlmp != NULL);
23597 
23598 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23599 	das_len = dlurp->dl_dest_addr_length;
23600 	das_off = dlurp->dl_dest_addr_offset;
23601 
23602 	pa_info.type = PATTR_DSTADDRSAP;
23603 	pa_info.len = sizeof (**das) + das_len - 1;
23604 
23605 	/* create and associate the attribute */
23606 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23607 	if (pa != NULL) {
23608 		ASSERT(*das != NULL);
23609 		(*das)->addr_is_group = 0;
23610 		(*das)->addr_len = (uint8_t)das_len;
23611 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23612 	}
23613 
23614 	return (pa != NULL);
23615 }
23616 
23617 /*
23618  * Create hardware checksum attribute and fill it with the values passed.
23619  */
23620 boolean_t
23621 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23622     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23623 {
23624 	pattr_t *pa;
23625 	pattrinfo_t pa_info;
23626 
23627 	ASSERT(mmd != NULL);
23628 
23629 	pa_info.type = PATTR_HCKSUM;
23630 	pa_info.len = sizeof (pattr_hcksum_t);
23631 
23632 	/* create and associate the attribute */
23633 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23634 	if (pa != NULL) {
23635 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23636 
23637 		hck->hcksum_start_offset = start_offset;
23638 		hck->hcksum_stuff_offset = stuff_offset;
23639 		hck->hcksum_end_offset = end_offset;
23640 		hck->hcksum_flags = flags;
23641 	}
23642 	return (pa != NULL);
23643 }
23644 
23645 /*
23646  * Create zerocopy attribute and fill it with the specified flags
23647  */
23648 boolean_t
23649 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23650 {
23651 	pattr_t *pa;
23652 	pattrinfo_t pa_info;
23653 
23654 	ASSERT(mmd != NULL);
23655 	pa_info.type = PATTR_ZCOPY;
23656 	pa_info.len = sizeof (pattr_zcopy_t);
23657 
23658 	/* create and associate the attribute */
23659 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23660 	if (pa != NULL) {
23661 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23662 
23663 		zcopy->zcopy_flags = flags;
23664 	}
23665 	return (pa != NULL);
23666 }
23667 
23668 /*
23669  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23670  * block chain. We could rewrite to handle arbitrary message block chains but
23671  * that would make the code complicated and slow. Right now there three
23672  * restrictions:
23673  *
23674  *   1. The first message block must contain the complete IP header and
23675  *	at least 1 byte of payload data.
23676  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23677  *	so that we can use a single Multidata message.
23678  *   3. No frag must be distributed over two or more message blocks so
23679  *	that we don't need more than two packet descriptors per frag.
23680  *
23681  * The above restrictions allow us to support userland applications (which
23682  * will send down a single message block) and NFS over UDP (which will
23683  * send down a chain of at most three message blocks).
23684  *
23685  * We also don't use MDT for payloads with less than or equal to
23686  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23687  */
23688 boolean_t
23689 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23690 {
23691 	int	blocks;
23692 	ssize_t	total, missing, size;
23693 
23694 	ASSERT(mp != NULL);
23695 	ASSERT(hdr_len > 0);
23696 
23697 	size = MBLKL(mp) - hdr_len;
23698 	if (size <= 0)
23699 		return (B_FALSE);
23700 
23701 	/* The first mblk contains the header and some payload. */
23702 	blocks = 1;
23703 	total = size;
23704 	size %= len;
23705 	missing = (size == 0) ? 0 : (len - size);
23706 	mp = mp->b_cont;
23707 
23708 	while (mp != NULL) {
23709 		/*
23710 		 * Give up if we encounter a zero length message block.
23711 		 * In practice, this should rarely happen and therefore
23712 		 * not worth the trouble of freeing and re-linking the
23713 		 * mblk from the chain to handle such case.
23714 		 */
23715 		if ((size = MBLKL(mp)) == 0)
23716 			return (B_FALSE);
23717 
23718 		/* Too many payload buffers for a single Multidata message? */
23719 		if (++blocks > MULTIDATA_MAX_PBUFS)
23720 			return (B_FALSE);
23721 
23722 		total += size;
23723 		/* Is a frag distributed over two or more message blocks? */
23724 		if (missing > size)
23725 			return (B_FALSE);
23726 		size -= missing;
23727 
23728 		size %= len;
23729 		missing = (size == 0) ? 0 : (len - size);
23730 
23731 		mp = mp->b_cont;
23732 	}
23733 
23734 	return (total > ip_wput_frag_mdt_min);
23735 }
23736 
23737 /*
23738  * Outbound IPv4 fragmentation routine using MDT.
23739  */
23740 static void
23741 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23742     uint32_t frag_flag, int offset)
23743 {
23744 	ipha_t		*ipha_orig;
23745 	int		i1, ip_data_end;
23746 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23747 	mblk_t		*hdr_mp, *md_mp = NULL;
23748 	unsigned char	*hdr_ptr, *pld_ptr;
23749 	multidata_t	*mmd;
23750 	ip_pdescinfo_t	pdi;
23751 	ill_t		*ill;
23752 	ip_stack_t	*ipst = ire->ire_ipst;
23753 
23754 	ASSERT(DB_TYPE(mp) == M_DATA);
23755 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23756 
23757 	ill = ire_to_ill(ire);
23758 	ASSERT(ill != NULL);
23759 
23760 	ipha_orig = (ipha_t *)mp->b_rptr;
23761 	mp->b_rptr += sizeof (ipha_t);
23762 
23763 	/* Calculate how many packets we will send out */
23764 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
23765 	pkts = (i1 + len - 1) / len;
23766 	ASSERT(pkts > 1);
23767 
23768 	/* Allocate a message block which will hold all the IP Headers. */
23769 	wroff = ipst->ips_ip_wroff_extra;
23770 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
23771 
23772 	i1 = pkts * hdr_chunk_len;
23773 	/*
23774 	 * Create the header buffer, Multidata and destination address
23775 	 * and SAP attribute that should be associated with it.
23776 	 */
23777 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
23778 	    ((hdr_mp->b_wptr += i1),
23779 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
23780 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
23781 		freemsg(mp);
23782 		if (md_mp == NULL) {
23783 			freemsg(hdr_mp);
23784 		} else {
23785 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
23786 			freemsg(md_mp);
23787 		}
23788 		IP_STAT(ipst, ip_frag_mdt_allocfail);
23789 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
23790 		return;
23791 	}
23792 	IP_STAT(ipst, ip_frag_mdt_allocd);
23793 
23794 	/*
23795 	 * Add a payload buffer to the Multidata; this operation must not
23796 	 * fail, or otherwise our logic in this routine is broken.  There
23797 	 * is no memory allocation done by the routine, so any returned
23798 	 * failure simply tells us that we've done something wrong.
23799 	 *
23800 	 * A failure tells us that either we're adding the same payload
23801 	 * buffer more than once, or we're trying to add more buffers than
23802 	 * allowed.  None of the above cases should happen, and we panic
23803 	 * because either there's horrible heap corruption, and/or
23804 	 * programming mistake.
23805 	 */
23806 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23807 		goto pbuf_panic;
23808 
23809 	hdr_ptr = hdr_mp->b_rptr;
23810 	pld_ptr = mp->b_rptr;
23811 
23812 	/* Establish the ending byte offset, based on the starting offset. */
23813 	offset <<= 3;
23814 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
23815 	    IP_SIMPLE_HDR_LENGTH;
23816 
23817 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
23818 
23819 	while (pld_ptr < mp->b_wptr) {
23820 		ipha_t		*ipha;
23821 		uint16_t	offset_and_flags;
23822 		uint16_t	ip_len;
23823 		int		error;
23824 
23825 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
23826 		ipha = (ipha_t *)(hdr_ptr + wroff);
23827 		ASSERT(OK_32PTR(ipha));
23828 		*ipha = *ipha_orig;
23829 
23830 		if (ip_data_end - offset > len) {
23831 			offset_and_flags = IPH_MF;
23832 		} else {
23833 			/*
23834 			 * Last frag. Set len to the length of this last piece.
23835 			 */
23836 			len = ip_data_end - offset;
23837 			/* A frag of a frag might have IPH_MF non-zero */
23838 			offset_and_flags =
23839 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23840 			    IPH_MF;
23841 		}
23842 		offset_and_flags |= (uint16_t)(offset >> 3);
23843 		offset_and_flags |= (uint16_t)frag_flag;
23844 		/* Store the offset and flags in the IP header. */
23845 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23846 
23847 		/* Store the length in the IP header. */
23848 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
23849 		ipha->ipha_length = htons(ip_len);
23850 
23851 		/*
23852 		 * Set the IP header checksum.  Note that mp is just
23853 		 * the header, so this is easy to pass to ip_csum.
23854 		 */
23855 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23856 
23857 		/*
23858 		 * Record offset and size of header and data of the next packet
23859 		 * in the multidata message.
23860 		 */
23861 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
23862 		PDESC_PLD_INIT(&pdi);
23863 		i1 = MIN(mp->b_wptr - pld_ptr, len);
23864 		ASSERT(i1 > 0);
23865 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
23866 		if (i1 == len) {
23867 			pld_ptr += len;
23868 		} else {
23869 			i1 = len - i1;
23870 			mp = mp->b_cont;
23871 			ASSERT(mp != NULL);
23872 			ASSERT(MBLKL(mp) >= i1);
23873 			/*
23874 			 * Attach the next payload message block to the
23875 			 * multidata message.
23876 			 */
23877 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23878 				goto pbuf_panic;
23879 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
23880 			pld_ptr = mp->b_rptr + i1;
23881 		}
23882 
23883 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
23884 		    KM_NOSLEEP)) == NULL) {
23885 			/*
23886 			 * Any failure other than ENOMEM indicates that we
23887 			 * have passed in invalid pdesc info or parameters
23888 			 * to mmd_addpdesc, which must not happen.
23889 			 *
23890 			 * EINVAL is a result of failure on boundary checks
23891 			 * against the pdesc info contents.  It should not
23892 			 * happen, and we panic because either there's
23893 			 * horrible heap corruption, and/or programming
23894 			 * mistake.
23895 			 */
23896 			if (error != ENOMEM) {
23897 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
23898 				    "pdesc logic error detected for "
23899 				    "mmd %p pinfo %p (%d)\n",
23900 				    (void *)mmd, (void *)&pdi, error);
23901 				/* NOTREACHED */
23902 			}
23903 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
23904 			/* Free unattached payload message blocks as well */
23905 			md_mp->b_cont = mp->b_cont;
23906 			goto free_mmd;
23907 		}
23908 
23909 		/* Advance fragment offset. */
23910 		offset += len;
23911 
23912 		/* Advance to location for next header in the buffer. */
23913 		hdr_ptr += hdr_chunk_len;
23914 
23915 		/* Did we reach the next payload message block? */
23916 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
23917 			mp = mp->b_cont;
23918 			/*
23919 			 * Attach the next message block with payload
23920 			 * data to the multidata message.
23921 			 */
23922 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23923 				goto pbuf_panic;
23924 			pld_ptr = mp->b_rptr;
23925 		}
23926 	}
23927 
23928 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
23929 	ASSERT(mp->b_wptr == pld_ptr);
23930 
23931 	/* Update IP statistics */
23932 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
23933 
23934 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
23935 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
23936 
23937 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
23938 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
23939 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
23940 
23941 	if (pkt_type == OB_PKT) {
23942 		ire->ire_ob_pkt_count += pkts;
23943 		if (ire->ire_ipif != NULL)
23944 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
23945 	} else {
23946 		/* The type is IB_PKT in the forwarding path. */
23947 		ire->ire_ib_pkt_count += pkts;
23948 		ASSERT(!IRE_IS_LOCAL(ire));
23949 		if (ire->ire_type & IRE_BROADCAST) {
23950 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
23951 		} else {
23952 			UPDATE_MIB(ill->ill_ip_mib,
23953 			    ipIfStatsHCOutForwDatagrams, pkts);
23954 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
23955 		}
23956 	}
23957 	ire->ire_last_used_time = lbolt;
23958 	/* Send it down */
23959 	putnext(ire->ire_stq, md_mp);
23960 	return;
23961 
23962 pbuf_panic:
23963 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
23964 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
23965 	    pbuf_idx);
23966 	/* NOTREACHED */
23967 }
23968 
23969 /*
23970  * Outbound IP fragmentation routine.
23971  *
23972  * NOTE : This routine does not ire_refrele the ire that is passed in
23973  * as the argument.
23974  */
23975 static void
23976 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
23977     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst)
23978 {
23979 	int		i1;
23980 	mblk_t		*ll_hdr_mp;
23981 	int 		ll_hdr_len;
23982 	int		hdr_len;
23983 	mblk_t		*hdr_mp;
23984 	ipha_t		*ipha;
23985 	int		ip_data_end;
23986 	int		len;
23987 	mblk_t		*mp = mp_orig, *mp1;
23988 	int		offset;
23989 	queue_t		*q;
23990 	uint32_t	v_hlen_tos_len;
23991 	mblk_t		*first_mp;
23992 	boolean_t	mctl_present;
23993 	ill_t		*ill;
23994 	ill_t		*out_ill;
23995 	mblk_t		*xmit_mp;
23996 	mblk_t		*carve_mp;
23997 	ire_t		*ire1 = NULL;
23998 	ire_t		*save_ire = NULL;
23999 	mblk_t  	*next_mp = NULL;
24000 	boolean_t	last_frag = B_FALSE;
24001 	boolean_t	multirt_send = B_FALSE;
24002 	ire_t		*first_ire = NULL;
24003 	irb_t		*irb = NULL;
24004 	mib2_ipIfStatsEntry_t *mibptr = NULL;
24005 
24006 	ill = ire_to_ill(ire);
24007 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
24008 
24009 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
24010 
24011 	if (max_frag == 0) {
24012 		ip1dbg(("ip_wput_frag: ire frag size is 0"
24013 		    " -  dropping packet\n"));
24014 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24015 		freemsg(mp);
24016 		return;
24017 	}
24018 
24019 	/*
24020 	 * IPsec does not allow hw accelerated packets to be fragmented
24021 	 * This check is made in ip_wput_ipsec_out prior to coming here
24022 	 * via ip_wput_ire_fragmentit.
24023 	 *
24024 	 * If at this point we have an ire whose ARP request has not
24025 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24026 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24027 	 * This packet and all fragmentable packets for this ire will
24028 	 * continue to get dropped while ire_nce->nce_state remains in
24029 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24030 	 * ND_REACHABLE, all subsquent large packets for this ire will
24031 	 * get fragemented and sent out by this function.
24032 	 */
24033 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24034 		/* If nce_state is ND_INITIAL, trigger ARP query */
24035 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
24036 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24037 		    " -  dropping packet\n"));
24038 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24039 		freemsg(mp);
24040 		return;
24041 	}
24042 
24043 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24044 	    "ip_wput_frag_start:");
24045 
24046 	if (mp->b_datap->db_type == M_CTL) {
24047 		first_mp = mp;
24048 		mp_orig = mp = mp->b_cont;
24049 		mctl_present = B_TRUE;
24050 	} else {
24051 		first_mp = mp;
24052 		mctl_present = B_FALSE;
24053 	}
24054 
24055 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24056 	ipha = (ipha_t *)mp->b_rptr;
24057 
24058 	/*
24059 	 * If the Don't Fragment flag is on, generate an ICMP destination
24060 	 * unreachable, fragmentation needed.
24061 	 */
24062 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24063 	if (offset & IPH_DF) {
24064 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24065 		if (is_system_labeled()) {
24066 			max_frag = tsol_pmtu_adjust(mp, ire->ire_max_frag,
24067 			    ire->ire_max_frag - max_frag, AF_INET);
24068 		}
24069 		/*
24070 		 * Need to compute hdr checksum if called from ip_wput_ire.
24071 		 * Note that ip_rput_forward verifies the checksum before
24072 		 * calling this routine so in that case this is a noop.
24073 		 */
24074 		ipha->ipha_hdr_checksum = 0;
24075 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24076 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24077 		    ipst);
24078 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24079 		    "ip_wput_frag_end:(%S)",
24080 		    "don't fragment");
24081 		return;
24082 	}
24083 	/*
24084 	 * Labeled systems adjust max_frag if they add a label
24085 	 * to send the correct path mtu.  We need the real mtu since we
24086 	 * are fragmenting the packet after label adjustment.
24087 	 */
24088 	if (is_system_labeled())
24089 		max_frag = ire->ire_max_frag;
24090 	if (mctl_present)
24091 		freeb(first_mp);
24092 	/*
24093 	 * Establish the starting offset.  May not be zero if we are fragging
24094 	 * a fragment that is being forwarded.
24095 	 */
24096 	offset = offset & IPH_OFFSET;
24097 
24098 	/* TODO why is this test needed? */
24099 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24100 	if (((max_frag - LENGTH) & ~7) < 8) {
24101 		/* TODO: notify ulp somehow */
24102 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24103 		freemsg(mp);
24104 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24105 		    "ip_wput_frag_end:(%S)",
24106 		    "len < 8");
24107 		return;
24108 	}
24109 
24110 	hdr_len = (V_HLEN & 0xF) << 2;
24111 
24112 	ipha->ipha_hdr_checksum = 0;
24113 
24114 	/*
24115 	 * Establish the number of bytes maximum per frag, after putting
24116 	 * in the header.
24117 	 */
24118 	len = (max_frag - hdr_len) & ~7;
24119 
24120 	/* Check if we can use MDT to send out the frags. */
24121 	ASSERT(!IRE_IS_LOCAL(ire));
24122 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24123 	    ipst->ips_ip_multidata_outbound &&
24124 	    !(ire->ire_flags & RTF_MULTIRT) &&
24125 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24126 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24127 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24128 		ASSERT(ill->ill_mdt_capab != NULL);
24129 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24130 			/*
24131 			 * If MDT has been previously turned off in the past,
24132 			 * and we currently can do MDT (due to IPQoS policy
24133 			 * removal, etc.) then enable it for this interface.
24134 			 */
24135 			ill->ill_mdt_capab->ill_mdt_on = 1;
24136 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24137 			    ill->ill_name));
24138 		}
24139 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24140 		    offset);
24141 		return;
24142 	}
24143 
24144 	/* Get a copy of the header for the trailing frags */
24145 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst);
24146 	if (!hdr_mp) {
24147 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24148 		freemsg(mp);
24149 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24150 		    "ip_wput_frag_end:(%S)",
24151 		    "couldn't copy hdr");
24152 		return;
24153 	}
24154 	if (DB_CRED(mp) != NULL)
24155 		mblk_setcred(hdr_mp, DB_CRED(mp));
24156 
24157 	/* Store the starting offset, with the MoreFrags flag. */
24158 	i1 = offset | IPH_MF | frag_flag;
24159 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24160 
24161 	/* Establish the ending byte offset, based on the starting offset. */
24162 	offset <<= 3;
24163 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24164 
24165 	/* Store the length of the first fragment in the IP header. */
24166 	i1 = len + hdr_len;
24167 	ASSERT(i1 <= IP_MAXPACKET);
24168 	ipha->ipha_length = htons((uint16_t)i1);
24169 
24170 	/*
24171 	 * Compute the IP header checksum for the first frag.  We have to
24172 	 * watch out that we stop at the end of the header.
24173 	 */
24174 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24175 
24176 	/*
24177 	 * Now carve off the first frag.  Note that this will include the
24178 	 * original IP header.
24179 	 */
24180 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24181 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24182 		freeb(hdr_mp);
24183 		freemsg(mp_orig);
24184 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24185 		    "ip_wput_frag_end:(%S)",
24186 		    "couldn't carve first");
24187 		return;
24188 	}
24189 
24190 	/*
24191 	 * Multirouting case. Each fragment is replicated
24192 	 * via all non-condemned RTF_MULTIRT routes
24193 	 * currently resolved.
24194 	 * We ensure that first_ire is the first RTF_MULTIRT
24195 	 * ire in the bucket.
24196 	 */
24197 	if (ire->ire_flags & RTF_MULTIRT) {
24198 		irb = ire->ire_bucket;
24199 		ASSERT(irb != NULL);
24200 
24201 		multirt_send = B_TRUE;
24202 
24203 		/* Make sure we do not omit any multiroute ire. */
24204 		IRB_REFHOLD(irb);
24205 		for (first_ire = irb->irb_ire;
24206 		    first_ire != NULL;
24207 		    first_ire = first_ire->ire_next) {
24208 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24209 			    (first_ire->ire_addr == ire->ire_addr) &&
24210 			    !(first_ire->ire_marks &
24211 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
24212 				break;
24213 			}
24214 		}
24215 
24216 		if (first_ire != NULL) {
24217 			if (first_ire != ire) {
24218 				IRE_REFHOLD(first_ire);
24219 				/*
24220 				 * Do not release the ire passed in
24221 				 * as the argument.
24222 				 */
24223 				ire = first_ire;
24224 			} else {
24225 				first_ire = NULL;
24226 			}
24227 		}
24228 		IRB_REFRELE(irb);
24229 
24230 		/*
24231 		 * Save the first ire; we will need to restore it
24232 		 * for the trailing frags.
24233 		 * We REFHOLD save_ire, as each iterated ire will be
24234 		 * REFRELEd.
24235 		 */
24236 		save_ire = ire;
24237 		IRE_REFHOLD(save_ire);
24238 	}
24239 
24240 	/*
24241 	 * First fragment emission loop.
24242 	 * In most cases, the emission loop below is entered only
24243 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24244 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24245 	 * bucket, and send the fragment through all crossed
24246 	 * RTF_MULTIRT routes.
24247 	 */
24248 	do {
24249 		if (ire->ire_flags & RTF_MULTIRT) {
24250 			/*
24251 			 * We are in a multiple send case, need to get
24252 			 * the next ire and make a copy of the packet.
24253 			 * ire1 holds here the next ire to process in the
24254 			 * bucket. If multirouting is expected,
24255 			 * any non-RTF_MULTIRT ire that has the
24256 			 * right destination address is ignored.
24257 			 *
24258 			 * We have to take into account the MTU of
24259 			 * each walked ire. max_frag is set by the
24260 			 * the caller and generally refers to
24261 			 * the primary ire entry. Here we ensure that
24262 			 * no route with a lower MTU will be used, as
24263 			 * fragments are carved once for all ires,
24264 			 * then replicated.
24265 			 */
24266 			ASSERT(irb != NULL);
24267 			IRB_REFHOLD(irb);
24268 			for (ire1 = ire->ire_next;
24269 			    ire1 != NULL;
24270 			    ire1 = ire1->ire_next) {
24271 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24272 					continue;
24273 				if (ire1->ire_addr != ire->ire_addr)
24274 					continue;
24275 				if (ire1->ire_marks &
24276 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
24277 					continue;
24278 				/*
24279 				 * Ensure we do not exceed the MTU
24280 				 * of the next route.
24281 				 */
24282 				if (ire1->ire_max_frag < max_frag) {
24283 					ip_multirt_bad_mtu(ire1, max_frag);
24284 					continue;
24285 				}
24286 
24287 				/* Got one. */
24288 				IRE_REFHOLD(ire1);
24289 				break;
24290 			}
24291 			IRB_REFRELE(irb);
24292 
24293 			if (ire1 != NULL) {
24294 				next_mp = copyb(mp);
24295 				if ((next_mp == NULL) ||
24296 				    ((mp->b_cont != NULL) &&
24297 				    ((next_mp->b_cont =
24298 				    dupmsg(mp->b_cont)) == NULL))) {
24299 					freemsg(next_mp);
24300 					next_mp = NULL;
24301 					ire_refrele(ire1);
24302 					ire1 = NULL;
24303 				}
24304 			}
24305 
24306 			/* Last multiroute ire; don't loop anymore. */
24307 			if (ire1 == NULL) {
24308 				multirt_send = B_FALSE;
24309 			}
24310 		}
24311 
24312 		ll_hdr_len = 0;
24313 		LOCK_IRE_FP_MP(ire);
24314 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24315 		if (ll_hdr_mp != NULL) {
24316 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24317 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24318 		} else {
24319 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24320 		}
24321 
24322 		/* If there is a transmit header, get a copy for this frag. */
24323 		/*
24324 		 * TODO: should check db_ref before calling ip_carve_mp since
24325 		 * it might give us a dup.
24326 		 */
24327 		if (!ll_hdr_mp) {
24328 			/* No xmit header. */
24329 			xmit_mp = mp;
24330 
24331 		/* We have a link-layer header that can fit in our mblk. */
24332 		} else if (mp->b_datap->db_ref == 1 &&
24333 		    ll_hdr_len != 0 &&
24334 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24335 			/* M_DATA fastpath */
24336 			mp->b_rptr -= ll_hdr_len;
24337 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24338 			xmit_mp = mp;
24339 
24340 		/* Corner case if copyb has failed */
24341 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24342 			UNLOCK_IRE_FP_MP(ire);
24343 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24344 			freeb(hdr_mp);
24345 			freemsg(mp);
24346 			freemsg(mp_orig);
24347 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24348 			    "ip_wput_frag_end:(%S)",
24349 			    "discard");
24350 
24351 			if (multirt_send) {
24352 				ASSERT(ire1);
24353 				ASSERT(next_mp);
24354 
24355 				freemsg(next_mp);
24356 				ire_refrele(ire1);
24357 			}
24358 			if (save_ire != NULL)
24359 				IRE_REFRELE(save_ire);
24360 
24361 			if (first_ire != NULL)
24362 				ire_refrele(first_ire);
24363 			return;
24364 
24365 		/*
24366 		 * Case of res_mp OR the fastpath mp can't fit
24367 		 * in the mblk
24368 		 */
24369 		} else {
24370 			xmit_mp->b_cont = mp;
24371 			if (DB_CRED(mp) != NULL)
24372 				mblk_setcred(xmit_mp, DB_CRED(mp));
24373 			/*
24374 			 * Get priority marking, if any.
24375 			 * We propagate the CoS marking from the
24376 			 * original packet that went to QoS processing
24377 			 * in ip_wput_ire to the newly carved mp.
24378 			 */
24379 			if (DB_TYPE(xmit_mp) == M_DATA)
24380 				xmit_mp->b_band = mp->b_band;
24381 		}
24382 		UNLOCK_IRE_FP_MP(ire);
24383 
24384 		q = ire->ire_stq;
24385 		out_ill = (ill_t *)q->q_ptr;
24386 
24387 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24388 
24389 		DTRACE_PROBE4(ip4__physical__out__start,
24390 		    ill_t *, NULL, ill_t *, out_ill,
24391 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24392 
24393 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24394 		    ipst->ips_ipv4firewall_physical_out,
24395 		    NULL, out_ill, ipha, xmit_mp, mp, ipst);
24396 
24397 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24398 
24399 		if (xmit_mp != NULL) {
24400 			putnext(q, xmit_mp);
24401 
24402 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24403 			UPDATE_MIB(out_ill->ill_ip_mib,
24404 			    ipIfStatsHCOutOctets, i1);
24405 
24406 			if (pkt_type != OB_PKT) {
24407 				/*
24408 				 * Update the packet count and MIB stats
24409 				 * of trailing RTF_MULTIRT ires.
24410 				 */
24411 				UPDATE_OB_PKT_COUNT(ire);
24412 				BUMP_MIB(out_ill->ill_ip_mib,
24413 				    ipIfStatsOutFragReqds);
24414 			}
24415 		}
24416 
24417 		if (multirt_send) {
24418 			/*
24419 			 * We are in a multiple send case; look for
24420 			 * the next ire and re-enter the loop.
24421 			 */
24422 			ASSERT(ire1);
24423 			ASSERT(next_mp);
24424 			/* REFRELE the current ire before looping */
24425 			ire_refrele(ire);
24426 			ire = ire1;
24427 			ire1 = NULL;
24428 			mp = next_mp;
24429 			next_mp = NULL;
24430 		}
24431 	} while (multirt_send);
24432 
24433 	ASSERT(ire1 == NULL);
24434 
24435 	/* Restore the original ire; we need it for the trailing frags */
24436 	if (save_ire != NULL) {
24437 		/* REFRELE the last iterated ire */
24438 		ire_refrele(ire);
24439 		/* save_ire has been REFHOLDed */
24440 		ire = save_ire;
24441 		save_ire = NULL;
24442 		q = ire->ire_stq;
24443 	}
24444 
24445 	if (pkt_type == OB_PKT) {
24446 		UPDATE_OB_PKT_COUNT(ire);
24447 	} else {
24448 		out_ill = (ill_t *)q->q_ptr;
24449 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24450 		UPDATE_IB_PKT_COUNT(ire);
24451 	}
24452 
24453 	/* Advance the offset to the second frag starting point. */
24454 	offset += len;
24455 	/*
24456 	 * Update hdr_len from the copied header - there might be less options
24457 	 * in the later fragments.
24458 	 */
24459 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24460 	/* Loop until done. */
24461 	for (;;) {
24462 		uint16_t	offset_and_flags;
24463 		uint16_t	ip_len;
24464 
24465 		if (ip_data_end - offset > len) {
24466 			/*
24467 			 * Carve off the appropriate amount from the original
24468 			 * datagram.
24469 			 */
24470 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24471 				mp = NULL;
24472 				break;
24473 			}
24474 			/*
24475 			 * More frags after this one.  Get another copy
24476 			 * of the header.
24477 			 */
24478 			if (carve_mp->b_datap->db_ref == 1 &&
24479 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24480 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24481 				/* Inline IP header */
24482 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24483 				    hdr_mp->b_rptr;
24484 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24485 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24486 				mp = carve_mp;
24487 			} else {
24488 				if (!(mp = copyb(hdr_mp))) {
24489 					freemsg(carve_mp);
24490 					break;
24491 				}
24492 				/* Get priority marking, if any. */
24493 				mp->b_band = carve_mp->b_band;
24494 				mp->b_cont = carve_mp;
24495 			}
24496 			ipha = (ipha_t *)mp->b_rptr;
24497 			offset_and_flags = IPH_MF;
24498 		} else {
24499 			/*
24500 			 * Last frag.  Consume the header. Set len to
24501 			 * the length of this last piece.
24502 			 */
24503 			len = ip_data_end - offset;
24504 
24505 			/*
24506 			 * Carve off the appropriate amount from the original
24507 			 * datagram.
24508 			 */
24509 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24510 				mp = NULL;
24511 				break;
24512 			}
24513 			if (carve_mp->b_datap->db_ref == 1 &&
24514 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24515 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24516 				/* Inline IP header */
24517 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24518 				    hdr_mp->b_rptr;
24519 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24520 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24521 				mp = carve_mp;
24522 				freeb(hdr_mp);
24523 				hdr_mp = mp;
24524 			} else {
24525 				mp = hdr_mp;
24526 				/* Get priority marking, if any. */
24527 				mp->b_band = carve_mp->b_band;
24528 				mp->b_cont = carve_mp;
24529 			}
24530 			ipha = (ipha_t *)mp->b_rptr;
24531 			/* A frag of a frag might have IPH_MF non-zero */
24532 			offset_and_flags =
24533 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24534 			    IPH_MF;
24535 		}
24536 		offset_and_flags |= (uint16_t)(offset >> 3);
24537 		offset_and_flags |= (uint16_t)frag_flag;
24538 		/* Store the offset and flags in the IP header. */
24539 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24540 
24541 		/* Store the length in the IP header. */
24542 		ip_len = (uint16_t)(len + hdr_len);
24543 		ipha->ipha_length = htons(ip_len);
24544 
24545 		/*
24546 		 * Set the IP header checksum.	Note that mp is just
24547 		 * the header, so this is easy to pass to ip_csum.
24548 		 */
24549 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24550 
24551 		/* Attach a transmit header, if any, and ship it. */
24552 		if (pkt_type == OB_PKT) {
24553 			UPDATE_OB_PKT_COUNT(ire);
24554 		} else {
24555 			out_ill = (ill_t *)q->q_ptr;
24556 			BUMP_MIB(out_ill->ill_ip_mib,
24557 			    ipIfStatsHCOutForwDatagrams);
24558 			UPDATE_IB_PKT_COUNT(ire);
24559 		}
24560 
24561 		if (ire->ire_flags & RTF_MULTIRT) {
24562 			irb = ire->ire_bucket;
24563 			ASSERT(irb != NULL);
24564 
24565 			multirt_send = B_TRUE;
24566 
24567 			/*
24568 			 * Save the original ire; we will need to restore it
24569 			 * for the tailing frags.
24570 			 */
24571 			save_ire = ire;
24572 			IRE_REFHOLD(save_ire);
24573 		}
24574 		/*
24575 		 * Emission loop for this fragment, similar
24576 		 * to what is done for the first fragment.
24577 		 */
24578 		do {
24579 			if (multirt_send) {
24580 				/*
24581 				 * We are in a multiple send case, need to get
24582 				 * the next ire and make a copy of the packet.
24583 				 */
24584 				ASSERT(irb != NULL);
24585 				IRB_REFHOLD(irb);
24586 				for (ire1 = ire->ire_next;
24587 				    ire1 != NULL;
24588 				    ire1 = ire1->ire_next) {
24589 					if (!(ire1->ire_flags & RTF_MULTIRT))
24590 						continue;
24591 					if (ire1->ire_addr != ire->ire_addr)
24592 						continue;
24593 					if (ire1->ire_marks &
24594 					    (IRE_MARK_CONDEMNED|
24595 					    IRE_MARK_HIDDEN)) {
24596 						continue;
24597 					}
24598 					/*
24599 					 * Ensure we do not exceed the MTU
24600 					 * of the next route.
24601 					 */
24602 					if (ire1->ire_max_frag < max_frag) {
24603 						ip_multirt_bad_mtu(ire1,
24604 						    max_frag);
24605 						continue;
24606 					}
24607 
24608 					/* Got one. */
24609 					IRE_REFHOLD(ire1);
24610 					break;
24611 				}
24612 				IRB_REFRELE(irb);
24613 
24614 				if (ire1 != NULL) {
24615 					next_mp = copyb(mp);
24616 					if ((next_mp == NULL) ||
24617 					    ((mp->b_cont != NULL) &&
24618 					    ((next_mp->b_cont =
24619 					    dupmsg(mp->b_cont)) == NULL))) {
24620 						freemsg(next_mp);
24621 						next_mp = NULL;
24622 						ire_refrele(ire1);
24623 						ire1 = NULL;
24624 					}
24625 				}
24626 
24627 				/* Last multiroute ire; don't loop anymore. */
24628 				if (ire1 == NULL) {
24629 					multirt_send = B_FALSE;
24630 				}
24631 			}
24632 
24633 			/* Update transmit header */
24634 			ll_hdr_len = 0;
24635 			LOCK_IRE_FP_MP(ire);
24636 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24637 			if (ll_hdr_mp != NULL) {
24638 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24639 				ll_hdr_len = MBLKL(ll_hdr_mp);
24640 			} else {
24641 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24642 			}
24643 
24644 			if (!ll_hdr_mp) {
24645 				xmit_mp = mp;
24646 
24647 			/*
24648 			 * We have link-layer header that can fit in
24649 			 * our mblk.
24650 			 */
24651 			} else if (mp->b_datap->db_ref == 1 &&
24652 			    ll_hdr_len != 0 &&
24653 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24654 				/* M_DATA fastpath */
24655 				mp->b_rptr -= ll_hdr_len;
24656 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24657 				    ll_hdr_len);
24658 				xmit_mp = mp;
24659 
24660 			/*
24661 			 * Case of res_mp OR the fastpath mp can't fit
24662 			 * in the mblk
24663 			 */
24664 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24665 				xmit_mp->b_cont = mp;
24666 				if (DB_CRED(mp) != NULL)
24667 					mblk_setcred(xmit_mp, DB_CRED(mp));
24668 				/* Get priority marking, if any. */
24669 				if (DB_TYPE(xmit_mp) == M_DATA)
24670 					xmit_mp->b_band = mp->b_band;
24671 
24672 			/* Corner case if copyb failed */
24673 			} else {
24674 				/*
24675 				 * Exit both the replication and
24676 				 * fragmentation loops.
24677 				 */
24678 				UNLOCK_IRE_FP_MP(ire);
24679 				goto drop_pkt;
24680 			}
24681 			UNLOCK_IRE_FP_MP(ire);
24682 
24683 			mp1 = mp;
24684 			out_ill = (ill_t *)q->q_ptr;
24685 
24686 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24687 
24688 			DTRACE_PROBE4(ip4__physical__out__start,
24689 			    ill_t *, NULL, ill_t *, out_ill,
24690 			    ipha_t *, ipha, mblk_t *, xmit_mp);
24691 
24692 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
24693 			    ipst->ips_ipv4firewall_physical_out,
24694 			    NULL, out_ill, ipha, xmit_mp, mp, ipst);
24695 
24696 			DTRACE_PROBE1(ip4__physical__out__end,
24697 			    mblk_t *, xmit_mp);
24698 
24699 			if (mp != mp1 && hdr_mp == mp1)
24700 				hdr_mp = mp;
24701 			if (mp != mp1 && mp_orig == mp1)
24702 				mp_orig = mp;
24703 
24704 			if (xmit_mp != NULL) {
24705 				putnext(q, xmit_mp);
24706 
24707 				BUMP_MIB(out_ill->ill_ip_mib,
24708 				    ipIfStatsHCOutTransmits);
24709 				UPDATE_MIB(out_ill->ill_ip_mib,
24710 				    ipIfStatsHCOutOctets, ip_len);
24711 
24712 				if (pkt_type != OB_PKT) {
24713 					/*
24714 					 * Update the packet count of trailing
24715 					 * RTF_MULTIRT ires.
24716 					 */
24717 					UPDATE_OB_PKT_COUNT(ire);
24718 				}
24719 			}
24720 
24721 			/* All done if we just consumed the hdr_mp. */
24722 			if (mp == hdr_mp) {
24723 				last_frag = B_TRUE;
24724 				BUMP_MIB(out_ill->ill_ip_mib,
24725 				    ipIfStatsOutFragOKs);
24726 			}
24727 
24728 			if (multirt_send) {
24729 				/*
24730 				 * We are in a multiple send case; look for
24731 				 * the next ire and re-enter the loop.
24732 				 */
24733 				ASSERT(ire1);
24734 				ASSERT(next_mp);
24735 				/* REFRELE the current ire before looping */
24736 				ire_refrele(ire);
24737 				ire = ire1;
24738 				ire1 = NULL;
24739 				q = ire->ire_stq;
24740 				mp = next_mp;
24741 				next_mp = NULL;
24742 			}
24743 		} while (multirt_send);
24744 		/*
24745 		 * Restore the original ire; we need it for the
24746 		 * trailing frags
24747 		 */
24748 		if (save_ire != NULL) {
24749 			ASSERT(ire1 == NULL);
24750 			/* REFRELE the last iterated ire */
24751 			ire_refrele(ire);
24752 			/* save_ire has been REFHOLDed */
24753 			ire = save_ire;
24754 			q = ire->ire_stq;
24755 			save_ire = NULL;
24756 		}
24757 
24758 		if (last_frag) {
24759 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24760 			    "ip_wput_frag_end:(%S)",
24761 			    "consumed hdr_mp");
24762 
24763 			if (first_ire != NULL)
24764 				ire_refrele(first_ire);
24765 			return;
24766 		}
24767 		/* Otherwise, advance and loop. */
24768 		offset += len;
24769 	}
24770 
24771 drop_pkt:
24772 	/* Clean up following allocation failure. */
24773 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24774 	freemsg(mp);
24775 	if (mp != hdr_mp)
24776 		freeb(hdr_mp);
24777 	if (mp != mp_orig)
24778 		freemsg(mp_orig);
24779 
24780 	if (save_ire != NULL)
24781 		IRE_REFRELE(save_ire);
24782 	if (first_ire != NULL)
24783 		ire_refrele(first_ire);
24784 
24785 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24786 	    "ip_wput_frag_end:(%S)",
24787 	    "end--alloc failure");
24788 }
24789 
24790 /*
24791  * Copy the header plus those options which have the copy bit set
24792  */
24793 static mblk_t *
24794 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst)
24795 {
24796 	mblk_t	*mp;
24797 	uchar_t	*up;
24798 
24799 	/*
24800 	 * Quick check if we need to look for options without the copy bit
24801 	 * set
24802 	 */
24803 	mp = allocb(ipst->ips_ip_wroff_extra + hdr_len, BPRI_HI);
24804 	if (!mp)
24805 		return (mp);
24806 	mp->b_rptr += ipst->ips_ip_wroff_extra;
24807 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
24808 		bcopy(rptr, mp->b_rptr, hdr_len);
24809 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
24810 		return (mp);
24811 	}
24812 	up  = mp->b_rptr;
24813 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
24814 	up += IP_SIMPLE_HDR_LENGTH;
24815 	rptr += IP_SIMPLE_HDR_LENGTH;
24816 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
24817 	while (hdr_len > 0) {
24818 		uint32_t optval;
24819 		uint32_t optlen;
24820 
24821 		optval = *rptr;
24822 		if (optval == IPOPT_EOL)
24823 			break;
24824 		if (optval == IPOPT_NOP)
24825 			optlen = 1;
24826 		else
24827 			optlen = rptr[1];
24828 		if (optval & IPOPT_COPY) {
24829 			bcopy(rptr, up, optlen);
24830 			up += optlen;
24831 		}
24832 		rptr += optlen;
24833 		hdr_len -= optlen;
24834 	}
24835 	/*
24836 	 * Make sure that we drop an even number of words by filling
24837 	 * with EOL to the next word boundary.
24838 	 */
24839 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
24840 	    hdr_len & 0x3; hdr_len++)
24841 		*up++ = IPOPT_EOL;
24842 	mp->b_wptr = up;
24843 	/* Update header length */
24844 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
24845 	return (mp);
24846 }
24847 
24848 /*
24849  * Delivery to local recipients including fanout to multiple recipients.
24850  * Does not do checksumming of UDP/TCP.
24851  * Note: q should be the read side queue for either the ill or conn.
24852  * Note: rq should be the read side q for the lower (ill) stream.
24853  * We don't send packets to IPPF processing, thus the last argument
24854  * to all the fanout calls are B_FALSE.
24855  */
24856 void
24857 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
24858     int fanout_flags, zoneid_t zoneid)
24859 {
24860 	uint32_t	protocol;
24861 	mblk_t		*first_mp;
24862 	boolean_t	mctl_present;
24863 	int		ire_type;
24864 #define	rptr	((uchar_t *)ipha)
24865 	ip_stack_t	*ipst = ill->ill_ipst;
24866 
24867 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
24868 	    "ip_wput_local_start: q %p", q);
24869 
24870 	if (ire != NULL) {
24871 		ire_type = ire->ire_type;
24872 	} else {
24873 		/*
24874 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
24875 		 * packet is not multicast, we can't tell the ire type.
24876 		 */
24877 		ASSERT(CLASSD(ipha->ipha_dst));
24878 		ire_type = IRE_BROADCAST;
24879 	}
24880 
24881 	first_mp = mp;
24882 	if (first_mp->b_datap->db_type == M_CTL) {
24883 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
24884 		if (!io->ipsec_out_secure) {
24885 			/*
24886 			 * This ipsec_out_t was allocated in ip_wput
24887 			 * for multicast packets to store the ill_index.
24888 			 * As this is being delivered locally, we don't
24889 			 * need this anymore.
24890 			 */
24891 			mp = first_mp->b_cont;
24892 			freeb(first_mp);
24893 			first_mp = mp;
24894 			mctl_present = B_FALSE;
24895 		} else {
24896 			/*
24897 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
24898 			 * security properties for the looped-back packet.
24899 			 */
24900 			mctl_present = B_TRUE;
24901 			mp = first_mp->b_cont;
24902 			ASSERT(mp != NULL);
24903 			ipsec_out_to_in(first_mp);
24904 		}
24905 	} else {
24906 		mctl_present = B_FALSE;
24907 	}
24908 
24909 	DTRACE_PROBE4(ip4__loopback__in__start,
24910 	    ill_t *, ill, ill_t *, NULL,
24911 	    ipha_t *, ipha, mblk_t *, first_mp);
24912 
24913 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
24914 	    ipst->ips_ipv4firewall_loopback_in,
24915 	    ill, NULL, ipha, first_mp, mp, ipst);
24916 
24917 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
24918 
24919 	if (first_mp == NULL)
24920 		return;
24921 
24922 	ipst->ips_loopback_packets++;
24923 
24924 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
24925 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
24926 	if (!IS_SIMPLE_IPH(ipha)) {
24927 		ip_wput_local_options(ipha, ipst);
24928 	}
24929 
24930 	protocol = ipha->ipha_protocol;
24931 	switch (protocol) {
24932 	case IPPROTO_ICMP: {
24933 		ire_t		*ire_zone;
24934 		ilm_t		*ilm;
24935 		mblk_t		*mp1;
24936 		zoneid_t	last_zoneid;
24937 
24938 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(ill)) {
24939 			ASSERT(ire_type == IRE_BROADCAST);
24940 			/*
24941 			 * In the multicast case, applications may have joined
24942 			 * the group from different zones, so we need to deliver
24943 			 * the packet to each of them. Loop through the
24944 			 * multicast memberships structures (ilm) on the receive
24945 			 * ill and send a copy of the packet up each matching
24946 			 * one. However, we don't do this for multicasts sent on
24947 			 * the loopback interface (PHYI_LOOPBACK flag set) as
24948 			 * they must stay in the sender's zone.
24949 			 *
24950 			 * ilm_add_v6() ensures that ilms in the same zone are
24951 			 * contiguous in the ill_ilm list. We use this property
24952 			 * to avoid sending duplicates needed when two
24953 			 * applications in the same zone join the same group on
24954 			 * different logical interfaces: we ignore the ilm if
24955 			 * it's zoneid is the same as the last matching one.
24956 			 * In addition, the sending of the packet for
24957 			 * ire_zoneid is delayed until all of the other ilms
24958 			 * have been exhausted.
24959 			 */
24960 			last_zoneid = -1;
24961 			ILM_WALKER_HOLD(ill);
24962 			for (ilm = ill->ill_ilm; ilm != NULL;
24963 			    ilm = ilm->ilm_next) {
24964 				if ((ilm->ilm_flags & ILM_DELETED) ||
24965 				    ipha->ipha_dst != ilm->ilm_addr ||
24966 				    ilm->ilm_zoneid == last_zoneid ||
24967 				    ilm->ilm_zoneid == zoneid ||
24968 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
24969 					continue;
24970 				mp1 = ip_copymsg(first_mp);
24971 				if (mp1 == NULL)
24972 					continue;
24973 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
24974 				    mctl_present, B_FALSE, ill,
24975 				    ilm->ilm_zoneid);
24976 				last_zoneid = ilm->ilm_zoneid;
24977 			}
24978 			ILM_WALKER_RELE(ill);
24979 			/*
24980 			 * Loopback case: the sending endpoint has
24981 			 * IP_MULTICAST_LOOP disabled, therefore we don't
24982 			 * dispatch the multicast packet to the sending zone.
24983 			 */
24984 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
24985 				freemsg(first_mp);
24986 				return;
24987 			}
24988 		} else if (ire_type == IRE_BROADCAST) {
24989 			/*
24990 			 * In the broadcast case, there may be many zones
24991 			 * which need a copy of the packet delivered to them.
24992 			 * There is one IRE_BROADCAST per broadcast address
24993 			 * and per zone; we walk those using a helper function.
24994 			 * In addition, the sending of the packet for zoneid is
24995 			 * delayed until all of the other ires have been
24996 			 * processed.
24997 			 */
24998 			IRB_REFHOLD(ire->ire_bucket);
24999 			ire_zone = NULL;
25000 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25001 			    ire)) != NULL) {
25002 				mp1 = ip_copymsg(first_mp);
25003 				if (mp1 == NULL)
25004 					continue;
25005 
25006 				UPDATE_IB_PKT_COUNT(ire_zone);
25007 				ire_zone->ire_last_used_time = lbolt;
25008 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25009 				    mctl_present, B_FALSE, ill,
25010 				    ire_zone->ire_zoneid);
25011 			}
25012 			IRB_REFRELE(ire->ire_bucket);
25013 		}
25014 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25015 		    0, mctl_present, B_FALSE, ill, zoneid);
25016 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25017 		    "ip_wput_local_end: q %p (%S)",
25018 		    q, "icmp");
25019 		return;
25020 	}
25021 	case IPPROTO_IGMP:
25022 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25023 			/* Bad packet - discarded by igmp_input */
25024 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25025 			    "ip_wput_local_end: q %p (%S)",
25026 			    q, "igmp_input--bad packet");
25027 			if (mctl_present)
25028 				freeb(first_mp);
25029 			return;
25030 		}
25031 		/*
25032 		 * igmp_input() may have returned the pulled up message.
25033 		 * So first_mp and ipha need to be reinitialized.
25034 		 */
25035 		ipha = (ipha_t *)mp->b_rptr;
25036 		if (mctl_present)
25037 			first_mp->b_cont = mp;
25038 		else
25039 			first_mp = mp;
25040 		/* deliver to local raw users */
25041 		break;
25042 	case IPPROTO_ENCAP:
25043 		/*
25044 		 * This case is covered by either ip_fanout_proto, or by
25045 		 * the above security processing for self-tunneled packets.
25046 		 */
25047 		break;
25048 	case IPPROTO_UDP: {
25049 		uint16_t	*up;
25050 		uint32_t	ports;
25051 
25052 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25053 		    UDP_PORTS_OFFSET);
25054 		/* Force a 'valid' checksum. */
25055 		up[3] = 0;
25056 
25057 		ports = *(uint32_t *)up;
25058 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25059 		    (ire_type == IRE_BROADCAST),
25060 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25061 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25062 		    ill, zoneid);
25063 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25064 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25065 		return;
25066 	}
25067 	case IPPROTO_TCP: {
25068 
25069 		/*
25070 		 * For TCP, discard broadcast packets.
25071 		 */
25072 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25073 			freemsg(first_mp);
25074 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25075 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25076 			return;
25077 		}
25078 
25079 		if (mp->b_datap->db_type == M_DATA) {
25080 			/*
25081 			 * M_DATA mblk, so init mblk (chain) for no struio().
25082 			 */
25083 			mblk_t	*mp1 = mp;
25084 
25085 			do {
25086 				mp1->b_datap->db_struioflag = 0;
25087 			} while ((mp1 = mp1->b_cont) != NULL);
25088 		}
25089 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25090 		    <= mp->b_wptr);
25091 		ip_fanout_tcp(q, first_mp, ill, ipha,
25092 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25093 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25094 		    mctl_present, B_FALSE, zoneid);
25095 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25096 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25097 		return;
25098 	}
25099 	case IPPROTO_SCTP:
25100 	{
25101 		uint32_t	ports;
25102 
25103 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25104 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25105 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25106 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25107 		return;
25108 	}
25109 
25110 	default:
25111 		break;
25112 	}
25113 	/*
25114 	 * Find a client for some other protocol.  We give
25115 	 * copies to multiple clients, if more than one is
25116 	 * bound.
25117 	 */
25118 	ip_fanout_proto(q, first_mp, ill, ipha,
25119 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25120 	    mctl_present, B_FALSE, ill, zoneid);
25121 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25122 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25123 #undef	rptr
25124 }
25125 
25126 /*
25127  * Update any source route, record route, or timestamp options.
25128  * Check that we are at end of strict source route.
25129  * The options have been sanity checked by ip_wput_options().
25130  */
25131 static void
25132 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25133 {
25134 	ipoptp_t	opts;
25135 	uchar_t		*opt;
25136 	uint8_t		optval;
25137 	uint8_t		optlen;
25138 	ipaddr_t	dst;
25139 	uint32_t	ts;
25140 	ire_t		*ire;
25141 	timestruc_t	now;
25142 
25143 	ip2dbg(("ip_wput_local_options\n"));
25144 	for (optval = ipoptp_first(&opts, ipha);
25145 	    optval != IPOPT_EOL;
25146 	    optval = ipoptp_next(&opts)) {
25147 		opt = opts.ipoptp_cur;
25148 		optlen = opts.ipoptp_len;
25149 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25150 		switch (optval) {
25151 			uint32_t off;
25152 		case IPOPT_SSRR:
25153 		case IPOPT_LSRR:
25154 			off = opt[IPOPT_OFFSET];
25155 			off--;
25156 			if (optlen < IP_ADDR_LEN ||
25157 			    off > optlen - IP_ADDR_LEN) {
25158 				/* End of source route */
25159 				break;
25160 			}
25161 			/*
25162 			 * This will only happen if two consecutive entries
25163 			 * in the source route contains our address or if
25164 			 * it is a packet with a loose source route which
25165 			 * reaches us before consuming the whole source route
25166 			 */
25167 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25168 			if (optval == IPOPT_SSRR) {
25169 				return;
25170 			}
25171 			/*
25172 			 * Hack: instead of dropping the packet truncate the
25173 			 * source route to what has been used by filling the
25174 			 * rest with IPOPT_NOP.
25175 			 */
25176 			opt[IPOPT_OLEN] = (uint8_t)off;
25177 			while (off < optlen) {
25178 				opt[off++] = IPOPT_NOP;
25179 			}
25180 			break;
25181 		case IPOPT_RR:
25182 			off = opt[IPOPT_OFFSET];
25183 			off--;
25184 			if (optlen < IP_ADDR_LEN ||
25185 			    off > optlen - IP_ADDR_LEN) {
25186 				/* No more room - ignore */
25187 				ip1dbg((
25188 				    "ip_wput_forward_options: end of RR\n"));
25189 				break;
25190 			}
25191 			dst = htonl(INADDR_LOOPBACK);
25192 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25193 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25194 			break;
25195 		case IPOPT_TS:
25196 			/* Insert timestamp if there is romm */
25197 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25198 			case IPOPT_TS_TSONLY:
25199 				off = IPOPT_TS_TIMELEN;
25200 				break;
25201 			case IPOPT_TS_PRESPEC:
25202 			case IPOPT_TS_PRESPEC_RFC791:
25203 				/* Verify that the address matched */
25204 				off = opt[IPOPT_OFFSET] - 1;
25205 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25206 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25207 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25208 				    ipst);
25209 				if (ire == NULL) {
25210 					/* Not for us */
25211 					break;
25212 				}
25213 				ire_refrele(ire);
25214 				/* FALLTHRU */
25215 			case IPOPT_TS_TSANDADDR:
25216 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25217 				break;
25218 			default:
25219 				/*
25220 				 * ip_*put_options should have already
25221 				 * dropped this packet.
25222 				 */
25223 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25224 				    "unknown IT - bug in ip_wput_options?\n");
25225 				return;	/* Keep "lint" happy */
25226 			}
25227 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25228 				/* Increase overflow counter */
25229 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25230 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25231 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25232 				    (off << 4);
25233 				break;
25234 			}
25235 			off = opt[IPOPT_OFFSET] - 1;
25236 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25237 			case IPOPT_TS_PRESPEC:
25238 			case IPOPT_TS_PRESPEC_RFC791:
25239 			case IPOPT_TS_TSANDADDR:
25240 				dst = htonl(INADDR_LOOPBACK);
25241 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25242 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25243 				/* FALLTHRU */
25244 			case IPOPT_TS_TSONLY:
25245 				off = opt[IPOPT_OFFSET] - 1;
25246 				/* Compute # of milliseconds since midnight */
25247 				gethrestime(&now);
25248 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25249 				    now.tv_nsec / (NANOSEC / MILLISEC);
25250 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25251 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25252 				break;
25253 			}
25254 			break;
25255 		}
25256 	}
25257 }
25258 
25259 /*
25260  * Send out a multicast packet on interface ipif.
25261  * The sender does not have an conn.
25262  * Caller verifies that this isn't a PHYI_LOOPBACK.
25263  */
25264 void
25265 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25266 {
25267 	ipha_t	*ipha;
25268 	ire_t	*ire;
25269 	ipaddr_t	dst;
25270 	mblk_t		*first_mp;
25271 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25272 
25273 	/* igmp_sendpkt always allocates a ipsec_out_t */
25274 	ASSERT(mp->b_datap->db_type == M_CTL);
25275 	ASSERT(!ipif->ipif_isv6);
25276 	ASSERT(!IS_LOOPBACK(ipif->ipif_ill));
25277 
25278 	first_mp = mp;
25279 	mp = first_mp->b_cont;
25280 	ASSERT(mp->b_datap->db_type == M_DATA);
25281 	ipha = (ipha_t *)mp->b_rptr;
25282 
25283 	/*
25284 	 * Find an IRE which matches the destination and the outgoing
25285 	 * queue (i.e. the outgoing interface.)
25286 	 */
25287 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25288 		dst = ipif->ipif_pp_dst_addr;
25289 	else
25290 		dst = ipha->ipha_dst;
25291 	/*
25292 	 * The source address has already been initialized by the
25293 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25294 	 * be sufficient rather than MATCH_IRE_IPIF.
25295 	 *
25296 	 * This function is used for sending IGMP packets. We need
25297 	 * to make sure that we send the packet out of the interface
25298 	 * (ipif->ipif_ill) where we joined the group. This is to
25299 	 * prevent from switches doing IGMP snooping to send us multicast
25300 	 * packets for a given group on the interface we have joined.
25301 	 * If we can't find an ire, igmp_sendpkt has already initialized
25302 	 * ipsec_out_attach_if so that this will not be load spread in
25303 	 * ip_newroute_ipif.
25304 	 */
25305 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25306 	    MATCH_IRE_ILL, ipst);
25307 	if (!ire) {
25308 		/*
25309 		 * Mark this packet to make it be delivered to
25310 		 * ip_wput_ire after the new ire has been
25311 		 * created.
25312 		 */
25313 		mp->b_prev = NULL;
25314 		mp->b_next = NULL;
25315 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25316 		    zoneid, &zero_info);
25317 		return;
25318 	}
25319 
25320 	/*
25321 	 * Honor the RTF_SETSRC flag; this is the only case
25322 	 * where we force this addr whatever the current src addr is,
25323 	 * because this address is set by igmp_sendpkt(), and
25324 	 * cannot be specified by any user.
25325 	 */
25326 	if (ire->ire_flags & RTF_SETSRC) {
25327 		ipha->ipha_src = ire->ire_src_addr;
25328 	}
25329 
25330 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25331 }
25332 
25333 /*
25334  * NOTE : This function does not ire_refrele the ire argument passed in.
25335  *
25336  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25337  * failure. The nce_fp_mp can vanish any time in the case of
25338  * IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25339  * the ire_lock to access the nce_fp_mp in this case.
25340  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25341  * prepending a fastpath message IPQoS processing must precede it, we also set
25342  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25343  * (IPQoS might have set the b_band for CoS marking).
25344  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25345  * must follow it so that IPQoS can mark the dl_priority field for CoS
25346  * marking, if needed.
25347  */
25348 static mblk_t *
25349 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
25350 {
25351 	uint_t	hlen;
25352 	ipha_t *ipha;
25353 	mblk_t *mp1;
25354 	boolean_t qos_done = B_FALSE;
25355 	uchar_t	*ll_hdr;
25356 	ip_stack_t	*ipst = ire->ire_ipst;
25357 
25358 #define	rptr	((uchar_t *)ipha)
25359 
25360 	ipha = (ipha_t *)mp->b_rptr;
25361 	hlen = 0;
25362 	LOCK_IRE_FP_MP(ire);
25363 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25364 		ASSERT(DB_TYPE(mp1) == M_DATA);
25365 		/* Initiate IPPF processing */
25366 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25367 			UNLOCK_IRE_FP_MP(ire);
25368 			ip_process(proc, &mp, ill_index);
25369 			if (mp == NULL)
25370 				return (NULL);
25371 
25372 			ipha = (ipha_t *)mp->b_rptr;
25373 			LOCK_IRE_FP_MP(ire);
25374 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25375 				qos_done = B_TRUE;
25376 				goto no_fp_mp;
25377 			}
25378 			ASSERT(DB_TYPE(mp1) == M_DATA);
25379 		}
25380 		hlen = MBLKL(mp1);
25381 		/*
25382 		 * Check if we have enough room to prepend fastpath
25383 		 * header
25384 		 */
25385 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25386 			ll_hdr = rptr - hlen;
25387 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25388 			/*
25389 			 * Set the b_rptr to the start of the link layer
25390 			 * header
25391 			 */
25392 			mp->b_rptr = ll_hdr;
25393 			mp1 = mp;
25394 		} else {
25395 			mp1 = copyb(mp1);
25396 			if (mp1 == NULL)
25397 				goto unlock_err;
25398 			mp1->b_band = mp->b_band;
25399 			mp1->b_cont = mp;
25400 			/*
25401 			 * certain system generated traffic may not
25402 			 * have cred/label in ip header block. This
25403 			 * is true even for a labeled system. But for
25404 			 * labeled traffic, inherit the label in the
25405 			 * new header.
25406 			 */
25407 			if (DB_CRED(mp) != NULL)
25408 				mblk_setcred(mp1, DB_CRED(mp));
25409 			/*
25410 			 * XXX disable ICK_VALID and compute checksum
25411 			 * here; can happen if nce_fp_mp changes and
25412 			 * it can't be copied now due to insufficient
25413 			 * space. (unlikely, fp mp can change, but it
25414 			 * does not increase in length)
25415 			 */
25416 		}
25417 		UNLOCK_IRE_FP_MP(ire);
25418 	} else {
25419 no_fp_mp:
25420 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25421 		if (mp1 == NULL) {
25422 unlock_err:
25423 			UNLOCK_IRE_FP_MP(ire);
25424 			freemsg(mp);
25425 			return (NULL);
25426 		}
25427 		UNLOCK_IRE_FP_MP(ire);
25428 		mp1->b_cont = mp;
25429 		/*
25430 		 * certain system generated traffic may not
25431 		 * have cred/label in ip header block. This
25432 		 * is true even for a labeled system. But for
25433 		 * labeled traffic, inherit the label in the
25434 		 * new header.
25435 		 */
25436 		if (DB_CRED(mp) != NULL)
25437 			mblk_setcred(mp1, DB_CRED(mp));
25438 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25439 			ip_process(proc, &mp1, ill_index);
25440 			if (mp1 == NULL)
25441 				return (NULL);
25442 		}
25443 	}
25444 	return (mp1);
25445 #undef rptr
25446 }
25447 
25448 /*
25449  * Finish the outbound IPsec processing for an IPv6 packet. This function
25450  * is called from ipsec_out_process() if the IPsec packet was processed
25451  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25452  * asynchronously.
25453  */
25454 void
25455 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25456     ire_t *ire_arg)
25457 {
25458 	in6_addr_t *v6dstp;
25459 	ire_t *ire;
25460 	mblk_t *mp;
25461 	ip6_t *ip6h1;
25462 	uint_t	ill_index;
25463 	ipsec_out_t *io;
25464 	boolean_t attach_if, hwaccel;
25465 	uint32_t flags = IP6_NO_IPPOLICY;
25466 	int match_flags;
25467 	zoneid_t zoneid;
25468 	boolean_t ill_need_rele = B_FALSE;
25469 	boolean_t ire_need_rele = B_FALSE;
25470 	ip_stack_t	*ipst;
25471 
25472 	mp = ipsec_mp->b_cont;
25473 	ip6h1 = (ip6_t *)mp->b_rptr;
25474 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25475 	ASSERT(io->ipsec_out_ns != NULL);
25476 	ipst = io->ipsec_out_ns->netstack_ip;
25477 	ill_index = io->ipsec_out_ill_index;
25478 	if (io->ipsec_out_reachable) {
25479 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25480 	}
25481 	attach_if = io->ipsec_out_attach_if;
25482 	hwaccel = io->ipsec_out_accelerated;
25483 	zoneid = io->ipsec_out_zoneid;
25484 	ASSERT(zoneid != ALL_ZONES);
25485 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25486 	/* Multicast addresses should have non-zero ill_index. */
25487 	v6dstp = &ip6h->ip6_dst;
25488 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25489 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25490 	ASSERT(!attach_if || ill_index != 0);
25491 	if (ill_index != 0) {
25492 		if (ill == NULL) {
25493 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
25494 			    B_TRUE, ipst);
25495 
25496 			/* Failure case frees things for us. */
25497 			if (ill == NULL)
25498 				return;
25499 
25500 			ill_need_rele = B_TRUE;
25501 		}
25502 		/*
25503 		 * If this packet needs to go out on a particular interface
25504 		 * honor it.
25505 		 */
25506 		if (attach_if) {
25507 			match_flags = MATCH_IRE_ILL;
25508 
25509 			/*
25510 			 * Check if we need an ire that will not be
25511 			 * looked up by anybody else i.e. HIDDEN.
25512 			 */
25513 			if (ill_is_probeonly(ill)) {
25514 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25515 			}
25516 		}
25517 	}
25518 	ASSERT(mp != NULL);
25519 
25520 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25521 		boolean_t unspec_src;
25522 		ipif_t	*ipif;
25523 
25524 		/*
25525 		 * Use the ill_index to get the right ill.
25526 		 */
25527 		unspec_src = io->ipsec_out_unspec_src;
25528 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25529 		if (ipif == NULL) {
25530 			if (ill_need_rele)
25531 				ill_refrele(ill);
25532 			freemsg(ipsec_mp);
25533 			return;
25534 		}
25535 
25536 		if (ire_arg != NULL) {
25537 			ire = ire_arg;
25538 		} else {
25539 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25540 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25541 			ire_need_rele = B_TRUE;
25542 		}
25543 		if (ire != NULL) {
25544 			ipif_refrele(ipif);
25545 			/*
25546 			 * XXX Do the multicast forwarding now, as the IPsec
25547 			 * processing has been done.
25548 			 */
25549 			goto send;
25550 		}
25551 
25552 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25553 		mp->b_prev = NULL;
25554 		mp->b_next = NULL;
25555 
25556 		/*
25557 		 * If the IPsec packet was processed asynchronously,
25558 		 * drop it now.
25559 		 */
25560 		if (q == NULL) {
25561 			if (ill_need_rele)
25562 				ill_refrele(ill);
25563 			freemsg(ipsec_mp);
25564 			return;
25565 		}
25566 
25567 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
25568 		    unspec_src, zoneid);
25569 		ipif_refrele(ipif);
25570 	} else {
25571 		if (attach_if) {
25572 			ipif_t	*ipif;
25573 
25574 			ipif = ipif_get_next_ipif(NULL, ill);
25575 			if (ipif == NULL) {
25576 				if (ill_need_rele)
25577 					ill_refrele(ill);
25578 				freemsg(ipsec_mp);
25579 				return;
25580 			}
25581 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25582 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25583 			ire_need_rele = B_TRUE;
25584 			ipif_refrele(ipif);
25585 		} else {
25586 			if (ire_arg != NULL) {
25587 				ire = ire_arg;
25588 			} else {
25589 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL,
25590 				    ipst);
25591 				ire_need_rele = B_TRUE;
25592 			}
25593 		}
25594 		if (ire != NULL)
25595 			goto send;
25596 		/*
25597 		 * ire disappeared underneath.
25598 		 *
25599 		 * What we need to do here is the ip_newroute
25600 		 * logic to get the ire without doing the IPsec
25601 		 * processing. Follow the same old path. But this
25602 		 * time, ip_wput or ire_add_then_send will call us
25603 		 * directly as all the IPsec operations are done.
25604 		 */
25605 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25606 		mp->b_prev = NULL;
25607 		mp->b_next = NULL;
25608 
25609 		/*
25610 		 * If the IPsec packet was processed asynchronously,
25611 		 * drop it now.
25612 		 */
25613 		if (q == NULL) {
25614 			if (ill_need_rele)
25615 				ill_refrele(ill);
25616 			freemsg(ipsec_mp);
25617 			return;
25618 		}
25619 
25620 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25621 		    zoneid, ipst);
25622 	}
25623 	if (ill != NULL && ill_need_rele)
25624 		ill_refrele(ill);
25625 	return;
25626 send:
25627 	if (ill != NULL && ill_need_rele)
25628 		ill_refrele(ill);
25629 
25630 	/* Local delivery */
25631 	if (ire->ire_stq == NULL) {
25632 		ill_t	*out_ill;
25633 		ASSERT(q != NULL);
25634 
25635 		/* PFHooks: LOOPBACK_OUT */
25636 		out_ill = ire_to_ill(ire);
25637 
25638 		DTRACE_PROBE4(ip6__loopback__out__start,
25639 		    ill_t *, NULL, ill_t *, out_ill,
25640 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25641 
25642 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
25643 		    ipst->ips_ipv6firewall_loopback_out,
25644 		    NULL, out_ill, ip6h1, ipsec_mp, mp, ipst);
25645 
25646 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25647 
25648 		if (ipsec_mp != NULL)
25649 			ip_wput_local_v6(RD(q), out_ill,
25650 			    ip6h, ipsec_mp, ire, 0);
25651 		if (ire_need_rele)
25652 			ire_refrele(ire);
25653 		return;
25654 	}
25655 	/*
25656 	 * Everything is done. Send it out on the wire.
25657 	 * We force the insertion of a fragment header using the
25658 	 * IPH_FRAG_HDR flag in two cases:
25659 	 * - after reception of an ICMPv6 "packet too big" message
25660 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25661 	 * - for multirouted IPv6 packets, so that the receiver can
25662 	 *   discard duplicates according to their fragment identifier
25663 	 */
25664 	/* XXX fix flow control problems. */
25665 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25666 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25667 		if (hwaccel) {
25668 			/*
25669 			 * hardware acceleration does not handle these
25670 			 * "slow path" cases.
25671 			 */
25672 			/* IPsec KSTATS: should bump bean counter here. */
25673 			if (ire_need_rele)
25674 				ire_refrele(ire);
25675 			freemsg(ipsec_mp);
25676 			return;
25677 		}
25678 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25679 		    (mp->b_cont ? msgdsize(mp) :
25680 		    mp->b_wptr - (uchar_t *)ip6h)) {
25681 			/* IPsec KSTATS: should bump bean counter here. */
25682 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25683 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25684 			    msgdsize(mp)));
25685 			if (ire_need_rele)
25686 				ire_refrele(ire);
25687 			freemsg(ipsec_mp);
25688 			return;
25689 		}
25690 		ASSERT(mp->b_prev == NULL);
25691 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
25692 		    ntohs(ip6h->ip6_plen) +
25693 		    IPV6_HDR_LEN, ire->ire_max_frag));
25694 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
25695 		    ire->ire_max_frag);
25696 	} else {
25697 		UPDATE_OB_PKT_COUNT(ire);
25698 		ire->ire_last_used_time = lbolt;
25699 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
25700 	}
25701 	if (ire_need_rele)
25702 		ire_refrele(ire);
25703 	freeb(ipsec_mp);
25704 }
25705 
25706 void
25707 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
25708 {
25709 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
25710 	da_ipsec_t *hada;	/* data attributes */
25711 	ill_t *ill = (ill_t *)q->q_ptr;
25712 
25713 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
25714 
25715 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
25716 		/* IPsec KSTATS: Bump lose counter here! */
25717 		freemsg(mp);
25718 		return;
25719 	}
25720 
25721 	/*
25722 	 * It's an IPsec packet that must be
25723 	 * accelerated by the Provider, and the
25724 	 * outbound ill is IPsec acceleration capable.
25725 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
25726 	 * to the ill.
25727 	 * IPsec KSTATS: should bump packet counter here.
25728 	 */
25729 
25730 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
25731 	if (hada_mp == NULL) {
25732 		/* IPsec KSTATS: should bump packet counter here. */
25733 		freemsg(mp);
25734 		return;
25735 	}
25736 
25737 	hada_mp->b_datap->db_type = M_CTL;
25738 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
25739 	hada_mp->b_cont = mp;
25740 
25741 	hada = (da_ipsec_t *)hada_mp->b_rptr;
25742 	bzero(hada, sizeof (da_ipsec_t));
25743 	hada->da_type = IPHADA_M_CTL;
25744 
25745 	putnext(q, hada_mp);
25746 }
25747 
25748 /*
25749  * Finish the outbound IPsec processing. This function is called from
25750  * ipsec_out_process() if the IPsec packet was processed
25751  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25752  * asynchronously.
25753  */
25754 void
25755 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
25756     ire_t *ire_arg)
25757 {
25758 	uint32_t v_hlen_tos_len;
25759 	ipaddr_t	dst;
25760 	ipif_t	*ipif = NULL;
25761 	ire_t *ire;
25762 	ire_t *ire1 = NULL;
25763 	mblk_t *next_mp = NULL;
25764 	uint32_t max_frag;
25765 	boolean_t multirt_send = B_FALSE;
25766 	mblk_t *mp;
25767 	ipha_t *ipha1;
25768 	uint_t	ill_index;
25769 	ipsec_out_t *io;
25770 	boolean_t attach_if;
25771 	int match_flags;
25772 	irb_t *irb = NULL;
25773 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
25774 	zoneid_t zoneid;
25775 	ipxmit_state_t	pktxmit_state;
25776 	ip_stack_t	*ipst;
25777 
25778 #ifdef	_BIG_ENDIAN
25779 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
25780 #else
25781 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
25782 #endif
25783 
25784 	mp = ipsec_mp->b_cont;
25785 	ipha1 = (ipha_t *)mp->b_rptr;
25786 	ASSERT(mp != NULL);
25787 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
25788 	dst = ipha->ipha_dst;
25789 
25790 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25791 	ill_index = io->ipsec_out_ill_index;
25792 	attach_if = io->ipsec_out_attach_if;
25793 	zoneid = io->ipsec_out_zoneid;
25794 	ASSERT(zoneid != ALL_ZONES);
25795 	ipst = io->ipsec_out_ns->netstack_ip;
25796 	ASSERT(io->ipsec_out_ns != NULL);
25797 
25798 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25799 	if (ill_index != 0) {
25800 		if (ill == NULL) {
25801 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
25802 			    ill_index, B_FALSE, ipst);
25803 
25804 			/* Failure case frees things for us. */
25805 			if (ill == NULL)
25806 				return;
25807 
25808 			ill_need_rele = B_TRUE;
25809 		}
25810 		/*
25811 		 * If this packet needs to go out on a particular interface
25812 		 * honor it.
25813 		 */
25814 		if (attach_if) {
25815 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25816 
25817 			/*
25818 			 * Check if we need an ire that will not be
25819 			 * looked up by anybody else i.e. HIDDEN.
25820 			 */
25821 			if (ill_is_probeonly(ill)) {
25822 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25823 			}
25824 		}
25825 	}
25826 
25827 	if (CLASSD(dst)) {
25828 		boolean_t conn_dontroute;
25829 		/*
25830 		 * Use the ill_index to get the right ipif.
25831 		 */
25832 		conn_dontroute = io->ipsec_out_dontroute;
25833 		if (ill_index == 0)
25834 			ipif = ipif_lookup_group(dst, zoneid, ipst);
25835 		else
25836 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25837 		if (ipif == NULL) {
25838 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
25839 			    " multicast\n"));
25840 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
25841 			freemsg(ipsec_mp);
25842 			goto done;
25843 		}
25844 		/*
25845 		 * ipha_src has already been intialized with the
25846 		 * value of the ipif in ip_wput. All we need now is
25847 		 * an ire to send this downstream.
25848 		 */
25849 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
25850 		    MBLK_GETLABEL(mp), match_flags, ipst);
25851 		if (ire != NULL) {
25852 			ill_t *ill1;
25853 			/*
25854 			 * Do the multicast forwarding now, as the IPsec
25855 			 * processing has been done.
25856 			 */
25857 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
25858 			    (ill1 = ire_to_ill(ire))) {
25859 				if (ip_mforward(ill1, ipha, mp)) {
25860 					freemsg(ipsec_mp);
25861 					ip1dbg(("ip_wput_ipsec_out: mforward "
25862 					    "failed\n"));
25863 					ire_refrele(ire);
25864 					goto done;
25865 				}
25866 			}
25867 			goto send;
25868 		}
25869 
25870 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
25871 		mp->b_prev = NULL;
25872 		mp->b_next = NULL;
25873 
25874 		/*
25875 		 * If the IPsec packet was processed asynchronously,
25876 		 * drop it now.
25877 		 */
25878 		if (q == NULL) {
25879 			freemsg(ipsec_mp);
25880 			goto done;
25881 		}
25882 
25883 		/*
25884 		 * We may be using a wrong ipif to create the ire.
25885 		 * But it is okay as the source address is assigned
25886 		 * for the packet already. Next outbound packet would
25887 		 * create the IRE with the right IPIF in ip_wput.
25888 		 *
25889 		 * Also handle RTF_MULTIRT routes.
25890 		 */
25891 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
25892 		    zoneid, &zero_info);
25893 	} else {
25894 		if (attach_if) {
25895 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
25896 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25897 		} else {
25898 			if (ire_arg != NULL) {
25899 				ire = ire_arg;
25900 				ire_need_rele = B_FALSE;
25901 			} else {
25902 				ire = ire_cache_lookup(dst, zoneid,
25903 				    MBLK_GETLABEL(mp), ipst);
25904 			}
25905 		}
25906 		if (ire != NULL) {
25907 			goto send;
25908 		}
25909 
25910 		/*
25911 		 * ire disappeared underneath.
25912 		 *
25913 		 * What we need to do here is the ip_newroute
25914 		 * logic to get the ire without doing the IPsec
25915 		 * processing. Follow the same old path. But this
25916 		 * time, ip_wput or ire_add_then_put will call us
25917 		 * directly as all the IPsec operations are done.
25918 		 */
25919 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
25920 		mp->b_prev = NULL;
25921 		mp->b_next = NULL;
25922 
25923 		/*
25924 		 * If the IPsec packet was processed asynchronously,
25925 		 * drop it now.
25926 		 */
25927 		if (q == NULL) {
25928 			freemsg(ipsec_mp);
25929 			goto done;
25930 		}
25931 
25932 		/*
25933 		 * Since we're going through ip_newroute() again, we
25934 		 * need to make sure we don't:
25935 		 *
25936 		 *	1.) Trigger the ASSERT() with the ipha_ident
25937 		 *	    overloading.
25938 		 *	2.) Redo transport-layer checksumming, since we've
25939 		 *	    already done all that to get this far.
25940 		 *
25941 		 * The easiest way not do either of the above is to set
25942 		 * the ipha_ident field to IP_HDR_INCLUDED.
25943 		 */
25944 		ipha->ipha_ident = IP_HDR_INCLUDED;
25945 		ip_newroute(q, ipsec_mp, dst, (CONN_Q(q) ? Q_TO_CONN(q) : NULL),
25946 		    zoneid, ipst);
25947 	}
25948 	goto done;
25949 send:
25950 	if (ire->ire_stq == NULL) {
25951 		ill_t	*out_ill;
25952 		/*
25953 		 * Loopbacks go through ip_wput_local except for one case.
25954 		 * We come here if we generate a icmp_frag_needed message
25955 		 * after IPsec processing is over. When this function calls
25956 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
25957 		 * icmp_frag_needed. The message generated comes back here
25958 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
25959 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
25960 		 * source address as it is usually set in ip_wput_ire. As
25961 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
25962 		 * and we end up here. We can't enter ip_wput_ire once the
25963 		 * IPsec processing is over and hence we need to do it here.
25964 		 */
25965 		ASSERT(q != NULL);
25966 		UPDATE_OB_PKT_COUNT(ire);
25967 		ire->ire_last_used_time = lbolt;
25968 		if (ipha->ipha_src == 0)
25969 			ipha->ipha_src = ire->ire_src_addr;
25970 
25971 		/* PFHooks: LOOPBACK_OUT */
25972 		out_ill = ire_to_ill(ire);
25973 
25974 		DTRACE_PROBE4(ip4__loopback__out__start,
25975 		    ill_t *, NULL, ill_t *, out_ill,
25976 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
25977 
25978 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
25979 		    ipst->ips_ipv4firewall_loopback_out,
25980 		    NULL, out_ill, ipha1, ipsec_mp, mp, ipst);
25981 
25982 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
25983 
25984 		if (ipsec_mp != NULL)
25985 			ip_wput_local(RD(q), out_ill,
25986 			    ipha, ipsec_mp, ire, 0, zoneid);
25987 		if (ire_need_rele)
25988 			ire_refrele(ire);
25989 		goto done;
25990 	}
25991 
25992 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
25993 		/*
25994 		 * We are through with IPsec processing.
25995 		 * Fragment this and send it on the wire.
25996 		 */
25997 		if (io->ipsec_out_accelerated) {
25998 			/*
25999 			 * The packet has been accelerated but must
26000 			 * be fragmented. This should not happen
26001 			 * since AH and ESP must not accelerate
26002 			 * packets that need fragmentation, however
26003 			 * the configuration could have changed
26004 			 * since the AH or ESP processing.
26005 			 * Drop packet.
26006 			 * IPsec KSTATS: bump bean counter here.
26007 			 */
26008 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
26009 			    "fragmented accelerated packet!\n"));
26010 			freemsg(ipsec_mp);
26011 		} else {
26012 			ip_wput_ire_fragmentit(ipsec_mp, ire, zoneid, ipst);
26013 		}
26014 		if (ire_need_rele)
26015 			ire_refrele(ire);
26016 		goto done;
26017 	}
26018 
26019 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
26020 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
26021 	    (void *)ire->ire_ipif, (void *)ipif));
26022 
26023 	/*
26024 	 * Multiroute the secured packet, unless IPsec really
26025 	 * requires the packet to go out only through a particular
26026 	 * interface.
26027 	 */
26028 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
26029 		ire_t *first_ire;
26030 		irb = ire->ire_bucket;
26031 		ASSERT(irb != NULL);
26032 		/*
26033 		 * This ire has been looked up as the one that
26034 		 * goes through the given ipif;
26035 		 * make sure we do not omit any other multiroute ire
26036 		 * that may be present in the bucket before this one.
26037 		 */
26038 		IRB_REFHOLD(irb);
26039 		for (first_ire = irb->irb_ire;
26040 		    first_ire != NULL;
26041 		    first_ire = first_ire->ire_next) {
26042 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
26043 			    (first_ire->ire_addr == ire->ire_addr) &&
26044 			    !(first_ire->ire_marks &
26045 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
26046 				break;
26047 			}
26048 		}
26049 
26050 		if ((first_ire != NULL) && (first_ire != ire)) {
26051 			/*
26052 			 * Don't change the ire if the packet must
26053 			 * be fragmented if sent via this new one.
26054 			 */
26055 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26056 				IRE_REFHOLD(first_ire);
26057 				if (ire_need_rele)
26058 					ire_refrele(ire);
26059 				else
26060 					ire_need_rele = B_TRUE;
26061 				ire = first_ire;
26062 			}
26063 		}
26064 		IRB_REFRELE(irb);
26065 
26066 		multirt_send = B_TRUE;
26067 		max_frag = ire->ire_max_frag;
26068 	} else {
26069 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
26070 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
26071 			    "flag, attach_if %d\n", attach_if));
26072 		}
26073 	}
26074 
26075 	/*
26076 	 * In most cases, the emission loop below is entered only once.
26077 	 * Only in the case where the ire holds the RTF_MULTIRT
26078 	 * flag, we loop to process all RTF_MULTIRT ires in the
26079 	 * bucket, and send the packet through all crossed
26080 	 * RTF_MULTIRT routes.
26081 	 */
26082 	do {
26083 		if (multirt_send) {
26084 			/*
26085 			 * ire1 holds here the next ire to process in the
26086 			 * bucket. If multirouting is expected,
26087 			 * any non-RTF_MULTIRT ire that has the
26088 			 * right destination address is ignored.
26089 			 */
26090 			ASSERT(irb != NULL);
26091 			IRB_REFHOLD(irb);
26092 			for (ire1 = ire->ire_next;
26093 			    ire1 != NULL;
26094 			    ire1 = ire1->ire_next) {
26095 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26096 					continue;
26097 				if (ire1->ire_addr != ire->ire_addr)
26098 					continue;
26099 				if (ire1->ire_marks &
26100 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
26101 					continue;
26102 				/* No loopback here */
26103 				if (ire1->ire_stq == NULL)
26104 					continue;
26105 				/*
26106 				 * Ensure we do not exceed the MTU
26107 				 * of the next route.
26108 				 */
26109 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26110 					ip_multirt_bad_mtu(ire1, max_frag);
26111 					continue;
26112 				}
26113 
26114 				IRE_REFHOLD(ire1);
26115 				break;
26116 			}
26117 			IRB_REFRELE(irb);
26118 			if (ire1 != NULL) {
26119 				/*
26120 				 * We are in a multiple send case, need to
26121 				 * make a copy of the packet.
26122 				 */
26123 				next_mp = copymsg(ipsec_mp);
26124 				if (next_mp == NULL) {
26125 					ire_refrele(ire1);
26126 					ire1 = NULL;
26127 				}
26128 			}
26129 		}
26130 		/*
26131 		 * Everything is done. Send it out on the wire
26132 		 *
26133 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26134 		 * either send it on the wire or, in the case of
26135 		 * HW acceleration, call ipsec_hw_putnext.
26136 		 */
26137 		if (ire->ire_nce &&
26138 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26139 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26140 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26141 			/*
26142 			 * If ire's link-layer is unresolved (this
26143 			 * would only happen if the incomplete ire
26144 			 * was added to cachetable via forwarding path)
26145 			 * don't bother going to ip_xmit_v4. Just drop the
26146 			 * packet.
26147 			 * There is a slight risk here, in that, if we
26148 			 * have the forwarding path create an incomplete
26149 			 * IRE, then until the IRE is completed, any
26150 			 * transmitted IPsec packets will be dropped
26151 			 * instead of being queued waiting for resolution.
26152 			 *
26153 			 * But the likelihood of a forwarding packet and a wput
26154 			 * packet sending to the same dst at the same time
26155 			 * and there not yet be an ARP entry for it is small.
26156 			 * Furthermore, if this actually happens, it might
26157 			 * be likely that wput would generate multiple
26158 			 * packets (and forwarding would also have a train
26159 			 * of packets) for that destination. If this is
26160 			 * the case, some of them would have been dropped
26161 			 * anyway, since ARP only queues a few packets while
26162 			 * waiting for resolution
26163 			 *
26164 			 * NOTE: We should really call ip_xmit_v4,
26165 			 * and let it queue the packet and send the
26166 			 * ARP query and have ARP come back thus:
26167 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26168 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26169 			 * hw accel work. But it's too complex to get
26170 			 * the IPsec hw  acceleration approach to fit
26171 			 * well with ip_xmit_v4 doing ARP without
26172 			 * doing IPsec simplification. For now, we just
26173 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26174 			 * that we can continue with the send on the next
26175 			 * attempt.
26176 			 *
26177 			 * XXX THis should be revisited, when
26178 			 * the IPsec/IP interaction is cleaned up
26179 			 */
26180 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26181 			    " - dropping packet\n"));
26182 			freemsg(ipsec_mp);
26183 			/*
26184 			 * Call ip_xmit_v4() to trigger ARP query
26185 			 * in case the nce_state is ND_INITIAL
26186 			 */
26187 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
26188 			goto drop_pkt;
26189 		}
26190 
26191 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26192 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26193 		    mblk_t *, ipsec_mp);
26194 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26195 		    ipst->ips_ipv4firewall_physical_out,
26196 		    NULL, ire->ire_ipif->ipif_ill, ipha1, ipsec_mp, mp, ipst);
26197 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, ipsec_mp);
26198 		if (ipsec_mp == NULL)
26199 			goto drop_pkt;
26200 
26201 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26202 		pktxmit_state = ip_xmit_v4(mp, ire,
26203 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE);
26204 
26205 		if ((pktxmit_state ==  SEND_FAILED) ||
26206 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26207 
26208 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26209 drop_pkt:
26210 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26211 			    ipIfStatsOutDiscards);
26212 			if (ire_need_rele)
26213 				ire_refrele(ire);
26214 			if (ire1 != NULL) {
26215 				ire_refrele(ire1);
26216 				freemsg(next_mp);
26217 			}
26218 			goto done;
26219 		}
26220 
26221 		freeb(ipsec_mp);
26222 		if (ire_need_rele)
26223 			ire_refrele(ire);
26224 
26225 		if (ire1 != NULL) {
26226 			ire = ire1;
26227 			ire_need_rele = B_TRUE;
26228 			ASSERT(next_mp);
26229 			ipsec_mp = next_mp;
26230 			mp = ipsec_mp->b_cont;
26231 			ire1 = NULL;
26232 			next_mp = NULL;
26233 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26234 		} else {
26235 			multirt_send = B_FALSE;
26236 		}
26237 	} while (multirt_send);
26238 done:
26239 	if (ill != NULL && ill_need_rele)
26240 		ill_refrele(ill);
26241 	if (ipif != NULL)
26242 		ipif_refrele(ipif);
26243 }
26244 
26245 /*
26246  * Get the ill corresponding to the specified ire, and compare its
26247  * capabilities with the protocol and algorithms specified by the
26248  * the SA obtained from ipsec_out. If they match, annotate the
26249  * ipsec_out structure to indicate that the packet needs acceleration.
26250  *
26251  *
26252  * A packet is eligible for outbound hardware acceleration if the
26253  * following conditions are satisfied:
26254  *
26255  * 1. the packet will not be fragmented
26256  * 2. the provider supports the algorithm
26257  * 3. there is no pending control message being exchanged
26258  * 4. snoop is not attached
26259  * 5. the destination address is not a broadcast or multicast address.
26260  *
26261  * Rationale:
26262  *	- Hardware drivers do not support fragmentation with
26263  *	  the current interface.
26264  *	- snoop, multicast, and broadcast may result in exposure of
26265  *	  a cleartext datagram.
26266  * We check all five of these conditions here.
26267  *
26268  * XXX would like to nuke "ire_t *" parameter here; problem is that
26269  * IRE is only way to figure out if a v4 address is a broadcast and
26270  * thus ineligible for acceleration...
26271  */
26272 static void
26273 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26274 {
26275 	ipsec_out_t *io;
26276 	mblk_t *data_mp;
26277 	uint_t plen, overhead;
26278 	ip_stack_t	*ipst;
26279 
26280 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26281 		return;
26282 
26283 	if (ill == NULL)
26284 		return;
26285 	ipst = ill->ill_ipst;
26286 	/*
26287 	 * Destination address is a broadcast or multicast.  Punt.
26288 	 */
26289 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26290 	    IRE_LOCAL)))
26291 		return;
26292 
26293 	data_mp = ipsec_mp->b_cont;
26294 
26295 	if (ill->ill_isv6) {
26296 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26297 
26298 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26299 			return;
26300 
26301 		plen = ip6h->ip6_plen;
26302 	} else {
26303 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26304 
26305 		if (CLASSD(ipha->ipha_dst))
26306 			return;
26307 
26308 		plen = ipha->ipha_length;
26309 	}
26310 	/*
26311 	 * Is there a pending DLPI control message being exchanged
26312 	 * between IP/IPsec and the DLS Provider? If there is, it
26313 	 * could be a SADB update, and the state of the DLS Provider
26314 	 * SADB might not be in sync with the SADB maintained by
26315 	 * IPsec. To avoid dropping packets or using the wrong keying
26316 	 * material, we do not accelerate this packet.
26317 	 */
26318 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26319 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26320 		    "ill_dlpi_pending! don't accelerate packet\n"));
26321 		return;
26322 	}
26323 
26324 	/*
26325 	 * Is the Provider in promiscous mode? If it does, we don't
26326 	 * accelerate the packet since it will bounce back up to the
26327 	 * listeners in the clear.
26328 	 */
26329 	if (ill->ill_promisc_on_phys) {
26330 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26331 		    "ill in promiscous mode, don't accelerate packet\n"));
26332 		return;
26333 	}
26334 
26335 	/*
26336 	 * Will the packet require fragmentation?
26337 	 */
26338 
26339 	/*
26340 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26341 	 * as is used elsewhere.
26342 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26343 	 *	+ 2-byte trailer
26344 	 */
26345 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26346 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26347 
26348 	if ((plen + overhead) > ill->ill_max_mtu)
26349 		return;
26350 
26351 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26352 
26353 	/*
26354 	 * Can the ill accelerate this IPsec protocol and algorithm
26355 	 * specified by the SA?
26356 	 */
26357 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26358 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26359 		return;
26360 	}
26361 
26362 	/*
26363 	 * Tell AH or ESP that the outbound ill is capable of
26364 	 * accelerating this packet.
26365 	 */
26366 	io->ipsec_out_is_capab_ill = B_TRUE;
26367 }
26368 
26369 /*
26370  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26371  *
26372  * If this function returns B_TRUE, the requested SA's have been filled
26373  * into the ipsec_out_*_sa pointers.
26374  *
26375  * If the function returns B_FALSE, the packet has been "consumed", most
26376  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26377  *
26378  * The SA references created by the protocol-specific "select"
26379  * function will be released when the ipsec_mp is freed, thanks to the
26380  * ipsec_out_free destructor -- see spd.c.
26381  */
26382 static boolean_t
26383 ipsec_out_select_sa(mblk_t *ipsec_mp)
26384 {
26385 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26386 	ipsec_out_t *io;
26387 	ipsec_policy_t *pp;
26388 	ipsec_action_t *ap;
26389 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26390 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26391 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26392 
26393 	if (!io->ipsec_out_secure) {
26394 		/*
26395 		 * We came here by mistake.
26396 		 * Don't bother with ipsec processing
26397 		 * We should "discourage" this path in the future.
26398 		 */
26399 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26400 		return (B_FALSE);
26401 	}
26402 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26403 	ASSERT((io->ipsec_out_policy != NULL) ||
26404 	    (io->ipsec_out_act != NULL));
26405 
26406 	ASSERT(io->ipsec_out_failed == B_FALSE);
26407 
26408 	/*
26409 	 * IPsec processing has started.
26410 	 */
26411 	io->ipsec_out_proc_begin = B_TRUE;
26412 	ap = io->ipsec_out_act;
26413 	if (ap == NULL) {
26414 		pp = io->ipsec_out_policy;
26415 		ASSERT(pp != NULL);
26416 		ap = pp->ipsp_act;
26417 		ASSERT(ap != NULL);
26418 	}
26419 
26420 	/*
26421 	 * We have an action.  now, let's select SA's.
26422 	 * (In the future, we can cache this in the conn_t..)
26423 	 */
26424 	if (ap->ipa_want_esp) {
26425 		if (io->ipsec_out_esp_sa == NULL) {
26426 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26427 			    IPPROTO_ESP);
26428 		}
26429 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26430 	}
26431 
26432 	if (ap->ipa_want_ah) {
26433 		if (io->ipsec_out_ah_sa == NULL) {
26434 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26435 			    IPPROTO_AH);
26436 		}
26437 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26438 		/*
26439 		 * The ESP and AH processing order needs to be preserved
26440 		 * when both protocols are required (ESP should be applied
26441 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26442 		 * when both ESP and AH are required, and an AH ACQUIRE
26443 		 * is needed.
26444 		 */
26445 		if (ap->ipa_want_esp && need_ah_acquire)
26446 			need_esp_acquire = B_TRUE;
26447 	}
26448 
26449 	/*
26450 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26451 	 * Release SAs that got referenced, but will not be used until we
26452 	 * acquire _all_ of the SAs we need.
26453 	 */
26454 	if (need_ah_acquire || need_esp_acquire) {
26455 		if (io->ipsec_out_ah_sa != NULL) {
26456 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26457 			io->ipsec_out_ah_sa = NULL;
26458 		}
26459 		if (io->ipsec_out_esp_sa != NULL) {
26460 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26461 			io->ipsec_out_esp_sa = NULL;
26462 		}
26463 
26464 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26465 		return (B_FALSE);
26466 	}
26467 
26468 	return (B_TRUE);
26469 }
26470 
26471 /*
26472  * Process an IPSEC_OUT message and see what you can
26473  * do with it.
26474  * IPQoS Notes:
26475  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26476  * IPsec.
26477  * XXX would like to nuke ire_t.
26478  * XXX ill_index better be "real"
26479  */
26480 void
26481 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26482 {
26483 	ipsec_out_t *io;
26484 	ipsec_policy_t *pp;
26485 	ipsec_action_t *ap;
26486 	ipha_t *ipha;
26487 	ip6_t *ip6h;
26488 	mblk_t *mp;
26489 	ill_t *ill;
26490 	zoneid_t zoneid;
26491 	ipsec_status_t ipsec_rc;
26492 	boolean_t ill_need_rele = B_FALSE;
26493 	ip_stack_t	*ipst;
26494 	ipsec_stack_t	*ipss;
26495 
26496 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26497 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26498 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26499 	ipst = io->ipsec_out_ns->netstack_ip;
26500 	mp = ipsec_mp->b_cont;
26501 
26502 	/*
26503 	 * Initiate IPPF processing. We do it here to account for packets
26504 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26505 	 * We can check for ipsec_out_proc_begin even for such packets, as
26506 	 * they will always be false (asserted below).
26507 	 */
26508 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26509 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26510 		    io->ipsec_out_ill_index : ill_index);
26511 		if (mp == NULL) {
26512 			ip2dbg(("ipsec_out_process: packet dropped "\
26513 			    "during IPPF processing\n"));
26514 			freeb(ipsec_mp);
26515 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26516 			return;
26517 		}
26518 	}
26519 
26520 	if (!io->ipsec_out_secure) {
26521 		/*
26522 		 * We came here by mistake.
26523 		 * Don't bother with ipsec processing
26524 		 * Should "discourage" this path in the future.
26525 		 */
26526 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26527 		goto done;
26528 	}
26529 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26530 	ASSERT((io->ipsec_out_policy != NULL) ||
26531 	    (io->ipsec_out_act != NULL));
26532 	ASSERT(io->ipsec_out_failed == B_FALSE);
26533 
26534 	ipss = ipst->ips_netstack->netstack_ipsec;
26535 	if (!ipsec_loaded(ipss)) {
26536 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26537 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26538 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26539 		} else {
26540 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26541 		}
26542 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26543 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26544 		    &ipss->ipsec_dropper);
26545 		return;
26546 	}
26547 
26548 	/*
26549 	 * IPsec processing has started.
26550 	 */
26551 	io->ipsec_out_proc_begin = B_TRUE;
26552 	ap = io->ipsec_out_act;
26553 	if (ap == NULL) {
26554 		pp = io->ipsec_out_policy;
26555 		ASSERT(pp != NULL);
26556 		ap = pp->ipsp_act;
26557 		ASSERT(ap != NULL);
26558 	}
26559 
26560 	/*
26561 	 * Save the outbound ill index. When the packet comes back
26562 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26563 	 * before sending it the accelerated packet.
26564 	 */
26565 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26566 		int ifindex;
26567 		ill = ire_to_ill(ire);
26568 		ifindex = ill->ill_phyint->phyint_ifindex;
26569 		io->ipsec_out_capab_ill_index = ifindex;
26570 	}
26571 
26572 	/*
26573 	 * The order of processing is first insert a IP header if needed.
26574 	 * Then insert the ESP header and then the AH header.
26575 	 */
26576 	if ((io->ipsec_out_se_done == B_FALSE) &&
26577 	    (ap->ipa_want_se)) {
26578 		/*
26579 		 * First get the outer IP header before sending
26580 		 * it to ESP.
26581 		 */
26582 		ipha_t *oipha, *iipha;
26583 		mblk_t *outer_mp, *inner_mp;
26584 
26585 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26586 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26587 			    "ipsec_out_process: "
26588 			    "Self-Encapsulation failed: Out of memory\n");
26589 			freemsg(ipsec_mp);
26590 			if (ill != NULL) {
26591 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26592 			} else {
26593 				BUMP_MIB(&ipst->ips_ip_mib,
26594 				    ipIfStatsOutDiscards);
26595 			}
26596 			return;
26597 		}
26598 		inner_mp = ipsec_mp->b_cont;
26599 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26600 		oipha = (ipha_t *)outer_mp->b_rptr;
26601 		iipha = (ipha_t *)inner_mp->b_rptr;
26602 		*oipha = *iipha;
26603 		outer_mp->b_wptr += sizeof (ipha_t);
26604 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26605 		    sizeof (ipha_t));
26606 		oipha->ipha_protocol = IPPROTO_ENCAP;
26607 		oipha->ipha_version_and_hdr_length =
26608 		    IP_SIMPLE_HDR_VERSION;
26609 		oipha->ipha_hdr_checksum = 0;
26610 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26611 		outer_mp->b_cont = inner_mp;
26612 		ipsec_mp->b_cont = outer_mp;
26613 
26614 		io->ipsec_out_se_done = B_TRUE;
26615 		io->ipsec_out_tunnel = B_TRUE;
26616 	}
26617 
26618 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26619 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26620 	    !ipsec_out_select_sa(ipsec_mp))
26621 		return;
26622 
26623 	/*
26624 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26625 	 * to do the heavy lifting.
26626 	 */
26627 	zoneid = io->ipsec_out_zoneid;
26628 	ASSERT(zoneid != ALL_ZONES);
26629 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26630 		ASSERT(io->ipsec_out_esp_sa != NULL);
26631 		io->ipsec_out_esp_done = B_TRUE;
26632 		/*
26633 		 * Note that since hw accel can only apply one transform,
26634 		 * not two, we skip hw accel for ESP if we also have AH
26635 		 * This is an design limitation of the interface
26636 		 * which should be revisited.
26637 		 */
26638 		ASSERT(ire != NULL);
26639 		if (io->ipsec_out_ah_sa == NULL) {
26640 			ill = (ill_t *)ire->ire_stq->q_ptr;
26641 			ipsec_out_is_accelerated(ipsec_mp,
26642 			    io->ipsec_out_esp_sa, ill, ire);
26643 		}
26644 
26645 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26646 		switch (ipsec_rc) {
26647 		case IPSEC_STATUS_SUCCESS:
26648 			break;
26649 		case IPSEC_STATUS_FAILED:
26650 			if (ill != NULL) {
26651 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26652 			} else {
26653 				BUMP_MIB(&ipst->ips_ip_mib,
26654 				    ipIfStatsOutDiscards);
26655 			}
26656 			/* FALLTHRU */
26657 		case IPSEC_STATUS_PENDING:
26658 			return;
26659 		}
26660 	}
26661 
26662 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
26663 		ASSERT(io->ipsec_out_ah_sa != NULL);
26664 		io->ipsec_out_ah_done = B_TRUE;
26665 		if (ire == NULL) {
26666 			int idx = io->ipsec_out_capab_ill_index;
26667 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
26668 			    NULL, NULL, NULL, NULL, ipst);
26669 			ill_need_rele = B_TRUE;
26670 		} else {
26671 			ill = (ill_t *)ire->ire_stq->q_ptr;
26672 		}
26673 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
26674 		    ire);
26675 
26676 		ipsec_rc = io->ipsec_out_ah_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 			if (ill != NULL && ill_need_rele)
26690 				ill_refrele(ill);
26691 			return;
26692 		}
26693 	}
26694 	/*
26695 	 * We are done with IPsec processing. Send it over
26696 	 * the wire.
26697 	 */
26698 done:
26699 	mp = ipsec_mp->b_cont;
26700 	ipha = (ipha_t *)mp->b_rptr;
26701 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26702 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
26703 	} else {
26704 		ip6h = (ip6_t *)ipha;
26705 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
26706 	}
26707 	if (ill != NULL && ill_need_rele)
26708 		ill_refrele(ill);
26709 }
26710 
26711 /* ARGSUSED */
26712 void
26713 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
26714 {
26715 	opt_restart_t	*or;
26716 	int	err;
26717 	conn_t	*connp;
26718 
26719 	ASSERT(CONN_Q(q));
26720 	connp = Q_TO_CONN(q);
26721 
26722 	ASSERT(first_mp->b_datap->db_type == M_CTL);
26723 	or = (opt_restart_t *)first_mp->b_rptr;
26724 	/*
26725 	 * We don't need to pass any credentials here since this is just
26726 	 * a restart. The credentials are passed in when svr4_optcom_req
26727 	 * is called the first time (from ip_wput_nondata).
26728 	 */
26729 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
26730 		err = svr4_optcom_req(q, first_mp, NULL,
26731 		    &ip_opt_obj, B_FALSE);
26732 	} else {
26733 		ASSERT(or->or_type == T_OPTMGMT_REQ);
26734 		err = tpi_optcom_req(q, first_mp, NULL,
26735 		    &ip_opt_obj, B_FALSE);
26736 	}
26737 	if (err != EINPROGRESS) {
26738 		/* operation is done */
26739 		CONN_OPER_PENDING_DONE(connp);
26740 	}
26741 }
26742 
26743 /*
26744  * ioctls that go through a down/up sequence may need to wait for the down
26745  * to complete. This involves waiting for the ire and ipif refcnts to go down
26746  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
26747  */
26748 /* ARGSUSED */
26749 void
26750 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26751 {
26752 	struct iocblk *iocp;
26753 	mblk_t *mp1;
26754 	ip_ioctl_cmd_t *ipip;
26755 	int err;
26756 	sin_t	*sin;
26757 	struct lifreq *lifr;
26758 	struct ifreq *ifr;
26759 
26760 	iocp = (struct iocblk *)mp->b_rptr;
26761 	ASSERT(ipsq != NULL);
26762 	/* Existence of mp1 verified in ip_wput_nondata */
26763 	mp1 = mp->b_cont->b_cont;
26764 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26765 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
26766 		/*
26767 		 * Special case where ipsq_current_ipif is not set:
26768 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
26769 		 * ill could also have become part of a ipmp group in the
26770 		 * process, we are here as were not able to complete the
26771 		 * operation in ipif_set_values because we could not become
26772 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
26773 		 * will not be set so we need to set it.
26774 		 */
26775 		ill_t *ill = q->q_ptr;
26776 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
26777 	}
26778 	ASSERT(ipsq->ipsq_current_ipif != NULL);
26779 
26780 	if (ipip->ipi_cmd_type == IF_CMD) {
26781 		/* This a old style SIOC[GS]IF* command */
26782 		ifr = (struct ifreq *)mp1->b_rptr;
26783 		sin = (sin_t *)&ifr->ifr_addr;
26784 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
26785 		/* This a new style SIOC[GS]LIF* command */
26786 		lifr = (struct lifreq *)mp1->b_rptr;
26787 		sin = (sin_t *)&lifr->lifr_addr;
26788 	} else {
26789 		sin = NULL;
26790 	}
26791 
26792 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_current_ipif, sin, q, mp,
26793 	    ipip, mp1->b_rptr);
26794 
26795 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26796 }
26797 
26798 /*
26799  * ioctl processing
26800  *
26801  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
26802  * the ioctl command in the ioctl tables, determines the copyin data size
26803  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
26804  *
26805  * ioctl processing then continues when the M_IOCDATA makes its way down to
26806  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
26807  * associated 'conn' is refheld till the end of the ioctl and the general
26808  * ioctl processing function ip_process_ioctl() is called to extract the
26809  * arguments and process the ioctl.  To simplify extraction, ioctl commands
26810  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
26811  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
26812  * is used to extract the ioctl's arguments.
26813  *
26814  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
26815  * so goes thru the serialization primitive ipsq_try_enter. Then the
26816  * appropriate function to handle the ioctl is called based on the entry in
26817  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
26818  * which also refreleases the 'conn' that was refheld at the start of the
26819  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
26820  *
26821  * Many exclusive ioctls go thru an internal down up sequence as part of
26822  * the operation. For example an attempt to change the IP address of an
26823  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
26824  * does all the cleanup such as deleting all ires that use this address.
26825  * Then we need to wait till all references to the interface go away.
26826  */
26827 void
26828 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
26829 {
26830 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
26831 	ip_ioctl_cmd_t *ipip = arg;
26832 	ip_extract_func_t *extract_funcp;
26833 	cmd_info_t ci;
26834 	int err;
26835 	boolean_t entered_ipsq = B_FALSE;
26836 
26837 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
26838 
26839 	if (ipip == NULL)
26840 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26841 
26842 	/*
26843 	 * SIOCLIFADDIF needs to go thru a special path since the
26844 	 * ill may not exist yet. This happens in the case of lo0
26845 	 * which is created using this ioctl.
26846 	 */
26847 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
26848 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
26849 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26850 		return;
26851 	}
26852 
26853 	ci.ci_ipif = NULL;
26854 	if (ipip->ipi_cmd_type == MISC_CMD) {
26855 		/*
26856 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
26857 		 */
26858 		if (ipip->ipi_cmd == IF_UNITSEL) {
26859 			/* ioctl comes down the ill */
26860 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
26861 			ipif_refhold(ci.ci_ipif);
26862 		}
26863 		err = 0;
26864 		ci.ci_sin = NULL;
26865 		ci.ci_sin6 = NULL;
26866 		ci.ci_lifr = NULL;
26867 	} else {
26868 		switch (ipip->ipi_cmd_type) {
26869 		case IF_CMD:
26870 		case LIF_CMD:
26871 			extract_funcp = ip_extract_lifreq;
26872 			break;
26873 
26874 		case ARP_CMD:
26875 		case XARP_CMD:
26876 			extract_funcp = ip_extract_arpreq;
26877 			break;
26878 
26879 		case TUN_CMD:
26880 			extract_funcp = ip_extract_tunreq;
26881 			break;
26882 
26883 		case MSFILT_CMD:
26884 			extract_funcp = ip_extract_msfilter;
26885 			break;
26886 
26887 		default:
26888 			ASSERT(0);
26889 		}
26890 
26891 		err = (*extract_funcp)(q, mp, ipip, &ci, ip_process_ioctl);
26892 		if (err != 0) {
26893 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26894 			return;
26895 		}
26896 
26897 		/*
26898 		 * All of the extraction functions return a refheld ipif.
26899 		 */
26900 		ASSERT(ci.ci_ipif != NULL);
26901 	}
26902 
26903 	/*
26904 	 * If ipsq is non-null, we are already being called exclusively
26905 	 */
26906 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
26907 	if (!(ipip->ipi_flags & IPI_WR)) {
26908 		/*
26909 		 * A return value of EINPROGRESS means the ioctl is
26910 		 * either queued and waiting for some reason or has
26911 		 * already completed.
26912 		 */
26913 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
26914 		    ci.ci_lifr);
26915 		if (ci.ci_ipif != NULL)
26916 			ipif_refrele(ci.ci_ipif);
26917 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26918 		return;
26919 	}
26920 
26921 	ASSERT(ci.ci_ipif != NULL);
26922 
26923 	if (ipsq == NULL) {
26924 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
26925 		    ip_process_ioctl, NEW_OP, B_TRUE);
26926 		entered_ipsq = B_TRUE;
26927 	}
26928 	/*
26929 	 * Release the ipif so that ipif_down and friends that wait for
26930 	 * references to go away are not misled about the current ipif_refcnt
26931 	 * values. We are writer so we can access the ipif even after releasing
26932 	 * the ipif.
26933 	 */
26934 	ipif_refrele(ci.ci_ipif);
26935 	if (ipsq == NULL)
26936 		return;
26937 
26938 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
26939 
26940 	/*
26941 	 * For most set ioctls that come here, this serves as a single point
26942 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
26943 	 * be any new references to the ipif. This helps functions that go
26944 	 * through this path and end up trying to wait for the refcnts
26945 	 * associated with the ipif to go down to zero. Some exceptions are
26946 	 * Failover, Failback, and Groupname commands that operate on more than
26947 	 * just the ci.ci_ipif. These commands internally determine the
26948 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
26949 	 * flags on that set. Another exception is the Removeif command that
26950 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
26951 	 * ipif to operate on.
26952 	 */
26953 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
26954 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
26955 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
26956 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
26957 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
26958 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
26959 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
26960 
26961 	/*
26962 	 * A return value of EINPROGRESS means the ioctl is
26963 	 * either queued and waiting for some reason or has
26964 	 * already completed.
26965 	 */
26966 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
26967 
26968 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26969 
26970 	if (entered_ipsq)
26971 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
26972 }
26973 
26974 /*
26975  * Complete the ioctl. Typically ioctls use the mi package and need to
26976  * do mi_copyout/mi_copy_done.
26977  */
26978 void
26979 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
26980 {
26981 	conn_t	*connp = NULL;
26982 
26983 	if (err == EINPROGRESS)
26984 		return;
26985 
26986 	if (CONN_Q(q)) {
26987 		connp = Q_TO_CONN(q);
26988 		ASSERT(connp->conn_ref >= 2);
26989 	}
26990 
26991 	switch (mode) {
26992 	case COPYOUT:
26993 		if (err == 0)
26994 			mi_copyout(q, mp);
26995 		else
26996 			mi_copy_done(q, mp, err);
26997 		break;
26998 
26999 	case NO_COPYOUT:
27000 		mi_copy_done(q, mp, err);
27001 		break;
27002 
27003 	default:
27004 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
27005 		break;
27006 	}
27007 
27008 	/*
27009 	 * The refhold placed at the start of the ioctl is released here.
27010 	 */
27011 	if (connp != NULL)
27012 		CONN_OPER_PENDING_DONE(connp);
27013 
27014 	if (ipsq != NULL)
27015 		ipsq_current_finish(ipsq);
27016 }
27017 
27018 /*
27019  * This is called from ip_wput_nondata to resume a deferred TCP bind.
27020  */
27021 /* ARGSUSED */
27022 void
27023 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
27024 {
27025 	conn_t *connp = arg;
27026 	tcp_t	*tcp;
27027 
27028 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
27029 	tcp = connp->conn_tcp;
27030 
27031 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
27032 		freemsg(mp);
27033 	else
27034 		tcp_rput_other(tcp, mp);
27035 	CONN_OPER_PENDING_DONE(connp);
27036 }
27037 
27038 /* Called from ip_wput for all non data messages */
27039 /* ARGSUSED */
27040 void
27041 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27042 {
27043 	mblk_t		*mp1;
27044 	ire_t		*ire, *fake_ire;
27045 	ill_t		*ill;
27046 	struct iocblk	*iocp;
27047 	ip_ioctl_cmd_t	*ipip;
27048 	cred_t		*cr;
27049 	conn_t		*connp;
27050 	int		err;
27051 	nce_t		*nce;
27052 	ipif_t		*ipif;
27053 	ip_stack_t	*ipst;
27054 	char		*proto_str;
27055 
27056 	if (CONN_Q(q)) {
27057 		connp = Q_TO_CONN(q);
27058 		ipst = connp->conn_netstack->netstack_ip;
27059 	} else {
27060 		connp = NULL;
27061 		ipst = ILLQ_TO_IPST(q);
27062 	}
27063 
27064 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
27065 
27066 	switch (DB_TYPE(mp)) {
27067 	case M_IOCTL:
27068 		/*
27069 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
27070 		 * will arrange to copy in associated control structures.
27071 		 */
27072 		ip_sioctl_copyin_setup(q, mp);
27073 		return;
27074 	case M_IOCDATA:
27075 		/*
27076 		 * Ensure that this is associated with one of our trans-
27077 		 * parent ioctls.  If it's not ours, discard it if we're
27078 		 * running as a driver, or pass it on if we're a module.
27079 		 */
27080 		iocp = (struct iocblk *)mp->b_rptr;
27081 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27082 		if (ipip == NULL) {
27083 			if (q->q_next == NULL) {
27084 				goto nak;
27085 			} else {
27086 				putnext(q, mp);
27087 			}
27088 			return;
27089 		}
27090 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
27091 			/*
27092 			 * the ioctl is one we recognise, but is not
27093 			 * consumed by IP as a module, pass M_IOCDATA
27094 			 * for processing downstream, but only for
27095 			 * common Streams ioctls.
27096 			 */
27097 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27098 				putnext(q, mp);
27099 				return;
27100 			} else {
27101 				goto nak;
27102 			}
27103 		}
27104 
27105 		/* IOCTL continuation following copyin or copyout. */
27106 		if (mi_copy_state(q, mp, NULL) == -1) {
27107 			/*
27108 			 * The copy operation failed.  mi_copy_state already
27109 			 * cleaned up, so we're out of here.
27110 			 */
27111 			return;
27112 		}
27113 		/*
27114 		 * If we just completed a copy in, we become writer and
27115 		 * continue processing in ip_sioctl_copyin_done.  If it
27116 		 * was a copy out, we call mi_copyout again.  If there is
27117 		 * nothing more to copy out, it will complete the IOCTL.
27118 		 */
27119 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27120 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27121 				mi_copy_done(q, mp, EPROTO);
27122 				return;
27123 			}
27124 			/*
27125 			 * Check for cases that need more copying.  A return
27126 			 * value of 0 means a second copyin has been started,
27127 			 * so we return; a return value of 1 means no more
27128 			 * copying is needed, so we continue.
27129 			 */
27130 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
27131 			    MI_COPY_COUNT(mp) == 1) {
27132 				if (ip_copyin_msfilter(q, mp) == 0)
27133 					return;
27134 			}
27135 			/*
27136 			 * Refhold the conn, till the ioctl completes. This is
27137 			 * needed in case the ioctl ends up in the pending mp
27138 			 * list. Every mp in the ill_pending_mp list and
27139 			 * the ipsq_pending_mp must have a refhold on the conn
27140 			 * to resume processing. The refhold is released when
27141 			 * the ioctl completes. (normally or abnormally)
27142 			 * In all cases ip_ioctl_finish is called to finish
27143 			 * the ioctl.
27144 			 */
27145 			if (connp != NULL) {
27146 				/* This is not a reentry */
27147 				ASSERT(ipsq == NULL);
27148 				CONN_INC_REF(connp);
27149 			} else {
27150 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27151 					mi_copy_done(q, mp, EINVAL);
27152 					return;
27153 				}
27154 			}
27155 
27156 			ip_process_ioctl(ipsq, q, mp, ipip);
27157 
27158 		} else {
27159 			mi_copyout(q, mp);
27160 		}
27161 		return;
27162 nak:
27163 		iocp->ioc_error = EINVAL;
27164 		mp->b_datap->db_type = M_IOCNAK;
27165 		iocp->ioc_count = 0;
27166 		qreply(q, mp);
27167 		return;
27168 
27169 	case M_IOCNAK:
27170 		/*
27171 		 * The only way we could get here is if a resolver didn't like
27172 		 * an IOCTL we sent it.	 This shouldn't happen.
27173 		 */
27174 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27175 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27176 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27177 		freemsg(mp);
27178 		return;
27179 	case M_IOCACK:
27180 		/* /dev/ip shouldn't see this */
27181 		if (CONN_Q(q))
27182 			goto nak;
27183 
27184 		/* Finish socket ioctls passed through to ARP. */
27185 		ip_sioctl_iocack(q, mp);
27186 		return;
27187 	case M_FLUSH:
27188 		if (*mp->b_rptr & FLUSHW)
27189 			flushq(q, FLUSHALL);
27190 		if (q->q_next) {
27191 			putnext(q, mp);
27192 			return;
27193 		}
27194 		if (*mp->b_rptr & FLUSHR) {
27195 			*mp->b_rptr &= ~FLUSHW;
27196 			qreply(q, mp);
27197 			return;
27198 		}
27199 		freemsg(mp);
27200 		return;
27201 	case IRE_DB_REQ_TYPE:
27202 		if (connp == NULL) {
27203 			proto_str = "IRE_DB_REQ_TYPE";
27204 			goto protonak;
27205 		}
27206 		/* An Upper Level Protocol wants a copy of an IRE. */
27207 		ip_ire_req(q, mp);
27208 		return;
27209 	case M_CTL:
27210 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27211 			break;
27212 
27213 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27214 		    TUN_HELLO) {
27215 			ASSERT(connp != NULL);
27216 			connp->conn_flags |= IPCL_IPTUN;
27217 			freeb(mp);
27218 			return;
27219 		}
27220 
27221 		/* M_CTL messages are used by ARP to tell us things. */
27222 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27223 			break;
27224 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27225 		case AR_ENTRY_SQUERY:
27226 			ip_wput_ctl(q, mp);
27227 			return;
27228 		case AR_CLIENT_NOTIFY:
27229 			ip_arp_news(q, mp);
27230 			return;
27231 		case AR_DLPIOP_DONE:
27232 			ASSERT(q->q_next != NULL);
27233 			ill = (ill_t *)q->q_ptr;
27234 			/* qwriter_ip releases the refhold */
27235 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27236 			ill_refhold(ill);
27237 			qwriter_ip(ill, q, mp, ip_arp_done, CUR_OP, B_FALSE);
27238 			return;
27239 		case AR_ARP_CLOSING:
27240 			/*
27241 			 * ARP (above us) is closing. If no ARP bringup is
27242 			 * currently pending, ack the message so that ARP
27243 			 * can complete its close. Also mark ill_arp_closing
27244 			 * so that new ARP bringups will fail. If any
27245 			 * ARP bringup is currently in progress, we will
27246 			 * ack this when the current ARP bringup completes.
27247 			 */
27248 			ASSERT(q->q_next != NULL);
27249 			ill = (ill_t *)q->q_ptr;
27250 			mutex_enter(&ill->ill_lock);
27251 			ill->ill_arp_closing = 1;
27252 			if (!ill->ill_arp_bringup_pending) {
27253 				mutex_exit(&ill->ill_lock);
27254 				qreply(q, mp);
27255 			} else {
27256 				mutex_exit(&ill->ill_lock);
27257 				freemsg(mp);
27258 			}
27259 			return;
27260 		case AR_ARP_EXTEND:
27261 			/*
27262 			 * The ARP module above us is capable of duplicate
27263 			 * address detection.  Old ATM drivers will not send
27264 			 * this message.
27265 			 */
27266 			ASSERT(q->q_next != NULL);
27267 			ill = (ill_t *)q->q_ptr;
27268 			ill->ill_arp_extend = B_TRUE;
27269 			freemsg(mp);
27270 			return;
27271 		default:
27272 			break;
27273 		}
27274 		break;
27275 	case M_PROTO:
27276 	case M_PCPROTO:
27277 		/*
27278 		 * The only PROTO messages we expect are ULP binds and
27279 		 * copies of option negotiation acknowledgements.
27280 		 */
27281 		switch (((union T_primitives *)mp->b_rptr)->type) {
27282 		case O_T_BIND_REQ:
27283 		case T_BIND_REQ: {
27284 			/* Request can get queued in bind */
27285 			if (connp == NULL) {
27286 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27287 				goto protonak;
27288 			}
27289 			/*
27290 			 * The transports except SCTP call ip_bind_{v4,v6}()
27291 			 * directly instead of a a putnext. SCTP doesn't
27292 			 * generate any T_BIND_REQ since it has its own
27293 			 * fanout data structures. However, ESP and AH
27294 			 * come in for regular binds; all other cases are
27295 			 * bind retries.
27296 			 */
27297 			ASSERT(!IPCL_IS_SCTP(connp));
27298 
27299 			/* Don't increment refcnt if this is a re-entry */
27300 			if (ipsq == NULL)
27301 				CONN_INC_REF(connp);
27302 
27303 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27304 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27305 			if (mp == NULL)
27306 				return;
27307 			if (IPCL_IS_TCP(connp)) {
27308 				/*
27309 				 * In the case of TCP endpoint we
27310 				 * come here only for bind retries
27311 				 */
27312 				ASSERT(ipsq != NULL);
27313 				CONN_INC_REF(connp);
27314 				squeue_fill(connp->conn_sqp, mp,
27315 				    ip_resume_tcp_bind, connp,
27316 				    SQTAG_BIND_RETRY);
27317 			} else if (IPCL_IS_UDP(connp)) {
27318 				/*
27319 				 * In the case of UDP endpoint we
27320 				 * come here only for bind retries
27321 				 */
27322 				ASSERT(ipsq != NULL);
27323 				udp_resume_bind(connp, mp);
27324 			} else if (IPCL_IS_RAWIP(connp)) {
27325 				/*
27326 				 * In the case of RAWIP endpoint we
27327 				 * come here only for bind retries
27328 				 */
27329 				ASSERT(ipsq != NULL);
27330 				rawip_resume_bind(connp, mp);
27331 			} else {
27332 				/* The case of AH and ESP */
27333 				qreply(q, mp);
27334 				CONN_OPER_PENDING_DONE(connp);
27335 			}
27336 			return;
27337 		}
27338 		case T_SVR4_OPTMGMT_REQ:
27339 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27340 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27341 
27342 			if (connp == NULL) {
27343 				proto_str = "T_SVR4_OPTMGMT_REQ";
27344 				goto protonak;
27345 			}
27346 
27347 			if (!snmpcom_req(q, mp, ip_snmp_set,
27348 			    ip_snmp_get, cr)) {
27349 				/*
27350 				 * Call svr4_optcom_req so that it can
27351 				 * generate the ack. We don't come here
27352 				 * if this operation is being restarted.
27353 				 * ip_restart_optmgmt will drop the conn ref.
27354 				 * In the case of ipsec option after the ipsec
27355 				 * load is complete conn_restart_ipsec_waiter
27356 				 * drops the conn ref.
27357 				 */
27358 				ASSERT(ipsq == NULL);
27359 				CONN_INC_REF(connp);
27360 				if (ip_check_for_ipsec_opt(q, mp))
27361 					return;
27362 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj,
27363 				    B_FALSE);
27364 				if (err != EINPROGRESS) {
27365 					/* Operation is done */
27366 					CONN_OPER_PENDING_DONE(connp);
27367 				}
27368 			}
27369 			return;
27370 		case T_OPTMGMT_REQ:
27371 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27372 			/*
27373 			 * Note: No snmpcom_req support through new
27374 			 * T_OPTMGMT_REQ.
27375 			 * Call tpi_optcom_req so that it can
27376 			 * generate the ack.
27377 			 */
27378 			if (connp == NULL) {
27379 				proto_str = "T_OPTMGMT_REQ";
27380 				goto protonak;
27381 			}
27382 
27383 			ASSERT(ipsq == NULL);
27384 			/*
27385 			 * We don't come here for restart. ip_restart_optmgmt
27386 			 * will drop the conn ref. In the case of ipsec option
27387 			 * after the ipsec load is complete
27388 			 * conn_restart_ipsec_waiter drops the conn ref.
27389 			 */
27390 			CONN_INC_REF(connp);
27391 			if (ip_check_for_ipsec_opt(q, mp))
27392 				return;
27393 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj, B_FALSE);
27394 			if (err != EINPROGRESS) {
27395 				/* Operation is done */
27396 				CONN_OPER_PENDING_DONE(connp);
27397 			}
27398 			return;
27399 		case T_UNBIND_REQ:
27400 			if (connp == NULL) {
27401 				proto_str = "T_UNBIND_REQ";
27402 				goto protonak;
27403 			}
27404 			mp = ip_unbind(q, mp);
27405 			qreply(q, mp);
27406 			return;
27407 		default:
27408 			/*
27409 			 * Have to drop any DLPI messages coming down from
27410 			 * arp (such as an info_req which would cause ip
27411 			 * to receive an extra info_ack if it was passed
27412 			 * through.
27413 			 */
27414 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27415 			    (int)*(uint_t *)mp->b_rptr));
27416 			freemsg(mp);
27417 			return;
27418 		}
27419 		/* NOTREACHED */
27420 	case IRE_DB_TYPE: {
27421 		nce_t		*nce;
27422 		ill_t		*ill;
27423 		in6_addr_t	gw_addr_v6;
27424 
27425 
27426 		/*
27427 		 * This is a response back from a resolver.  It
27428 		 * consists of a message chain containing:
27429 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27430 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27431 		 * The LL_HDR_MBLK is the DLPI header to use to get
27432 		 * the attached packet, and subsequent ones for the
27433 		 * same destination, transmitted.
27434 		 */
27435 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27436 			break;
27437 		/*
27438 		 * First, check to make sure the resolution succeeded.
27439 		 * If it failed, the second mblk will be empty.
27440 		 * If it is, free the chain, dropping the packet.
27441 		 * (We must ire_delete the ire; that frees the ire mblk)
27442 		 * We're doing this now to support PVCs for ATM; it's
27443 		 * a partial xresolv implementation. When we fully implement
27444 		 * xresolv interfaces, instead of freeing everything here
27445 		 * we'll initiate neighbor discovery.
27446 		 *
27447 		 * For v4 (ARP and other external resolvers) the resolver
27448 		 * frees the message, so no check is needed. This check
27449 		 * is required, though, for a full xresolve implementation.
27450 		 * Including this code here now both shows how external
27451 		 * resolvers can NACK a resolution request using an
27452 		 * existing design that has no specific provisions for NACKs,
27453 		 * and also takes into account that the current non-ARP
27454 		 * external resolver has been coded to use this method of
27455 		 * NACKing for all IPv6 (xresolv) cases,
27456 		 * whether our xresolv implementation is complete or not.
27457 		 *
27458 		 */
27459 		ire = (ire_t *)mp->b_rptr;
27460 		ill = ire_to_ill(ire);
27461 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27462 		if (mp1->b_rptr == mp1->b_wptr) {
27463 			if (ire->ire_ipversion == IPV6_VERSION) {
27464 				/*
27465 				 * XRESOLV interface.
27466 				 */
27467 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27468 				mutex_enter(&ire->ire_lock);
27469 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27470 				mutex_exit(&ire->ire_lock);
27471 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27472 					nce = ndp_lookup_v6(ill,
27473 					    &ire->ire_addr_v6, B_FALSE);
27474 				} else {
27475 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
27476 					    B_FALSE);
27477 				}
27478 				if (nce != NULL) {
27479 					nce_resolv_failed(nce);
27480 					ndp_delete(nce);
27481 					NCE_REFRELE(nce);
27482 				}
27483 			}
27484 			mp->b_cont = NULL;
27485 			freemsg(mp1);		/* frees the pkt as well */
27486 			ASSERT(ire->ire_nce == NULL);
27487 			ire_delete((ire_t *)mp->b_rptr);
27488 			return;
27489 		}
27490 
27491 		/*
27492 		 * Split them into IRE_MBLK and pkt and feed it into
27493 		 * ire_add_then_send. Then in ire_add_then_send
27494 		 * the IRE will be added, and then the packet will be
27495 		 * run back through ip_wput. This time it will make
27496 		 * it to the wire.
27497 		 */
27498 		mp->b_cont = NULL;
27499 		mp = mp1->b_cont;		/* now, mp points to pkt */
27500 		mp1->b_cont = NULL;
27501 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27502 		if (ire->ire_ipversion == IPV6_VERSION) {
27503 			/*
27504 			 * XRESOLV interface. Find the nce and put a copy
27505 			 * of the dl_unitdata_req in nce_res_mp
27506 			 */
27507 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27508 			mutex_enter(&ire->ire_lock);
27509 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27510 			mutex_exit(&ire->ire_lock);
27511 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27512 				nce = ndp_lookup_v6(ill, &ire->ire_addr_v6,
27513 				    B_FALSE);
27514 			} else {
27515 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
27516 			}
27517 			if (nce != NULL) {
27518 				/*
27519 				 * We have to protect nce_res_mp here
27520 				 * from being accessed by other threads
27521 				 * while we change the mblk pointer.
27522 				 * Other functions will also lock the nce when
27523 				 * accessing nce_res_mp.
27524 				 *
27525 				 * The reason we change the mblk pointer
27526 				 * here rather than copying the resolved address
27527 				 * into the template is that, unlike with
27528 				 * ethernet, we have no guarantee that the
27529 				 * resolved address length will be
27530 				 * smaller than or equal to the lla length
27531 				 * with which the template was allocated,
27532 				 * (for ethernet, they're equal)
27533 				 * so we have to use the actual resolved
27534 				 * address mblk - which holds the real
27535 				 * dl_unitdata_req with the resolved address.
27536 				 *
27537 				 * Doing this is the same behavior as was
27538 				 * previously used in the v4 ARP case.
27539 				 */
27540 				mutex_enter(&nce->nce_lock);
27541 				if (nce->nce_res_mp != NULL)
27542 					freemsg(nce->nce_res_mp);
27543 				nce->nce_res_mp = mp1;
27544 				mutex_exit(&nce->nce_lock);
27545 				/*
27546 				 * We do a fastpath probe here because
27547 				 * we have resolved the address without
27548 				 * using Neighbor Discovery.
27549 				 * In the non-XRESOLV v6 case, the fastpath
27550 				 * probe is done right after neighbor
27551 				 * discovery completes.
27552 				 */
27553 				if (nce->nce_res_mp != NULL) {
27554 					int res;
27555 					nce_fastpath_list_add(nce);
27556 					res = ill_fastpath_probe(ill,
27557 					    nce->nce_res_mp);
27558 					if (res != 0 && res != EAGAIN)
27559 						nce_fastpath_list_delete(nce);
27560 				}
27561 
27562 				ire_add_then_send(q, ire, mp);
27563 				/*
27564 				 * Now we have to clean out any packets
27565 				 * that may have been queued on the nce
27566 				 * while it was waiting for address resolution
27567 				 * to complete.
27568 				 */
27569 				mutex_enter(&nce->nce_lock);
27570 				mp1 = nce->nce_qd_mp;
27571 				nce->nce_qd_mp = NULL;
27572 				mutex_exit(&nce->nce_lock);
27573 				while (mp1 != NULL) {
27574 					mblk_t *nxt_mp;
27575 					queue_t *fwdq = NULL;
27576 					ill_t   *inbound_ill;
27577 					uint_t ifindex;
27578 
27579 					nxt_mp = mp1->b_next;
27580 					mp1->b_next = NULL;
27581 					/*
27582 					 * Retrieve ifindex stored in
27583 					 * ip_rput_data_v6()
27584 					 */
27585 					ifindex =
27586 					    (uint_t)(uintptr_t)mp1->b_prev;
27587 					inbound_ill =
27588 					    ill_lookup_on_ifindex(ifindex,
27589 					    B_TRUE, NULL, NULL, NULL,
27590 					    NULL, ipst);
27591 					mp1->b_prev = NULL;
27592 					if (inbound_ill != NULL)
27593 						fwdq = inbound_ill->ill_rq;
27594 
27595 					if (fwdq != NULL) {
27596 						put(fwdq, mp1);
27597 						ill_refrele(inbound_ill);
27598 					} else
27599 						put(WR(ill->ill_rq), mp1);
27600 					mp1 = nxt_mp;
27601 				}
27602 				NCE_REFRELE(nce);
27603 			} else {	/* nce is NULL; clean up */
27604 				ire_delete(ire);
27605 				freemsg(mp);
27606 				freemsg(mp1);
27607 				return;
27608 			}
27609 		} else {
27610 			nce_t *arpce;
27611 			/*
27612 			 * Link layer resolution succeeded. Recompute the
27613 			 * ire_nce.
27614 			 */
27615 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27616 			if ((arpce = ndp_lookup_v4(ill,
27617 			    (ire->ire_gateway_addr != INADDR_ANY ?
27618 			    &ire->ire_gateway_addr : &ire->ire_addr),
27619 			    B_FALSE)) == NULL) {
27620 				freeb(ire->ire_mp);
27621 				freeb(mp1);
27622 				freemsg(mp);
27623 				return;
27624 			}
27625 			mutex_enter(&arpce->nce_lock);
27626 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27627 			if (arpce->nce_state == ND_REACHABLE) {
27628 				/*
27629 				 * Someone resolved this before us;
27630 				 * cleanup the res_mp. Since ire has
27631 				 * not been added yet, the call to ire_add_v4
27632 				 * from ire_add_then_send (when a dup is
27633 				 * detected) will clean up the ire.
27634 				 */
27635 				freeb(mp1);
27636 			} else {
27637 				ASSERT(arpce->nce_res_mp == NULL);
27638 				arpce->nce_res_mp = mp1;
27639 				arpce->nce_state = ND_REACHABLE;
27640 			}
27641 			mutex_exit(&arpce->nce_lock);
27642 			if (ire->ire_marks & IRE_MARK_NOADD) {
27643 				/*
27644 				 * this ire will not be added to the ire
27645 				 * cache table, so we can set the ire_nce
27646 				 * here, as there are no atomicity constraints.
27647 				 */
27648 				ire->ire_nce = arpce;
27649 				/*
27650 				 * We are associating this nce with the ire
27651 				 * so change the nce ref taken in
27652 				 * ndp_lookup_v4() from
27653 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
27654 				 */
27655 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
27656 			} else {
27657 				NCE_REFRELE(arpce);
27658 			}
27659 			ire_add_then_send(q, ire, mp);
27660 		}
27661 		return;	/* All is well, the packet has been sent. */
27662 	}
27663 	case IRE_ARPRESOLVE_TYPE: {
27664 
27665 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
27666 			break;
27667 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27668 		mp->b_cont = NULL;
27669 		/*
27670 		 * First, check to make sure the resolution succeeded.
27671 		 * If it failed, the second mblk will be empty.
27672 		 */
27673 		if (mp1->b_rptr == mp1->b_wptr) {
27674 			/* cleanup  the incomplete ire, free queued packets */
27675 			freemsg(mp); /* fake ire */
27676 			freeb(mp1);  /* dl_unitdata response */
27677 			return;
27678 		}
27679 
27680 		/*
27681 		 * update any incomplete nce_t found. we lookup the ctable
27682 		 * and find the nce from the ire->ire_nce because we need
27683 		 * to pass the ire to ip_xmit_v4 later, and can find both
27684 		 * ire and nce in one lookup from the ctable.
27685 		 */
27686 		fake_ire = (ire_t *)mp->b_rptr;
27687 		/*
27688 		 * By the time we come back here from ARP
27689 		 * the logical outgoing interface  of the incomplete ire
27690 		 * we added in ire_forward could have disappeared,
27691 		 * causing the incomplete ire to also have
27692 		 * dissapeared. So we need to retreive the
27693 		 * proper ipif for the ire  before looking
27694 		 * in ctable;  do the ctablelookup based on ire_ipif_seqid
27695 		 */
27696 		ill = q->q_ptr;
27697 
27698 		/* Get the outgoing ipif */
27699 		mutex_enter(&ill->ill_lock);
27700 		if (ill->ill_state_flags & ILL_CONDEMNED) {
27701 			mutex_exit(&ill->ill_lock);
27702 			freemsg(mp); /* fake ire */
27703 			freeb(mp1);  /* dl_unitdata response */
27704 			return;
27705 		}
27706 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27707 
27708 		if (ipif == NULL) {
27709 			mutex_exit(&ill->ill_lock);
27710 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27711 			freemsg(mp);
27712 			freeb(mp1);
27713 			return;
27714 		}
27715 		ipif_refhold_locked(ipif);
27716 		mutex_exit(&ill->ill_lock);
27717 		ire = ire_ctable_lookup(fake_ire->ire_addr,
27718 		    fake_ire->ire_gateway_addr, IRE_CACHE,
27719 		    ipif, fake_ire->ire_zoneid, NULL,
27720 		    (MATCH_IRE_GW|MATCH_IRE_IPIF|MATCH_IRE_ZONEONLY), ipst);
27721 		ipif_refrele(ipif);
27722 		if (ire == NULL) {
27723 			/*
27724 			 * no ire was found; check if there is an nce
27725 			 * for this lookup; if it has no ire's pointing at it
27726 			 * cleanup.
27727 			 */
27728 			if ((nce = ndp_lookup_v4(ill,
27729 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
27730 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
27731 			    B_FALSE)) != NULL) {
27732 				/*
27733 				 * cleanup:
27734 				 * We check for refcnt 2 (one for the nce
27735 				 * hash list + 1 for the ref taken by
27736 				 * ndp_lookup_v4) to check that there are
27737 				 * no ire's pointing at the nce.
27738 				 */
27739 				if (nce->nce_refcnt == 2)
27740 					ndp_delete(nce);
27741 				NCE_REFRELE(nce);
27742 			}
27743 			freeb(mp1);  /* dl_unitdata response */
27744 			freemsg(mp); /* fake ire */
27745 			return;
27746 		}
27747 		nce = ire->ire_nce;
27748 		DTRACE_PROBE2(ire__arpresolve__type,
27749 		    ire_t *, ire, nce_t *, nce);
27750 		ASSERT(nce->nce_state != ND_INITIAL);
27751 		mutex_enter(&nce->nce_lock);
27752 		nce->nce_last = TICK_TO_MSEC(lbolt64);
27753 		if (nce->nce_state == ND_REACHABLE) {
27754 			/*
27755 			 * Someone resolved this before us;
27756 			 * our response is not needed any more.
27757 			 */
27758 			mutex_exit(&nce->nce_lock);
27759 			freeb(mp1);  /* dl_unitdata response */
27760 		} else {
27761 			ASSERT(nce->nce_res_mp == NULL);
27762 			nce->nce_res_mp = mp1;
27763 			nce->nce_state = ND_REACHABLE;
27764 			mutex_exit(&nce->nce_lock);
27765 			nce_fastpath(nce);
27766 		}
27767 		/*
27768 		 * The cached nce_t has been updated to be reachable;
27769 		 * Clear the IRE_MARK_UNCACHED flag and free the fake_ire.
27770 		 */
27771 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
27772 		freemsg(mp);
27773 		/*
27774 		 * send out queued packets.
27775 		 */
27776 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
27777 
27778 		IRE_REFRELE(ire);
27779 		return;
27780 	}
27781 	default:
27782 		break;
27783 	}
27784 	if (q->q_next) {
27785 		putnext(q, mp);
27786 	} else
27787 		freemsg(mp);
27788 	return;
27789 
27790 protonak:
27791 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
27792 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
27793 		qreply(q, mp);
27794 }
27795 
27796 /*
27797  * Process IP options in an outbound packet.  Modify the destination if there
27798  * is a source route option.
27799  * Returns non-zero if something fails in which case an ICMP error has been
27800  * sent and mp freed.
27801  */
27802 static int
27803 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
27804     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
27805 {
27806 	ipoptp_t	opts;
27807 	uchar_t		*opt;
27808 	uint8_t		optval;
27809 	uint8_t		optlen;
27810 	ipaddr_t	dst;
27811 	intptr_t	code = 0;
27812 	mblk_t		*mp;
27813 	ire_t		*ire = NULL;
27814 
27815 	ip2dbg(("ip_wput_options\n"));
27816 	mp = ipsec_mp;
27817 	if (mctl_present) {
27818 		mp = ipsec_mp->b_cont;
27819 	}
27820 
27821 	dst = ipha->ipha_dst;
27822 	for (optval = ipoptp_first(&opts, ipha);
27823 	    optval != IPOPT_EOL;
27824 	    optval = ipoptp_next(&opts)) {
27825 		opt = opts.ipoptp_cur;
27826 		optlen = opts.ipoptp_len;
27827 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
27828 		    optval, optlen));
27829 		switch (optval) {
27830 			uint32_t off;
27831 		case IPOPT_SSRR:
27832 		case IPOPT_LSRR:
27833 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27834 				ip1dbg((
27835 				    "ip_wput_options: bad option offset\n"));
27836 				code = (char *)&opt[IPOPT_OLEN] -
27837 				    (char *)ipha;
27838 				goto param_prob;
27839 			}
27840 			off = opt[IPOPT_OFFSET];
27841 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
27842 			    ntohl(dst)));
27843 			/*
27844 			 * For strict: verify that dst is directly
27845 			 * reachable.
27846 			 */
27847 			if (optval == IPOPT_SSRR) {
27848 				ire = ire_ftable_lookup(dst, 0, 0,
27849 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
27850 				    MBLK_GETLABEL(mp),
27851 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
27852 				if (ire == NULL) {
27853 					ip1dbg(("ip_wput_options: SSRR not"
27854 					    " directly reachable: 0x%x\n",
27855 					    ntohl(dst)));
27856 					goto bad_src_route;
27857 				}
27858 				ire_refrele(ire);
27859 			}
27860 			break;
27861 		case IPOPT_RR:
27862 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27863 				ip1dbg((
27864 				    "ip_wput_options: bad option offset\n"));
27865 				code = (char *)&opt[IPOPT_OLEN] -
27866 				    (char *)ipha;
27867 				goto param_prob;
27868 			}
27869 			break;
27870 		case IPOPT_TS:
27871 			/*
27872 			 * Verify that length >=5 and that there is either
27873 			 * room for another timestamp or that the overflow
27874 			 * counter is not maxed out.
27875 			 */
27876 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
27877 			if (optlen < IPOPT_MINLEN_IT) {
27878 				goto param_prob;
27879 			}
27880 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27881 				ip1dbg((
27882 				    "ip_wput_options: bad option offset\n"));
27883 				code = (char *)&opt[IPOPT_OFFSET] -
27884 				    (char *)ipha;
27885 				goto param_prob;
27886 			}
27887 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
27888 			case IPOPT_TS_TSONLY:
27889 				off = IPOPT_TS_TIMELEN;
27890 				break;
27891 			case IPOPT_TS_TSANDADDR:
27892 			case IPOPT_TS_PRESPEC:
27893 			case IPOPT_TS_PRESPEC_RFC791:
27894 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
27895 				break;
27896 			default:
27897 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
27898 				    (char *)ipha;
27899 				goto param_prob;
27900 			}
27901 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
27902 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
27903 				/*
27904 				 * No room and the overflow counter is 15
27905 				 * already.
27906 				 */
27907 				goto param_prob;
27908 			}
27909 			break;
27910 		}
27911 	}
27912 
27913 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
27914 		return (0);
27915 
27916 	ip1dbg(("ip_wput_options: error processing IP options."));
27917 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
27918 
27919 param_prob:
27920 	/*
27921 	 * Since ip_wput() isn't close to finished, we fill
27922 	 * in enough of the header for credible error reporting.
27923 	 */
27924 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
27925 		/* Failed */
27926 		freemsg(ipsec_mp);
27927 		return (-1);
27928 	}
27929 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
27930 	return (-1);
27931 
27932 bad_src_route:
27933 	/*
27934 	 * Since ip_wput() isn't close to finished, we fill
27935 	 * in enough of the header for credible error reporting.
27936 	 */
27937 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
27938 		/* Failed */
27939 		freemsg(ipsec_mp);
27940 		return (-1);
27941 	}
27942 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
27943 	return (-1);
27944 }
27945 
27946 /*
27947  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
27948  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
27949  * thru /etc/system.
27950  */
27951 #define	CONN_MAXDRAINCNT	64
27952 
27953 static void
27954 conn_drain_init(ip_stack_t *ipst)
27955 {
27956 	int i;
27957 
27958 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
27959 
27960 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
27961 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
27962 		/*
27963 		 * Default value of the number of drainers is the
27964 		 * number of cpus, subject to maximum of 8 drainers.
27965 		 */
27966 		if (boot_max_ncpus != -1)
27967 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
27968 		else
27969 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
27970 	}
27971 
27972 	ipst->ips_conn_drain_list = kmem_zalloc(ipst->ips_conn_drain_list_cnt *
27973 	    sizeof (idl_t), KM_SLEEP);
27974 
27975 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
27976 		mutex_init(&ipst->ips_conn_drain_list[i].idl_lock, NULL,
27977 		    MUTEX_DEFAULT, NULL);
27978 	}
27979 }
27980 
27981 static void
27982 conn_drain_fini(ip_stack_t *ipst)
27983 {
27984 	int i;
27985 
27986 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++)
27987 		mutex_destroy(&ipst->ips_conn_drain_list[i].idl_lock);
27988 	kmem_free(ipst->ips_conn_drain_list,
27989 	    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
27990 	ipst->ips_conn_drain_list = NULL;
27991 }
27992 
27993 /*
27994  * Note: For an overview of how flowcontrol is handled in IP please see the
27995  * IP Flowcontrol notes at the top of this file.
27996  *
27997  * Flow control has blocked us from proceeding. Insert the given conn in one
27998  * of the conn drain lists. These conn wq's will be qenabled later on when
27999  * STREAMS flow control does a backenable. conn_walk_drain will enable
28000  * the first conn in each of these drain lists. Each of these qenabled conns
28001  * in turn enables the next in the list, after it runs, or when it closes,
28002  * thus sustaining the drain process.
28003  *
28004  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
28005  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
28006  * running at any time, on a given conn, since there can be only 1 service proc
28007  * running on a queue at any time.
28008  */
28009 void
28010 conn_drain_insert(conn_t *connp)
28011 {
28012 	idl_t	*idl;
28013 	uint_t	index;
28014 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28015 
28016 	mutex_enter(&connp->conn_lock);
28017 	if (connp->conn_state_flags & CONN_CLOSING) {
28018 		/*
28019 		 * The conn is closing as a result of which CONN_CLOSING
28020 		 * is set. Return.
28021 		 */
28022 		mutex_exit(&connp->conn_lock);
28023 		return;
28024 	} else if (connp->conn_idl == NULL) {
28025 		/*
28026 		 * Assign the next drain list round robin. We dont' use
28027 		 * a lock, and thus it may not be strictly round robin.
28028 		 * Atomicity of load/stores is enough to make sure that
28029 		 * conn_drain_list_index is always within bounds.
28030 		 */
28031 		index = ipst->ips_conn_drain_list_index;
28032 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
28033 		connp->conn_idl = &ipst->ips_conn_drain_list[index];
28034 		index++;
28035 		if (index == ipst->ips_conn_drain_list_cnt)
28036 			index = 0;
28037 		ipst->ips_conn_drain_list_index = index;
28038 	}
28039 	mutex_exit(&connp->conn_lock);
28040 
28041 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28042 	if ((connp->conn_drain_prev != NULL) ||
28043 	    (connp->conn_state_flags & CONN_CLOSING)) {
28044 		/*
28045 		 * The conn is already in the drain list, OR
28046 		 * the conn is closing. We need to check again for
28047 		 * the closing case again since close can happen
28048 		 * after we drop the conn_lock, and before we
28049 		 * acquire the CONN_DRAIN_LIST_LOCK.
28050 		 */
28051 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28052 		return;
28053 	} else {
28054 		idl = connp->conn_idl;
28055 	}
28056 
28057 	/*
28058 	 * The conn is not in the drain list. Insert it at the
28059 	 * tail of the drain list. The drain list is circular
28060 	 * and doubly linked. idl_conn points to the 1st element
28061 	 * in the list.
28062 	 */
28063 	if (idl->idl_conn == NULL) {
28064 		idl->idl_conn = connp;
28065 		connp->conn_drain_next = connp;
28066 		connp->conn_drain_prev = connp;
28067 	} else {
28068 		conn_t *head = idl->idl_conn;
28069 
28070 		connp->conn_drain_next = head;
28071 		connp->conn_drain_prev = head->conn_drain_prev;
28072 		head->conn_drain_prev->conn_drain_next = connp;
28073 		head->conn_drain_prev = connp;
28074 	}
28075 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28076 }
28077 
28078 /*
28079  * This conn is closing, and we are called from ip_close. OR
28080  * This conn has been serviced by ip_wsrv, and we need to do the tail
28081  * processing.
28082  * If this conn is part of the drain list, we may need to sustain the drain
28083  * process by qenabling the next conn in the drain list. We may also need to
28084  * remove this conn from the list, if it is done.
28085  */
28086 static void
28087 conn_drain_tail(conn_t *connp, boolean_t closing)
28088 {
28089 	idl_t *idl;
28090 
28091 	/*
28092 	 * connp->conn_idl is stable at this point, and no lock is needed
28093 	 * to check it. If we are called from ip_close, close has already
28094 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28095 	 * called us only because conn_idl is non-null. If we are called thru
28096 	 * service, conn_idl could be null, but it cannot change because
28097 	 * service is single-threaded per queue, and there cannot be another
28098 	 * instance of service trying to call conn_drain_insert on this conn
28099 	 * now.
28100 	 */
28101 	ASSERT(!closing || (connp->conn_idl != NULL));
28102 
28103 	/*
28104 	 * If connp->conn_idl is null, the conn has not been inserted into any
28105 	 * drain list even once since creation of the conn. Just return.
28106 	 */
28107 	if (connp->conn_idl == NULL)
28108 		return;
28109 
28110 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28111 
28112 	if (connp->conn_drain_prev == NULL) {
28113 		/* This conn is currently not in the drain list.  */
28114 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28115 		return;
28116 	}
28117 	idl = connp->conn_idl;
28118 	if (idl->idl_conn_draining == connp) {
28119 		/*
28120 		 * This conn is the current drainer. If this is the last conn
28121 		 * in the drain list, we need to do more checks, in the 'if'
28122 		 * below. Otherwwise we need to just qenable the next conn,
28123 		 * to sustain the draining, and is handled in the 'else'
28124 		 * below.
28125 		 */
28126 		if (connp->conn_drain_next == idl->idl_conn) {
28127 			/*
28128 			 * This conn is the last in this list. This round
28129 			 * of draining is complete. If idl_repeat is set,
28130 			 * it means another flow enabling has happened from
28131 			 * the driver/streams and we need to another round
28132 			 * of draining.
28133 			 * If there are more than 2 conns in the drain list,
28134 			 * do a left rotate by 1, so that all conns except the
28135 			 * conn at the head move towards the head by 1, and the
28136 			 * the conn at the head goes to the tail. This attempts
28137 			 * a more even share for all queues that are being
28138 			 * drained.
28139 			 */
28140 			if ((connp->conn_drain_next != connp) &&
28141 			    (idl->idl_conn->conn_drain_next != connp)) {
28142 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28143 			}
28144 			if (idl->idl_repeat) {
28145 				qenable(idl->idl_conn->conn_wq);
28146 				idl->idl_conn_draining = idl->idl_conn;
28147 				idl->idl_repeat = 0;
28148 			} else {
28149 				idl->idl_conn_draining = NULL;
28150 			}
28151 		} else {
28152 			/*
28153 			 * If the next queue that we are now qenable'ing,
28154 			 * is closing, it will remove itself from this list
28155 			 * and qenable the subsequent queue in ip_close().
28156 			 * Serialization is acheived thru idl_lock.
28157 			 */
28158 			qenable(connp->conn_drain_next->conn_wq);
28159 			idl->idl_conn_draining = connp->conn_drain_next;
28160 		}
28161 	}
28162 	if (!connp->conn_did_putbq || closing) {
28163 		/*
28164 		 * Remove ourself from the drain list, if we did not do
28165 		 * a putbq, or if the conn is closing.
28166 		 * Note: It is possible that q->q_first is non-null. It means
28167 		 * that these messages landed after we did a enableok() in
28168 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28169 		 * service them.
28170 		 */
28171 		if (connp->conn_drain_next == connp) {
28172 			/* Singleton in the list */
28173 			ASSERT(connp->conn_drain_prev == connp);
28174 			idl->idl_conn = NULL;
28175 			idl->idl_conn_draining = NULL;
28176 		} else {
28177 			connp->conn_drain_prev->conn_drain_next =
28178 			    connp->conn_drain_next;
28179 			connp->conn_drain_next->conn_drain_prev =
28180 			    connp->conn_drain_prev;
28181 			if (idl->idl_conn == connp)
28182 				idl->idl_conn = connp->conn_drain_next;
28183 			ASSERT(idl->idl_conn_draining != connp);
28184 
28185 		}
28186 		connp->conn_drain_next = NULL;
28187 		connp->conn_drain_prev = NULL;
28188 	}
28189 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28190 }
28191 
28192 /*
28193  * Write service routine. Shared perimeter entry point.
28194  * ip_wsrv can be called in any of the following ways.
28195  * 1. The device queue's messages has fallen below the low water mark
28196  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28197  *    the drain lists and backenable the first conn in each list.
28198  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28199  *    qenabled non-tcp upper layers. We start dequeing messages and call
28200  *    ip_wput for each message.
28201  */
28202 
28203 void
28204 ip_wsrv(queue_t *q)
28205 {
28206 	conn_t	*connp;
28207 	ill_t	*ill;
28208 	mblk_t	*mp;
28209 
28210 	if (q->q_next) {
28211 		ill = (ill_t *)q->q_ptr;
28212 		if (ill->ill_state_flags == 0) {
28213 			/*
28214 			 * The device flow control has opened up.
28215 			 * Walk through conn drain lists and qenable the
28216 			 * first conn in each list. This makes sense only
28217 			 * if the stream is fully plumbed and setup.
28218 			 * Hence the if check above.
28219 			 */
28220 			ip1dbg(("ip_wsrv: walking\n"));
28221 			conn_walk_drain(ill->ill_ipst);
28222 		}
28223 		return;
28224 	}
28225 
28226 	connp = Q_TO_CONN(q);
28227 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28228 
28229 	/*
28230 	 * 1. Set conn_draining flag to signal that service is active.
28231 	 *
28232 	 * 2. ip_output determines whether it has been called from service,
28233 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28234 	 *    has been called from service.
28235 	 *
28236 	 * 3. Message ordering is preserved by the following logic.
28237 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28238 	 *    the message at the tail, if conn_draining is set (i.e. service
28239 	 *    is running) or if q->q_first is non-null.
28240 	 *
28241 	 *    ii. If ip_output is called from service, and if ip_output cannot
28242 	 *    putnext due to flow control, it does a putbq.
28243 	 *
28244 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28245 	 *    (causing an infinite loop).
28246 	 */
28247 	ASSERT(!connp->conn_did_putbq);
28248 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28249 		connp->conn_draining = 1;
28250 		noenable(q);
28251 		while ((mp = getq(q)) != NULL) {
28252 			ASSERT(CONN_Q(q));
28253 
28254 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28255 			if (connp->conn_did_putbq) {
28256 				/* ip_wput did a putbq */
28257 				break;
28258 			}
28259 		}
28260 		/*
28261 		 * At this point, a thread coming down from top, calling
28262 		 * ip_wput, may end up queueing the message. We have not yet
28263 		 * enabled the queue, so ip_wsrv won't be called again.
28264 		 * To avoid this race, check q->q_first again (in the loop)
28265 		 * If the other thread queued the message before we call
28266 		 * enableok(), we will catch it in the q->q_first check.
28267 		 * If the other thread queues the message after we call
28268 		 * enableok(), ip_wsrv will be called again by STREAMS.
28269 		 */
28270 		connp->conn_draining = 0;
28271 		enableok(q);
28272 	}
28273 
28274 	/* Enable the next conn for draining */
28275 	conn_drain_tail(connp, B_FALSE);
28276 
28277 	connp->conn_did_putbq = 0;
28278 }
28279 
28280 /*
28281  * Walk the list of all conn's calling the function provided with the
28282  * specified argument for each.	 Note that this only walks conn's that
28283  * have been bound.
28284  * Applies to both IPv4 and IPv6.
28285  */
28286 static void
28287 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid, ip_stack_t *ipst)
28288 {
28289 	conn_walk_fanout_table(ipst->ips_ipcl_udp_fanout,
28290 	    ipst->ips_ipcl_udp_fanout_size,
28291 	    func, arg, zoneid);
28292 	conn_walk_fanout_table(ipst->ips_ipcl_conn_fanout,
28293 	    ipst->ips_ipcl_conn_fanout_size,
28294 	    func, arg, zoneid);
28295 	conn_walk_fanout_table(ipst->ips_ipcl_bind_fanout,
28296 	    ipst->ips_ipcl_bind_fanout_size,
28297 	    func, arg, zoneid);
28298 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout,
28299 	    IPPROTO_MAX, func, arg, zoneid);
28300 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout_v6,
28301 	    IPPROTO_MAX, func, arg, zoneid);
28302 }
28303 
28304 /*
28305  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28306  * of conns that need to be drained, check if drain is already in progress.
28307  * If so set the idl_repeat bit, indicating that the last conn in the list
28308  * needs to reinitiate the drain once again, for the list. If drain is not
28309  * in progress for the list, initiate the draining, by qenabling the 1st
28310  * conn in the list. The drain is self-sustaining, each qenabled conn will
28311  * in turn qenable the next conn, when it is done/blocked/closing.
28312  */
28313 static void
28314 conn_walk_drain(ip_stack_t *ipst)
28315 {
28316 	int i;
28317 	idl_t *idl;
28318 
28319 	IP_STAT(ipst, ip_conn_walk_drain);
28320 
28321 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28322 		idl = &ipst->ips_conn_drain_list[i];
28323 		mutex_enter(&idl->idl_lock);
28324 		if (idl->idl_conn == NULL) {
28325 			mutex_exit(&idl->idl_lock);
28326 			continue;
28327 		}
28328 		/*
28329 		 * If this list is not being drained currently by
28330 		 * an ip_wsrv thread, start the process.
28331 		 */
28332 		if (idl->idl_conn_draining == NULL) {
28333 			ASSERT(idl->idl_repeat == 0);
28334 			qenable(idl->idl_conn->conn_wq);
28335 			idl->idl_conn_draining = idl->idl_conn;
28336 		} else {
28337 			idl->idl_repeat = 1;
28338 		}
28339 		mutex_exit(&idl->idl_lock);
28340 	}
28341 }
28342 
28343 /*
28344  * Walk an conn hash table of `count' buckets, calling func for each entry.
28345  */
28346 static void
28347 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
28348     zoneid_t zoneid)
28349 {
28350 	conn_t	*connp;
28351 
28352 	while (count-- > 0) {
28353 		mutex_enter(&connfp->connf_lock);
28354 		for (connp = connfp->connf_head; connp != NULL;
28355 		    connp = connp->conn_next) {
28356 			if (zoneid == GLOBAL_ZONEID ||
28357 			    zoneid == connp->conn_zoneid) {
28358 				CONN_INC_REF(connp);
28359 				mutex_exit(&connfp->connf_lock);
28360 				(*func)(connp, arg);
28361 				mutex_enter(&connfp->connf_lock);
28362 				CONN_DEC_REF(connp);
28363 			}
28364 		}
28365 		mutex_exit(&connfp->connf_lock);
28366 		connfp++;
28367 	}
28368 }
28369 
28370 /* conn_walk_fanout routine invoked for ip_conn_report for each conn. */
28371 static void
28372 conn_report1(conn_t *connp, void *mp)
28373 {
28374 	char	buf1[INET6_ADDRSTRLEN];
28375 	char	buf2[INET6_ADDRSTRLEN];
28376 	uint_t	print_len, buf_len;
28377 
28378 	ASSERT(connp != NULL);
28379 
28380 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
28381 	if (buf_len <= 0)
28382 		return;
28383 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1));
28384 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2));
28385 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
28386 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
28387 	    "%5d %s/%05d %s/%05d\n",
28388 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
28389 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
28390 	    buf1, connp->conn_lport,
28391 	    buf2, connp->conn_fport);
28392 	if (print_len < buf_len) {
28393 		((mblk_t *)mp)->b_wptr += print_len;
28394 	} else {
28395 		((mblk_t *)mp)->b_wptr += buf_len;
28396 	}
28397 }
28398 
28399 /*
28400  * Named Dispatch routine to produce a formatted report on all conns
28401  * that are listed in one of the fanout tables.
28402  * This report is accessed by using the ndd utility to "get" ND variable
28403  * "ip_conn_status".
28404  */
28405 /* ARGSUSED */
28406 static int
28407 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
28408 {
28409 	conn_t *connp = Q_TO_CONN(q);
28410 
28411 	(void) mi_mpprintf(mp,
28412 	    "CONN      " MI_COL_HDRPAD_STR
28413 	    "rfq      " MI_COL_HDRPAD_STR
28414 	    "stq      " MI_COL_HDRPAD_STR
28415 	    " zone local                 remote");
28416 
28417 	/*
28418 	 * Because of the ndd constraint, at most we can have 64K buffer
28419 	 * to put in all conn info.  So to be more efficient, just
28420 	 * allocate a 64K buffer here, assuming we need that large buffer.
28421 	 * This should be OK as only privileged processes can do ndd /dev/ip.
28422 	 */
28423 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
28424 		/* The following may work even if we cannot get a large buf. */
28425 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
28426 		return (0);
28427 	}
28428 
28429 	conn_walk_fanout(conn_report1, mp->b_cont, connp->conn_zoneid,
28430 	    connp->conn_netstack->netstack_ip);
28431 	return (0);
28432 }
28433 
28434 /*
28435  * Determine if the ill and multicast aspects of that packets
28436  * "matches" the conn.
28437  */
28438 boolean_t
28439 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28440     zoneid_t zoneid)
28441 {
28442 	ill_t *in_ill;
28443 	boolean_t found;
28444 	ipif_t *ipif;
28445 	ire_t *ire;
28446 	ipaddr_t dst, src;
28447 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28448 
28449 	dst = ipha->ipha_dst;
28450 	src = ipha->ipha_src;
28451 
28452 	/*
28453 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28454 	 * unicast, broadcast and multicast reception to
28455 	 * conn_incoming_ill. conn_wantpacket itself is called
28456 	 * only for BROADCAST and multicast.
28457 	 *
28458 	 * 1) ip_rput supresses duplicate broadcasts if the ill
28459 	 *    is part of a group. Hence, we should be receiving
28460 	 *    just one copy of broadcast for the whole group.
28461 	 *    Thus, if it is part of the group the packet could
28462 	 *    come on any ill of the group and hence we need a
28463 	 *    match on the group. Otherwise, match on ill should
28464 	 *    be sufficient.
28465 	 *
28466 	 * 2) ip_rput does not suppress duplicate multicast packets.
28467 	 *    If there are two interfaces in a ill group and we have
28468 	 *    2 applications (conns) joined a multicast group G on
28469 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
28470 	 *    will give us two packets because we join G on both the
28471 	 *    interfaces rather than nominating just one interface
28472 	 *    for receiving multicast like broadcast above. So,
28473 	 *    we have to call ilg_lookup_ill to filter out duplicate
28474 	 *    copies, if ill is part of a group.
28475 	 */
28476 	in_ill = connp->conn_incoming_ill;
28477 	if (in_ill != NULL) {
28478 		if (in_ill->ill_group == NULL) {
28479 			if (in_ill != ill)
28480 				return (B_FALSE);
28481 		} else if (in_ill->ill_group != ill->ill_group) {
28482 			return (B_FALSE);
28483 		}
28484 	}
28485 
28486 	if (!CLASSD(dst)) {
28487 		if (IPCL_ZONE_MATCH(connp, zoneid))
28488 			return (B_TRUE);
28489 		/*
28490 		 * The conn is in a different zone; we need to check that this
28491 		 * broadcast address is configured in the application's zone and
28492 		 * on one ill in the group.
28493 		 */
28494 		ipif = ipif_get_next_ipif(NULL, ill);
28495 		if (ipif == NULL)
28496 			return (B_FALSE);
28497 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28498 		    connp->conn_zoneid, NULL,
28499 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
28500 		ipif_refrele(ipif);
28501 		if (ire != NULL) {
28502 			ire_refrele(ire);
28503 			return (B_TRUE);
28504 		} else {
28505 			return (B_FALSE);
28506 		}
28507 	}
28508 
28509 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28510 	    connp->conn_zoneid == zoneid) {
28511 		/*
28512 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28513 		 * disabled, therefore we don't dispatch the multicast packet to
28514 		 * the sending zone.
28515 		 */
28516 		return (B_FALSE);
28517 	}
28518 
28519 	if (IS_LOOPBACK(ill) && connp->conn_zoneid != zoneid) {
28520 		/*
28521 		 * Multicast packet on the loopback interface: we only match
28522 		 * conns who joined the group in the specified zone.
28523 		 */
28524 		return (B_FALSE);
28525 	}
28526 
28527 	if (connp->conn_multi_router) {
28528 		/* multicast packet and multicast router socket: send up */
28529 		return (B_TRUE);
28530 	}
28531 
28532 	mutex_enter(&connp->conn_lock);
28533 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28534 	mutex_exit(&connp->conn_lock);
28535 	return (found);
28536 }
28537 
28538 /*
28539  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28540  */
28541 /* ARGSUSED */
28542 static void
28543 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28544 {
28545 	ill_t *ill = (ill_t *)q->q_ptr;
28546 	mblk_t	*mp1, *mp2;
28547 	ipif_t  *ipif;
28548 	int err = 0;
28549 	conn_t *connp = NULL;
28550 	ipsq_t	*ipsq;
28551 	arc_t	*arc;
28552 
28553 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28554 
28555 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28556 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28557 
28558 	ASSERT(IAM_WRITER_ILL(ill));
28559 	mp2 = mp->b_cont;
28560 	mp->b_cont = NULL;
28561 
28562 	/*
28563 	 * We have now received the arp bringup completion message
28564 	 * from ARP. Mark the arp bringup as done. Also if the arp
28565 	 * stream has already started closing, send up the AR_ARP_CLOSING
28566 	 * ack now since ARP is waiting in close for this ack.
28567 	 */
28568 	mutex_enter(&ill->ill_lock);
28569 	ill->ill_arp_bringup_pending = 0;
28570 	if (ill->ill_arp_closing) {
28571 		mutex_exit(&ill->ill_lock);
28572 		/* Let's reuse the mp for sending the ack */
28573 		arc = (arc_t *)mp->b_rptr;
28574 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28575 		arc->arc_cmd = AR_ARP_CLOSING;
28576 		qreply(q, mp);
28577 	} else {
28578 		mutex_exit(&ill->ill_lock);
28579 		freeb(mp);
28580 	}
28581 
28582 	ipsq = ill->ill_phyint->phyint_ipsq;
28583 	ipif = ipsq->ipsq_pending_ipif;
28584 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28585 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
28586 	if (mp1 == NULL) {
28587 		/* bringup was aborted by the user */
28588 		freemsg(mp2);
28589 		return;
28590 	}
28591 
28592 	/*
28593 	 * If an IOCTL is waiting on this (ipsq_current_ioctl != 0), then we
28594 	 * must have an associated conn_t.  Otherwise, we're bringing this
28595 	 * interface back up as part of handling an asynchronous event (e.g.,
28596 	 * physical address change).
28597 	 */
28598 	if (ipsq->ipsq_current_ioctl != 0) {
28599 		ASSERT(connp != NULL);
28600 		q = CONNP_TO_WQ(connp);
28601 	} else {
28602 		ASSERT(connp == NULL);
28603 		q = ill->ill_rq;
28604 	}
28605 
28606 	/*
28607 	 * If the DL_BIND_REQ fails, it is noted
28608 	 * in arc_name_offset.
28609 	 */
28610 	err = *((int *)mp2->b_rptr);
28611 	if (err == 0) {
28612 		if (ipif->ipif_isv6) {
28613 			if ((err = ipif_up_done_v6(ipif)) != 0)
28614 				ip0dbg(("ip_arp_done: init failed\n"));
28615 		} else {
28616 			if ((err = ipif_up_done(ipif)) != 0)
28617 				ip0dbg(("ip_arp_done: init failed\n"));
28618 		}
28619 	} else {
28620 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28621 	}
28622 
28623 	freemsg(mp2);
28624 
28625 	if ((err == 0) && (ill->ill_up_ipifs)) {
28626 		err = ill_up_ipifs(ill, q, mp1);
28627 		if (err == EINPROGRESS)
28628 			return;
28629 	}
28630 
28631 	if (ill->ill_up_ipifs)
28632 		ill_group_cleanup(ill);
28633 
28634 	/*
28635 	 * The operation must complete without EINPROGRESS since
28636 	 * ipsq_pending_mp_get() has removed the mblk from ipsq_pending_mp.
28637 	 * Otherwise, the operation will be stuck forever in the ipsq.
28638 	 */
28639 	ASSERT(err != EINPROGRESS);
28640 	if (ipsq->ipsq_current_ioctl != 0)
28641 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
28642 	else
28643 		ipsq_current_finish(ipsq);
28644 }
28645 
28646 /* Allocate the private structure */
28647 static int
28648 ip_priv_alloc(void **bufp)
28649 {
28650 	void	*buf;
28651 
28652 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
28653 		return (ENOMEM);
28654 
28655 	*bufp = buf;
28656 	return (0);
28657 }
28658 
28659 /* Function to delete the private structure */
28660 void
28661 ip_priv_free(void *buf)
28662 {
28663 	ASSERT(buf != NULL);
28664 	kmem_free(buf, sizeof (ip_priv_t));
28665 }
28666 
28667 /*
28668  * The entry point for IPPF processing.
28669  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
28670  * routine just returns.
28671  *
28672  * When called, ip_process generates an ipp_packet_t structure
28673  * which holds the state information for this packet and invokes the
28674  * the classifier (via ipp_packet_process). The classification, depending on
28675  * configured filters, results in a list of actions for this packet. Invoking
28676  * an action may cause the packet to be dropped, in which case the resulting
28677  * mblk (*mpp) is NULL. proc indicates the callout position for
28678  * this packet and ill_index is the interface this packet on or will leave
28679  * on (inbound and outbound resp.).
28680  */
28681 void
28682 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
28683 {
28684 	mblk_t		*mp;
28685 	ip_priv_t	*priv;
28686 	ipp_action_id_t	aid;
28687 	int		rc = 0;
28688 	ipp_packet_t	*pp;
28689 #define	IP_CLASS	"ip"
28690 
28691 	/* If the classifier is not loaded, return  */
28692 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
28693 		return;
28694 	}
28695 
28696 	mp = *mpp;
28697 	ASSERT(mp != NULL);
28698 
28699 	/* Allocate the packet structure */
28700 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
28701 	if (rc != 0) {
28702 		*mpp = NULL;
28703 		freemsg(mp);
28704 		return;
28705 	}
28706 
28707 	/* Allocate the private structure */
28708 	rc = ip_priv_alloc((void **)&priv);
28709 	if (rc != 0) {
28710 		*mpp = NULL;
28711 		freemsg(mp);
28712 		ipp_packet_free(pp);
28713 		return;
28714 	}
28715 	priv->proc = proc;
28716 	priv->ill_index = ill_index;
28717 	ipp_packet_set_private(pp, priv, ip_priv_free);
28718 	ipp_packet_set_data(pp, mp);
28719 
28720 	/* Invoke the classifier */
28721 	rc = ipp_packet_process(&pp);
28722 	if (pp != NULL) {
28723 		mp = ipp_packet_get_data(pp);
28724 		ipp_packet_free(pp);
28725 		if (rc != 0) {
28726 			freemsg(mp);
28727 			*mpp = NULL;
28728 		}
28729 	} else {
28730 		*mpp = NULL;
28731 	}
28732 #undef	IP_CLASS
28733 }
28734 
28735 /*
28736  * Propagate a multicast group membership operation (add/drop) on
28737  * all the interfaces crossed by the related multirt routes.
28738  * The call is considered successful if the operation succeeds
28739  * on at least one interface.
28740  */
28741 static int
28742 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
28743     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
28744     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
28745     mblk_t *first_mp)
28746 {
28747 	ire_t		*ire_gw;
28748 	irb_t		*irb;
28749 	int		error = 0;
28750 	opt_restart_t	*or;
28751 	ip_stack_t	*ipst = ire->ire_ipst;
28752 
28753 	irb = ire->ire_bucket;
28754 	ASSERT(irb != NULL);
28755 
28756 	ASSERT(DB_TYPE(first_mp) == M_CTL);
28757 
28758 	or = (opt_restart_t *)first_mp->b_rptr;
28759 	IRB_REFHOLD(irb);
28760 	for (; ire != NULL; ire = ire->ire_next) {
28761 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
28762 			continue;
28763 		if (ire->ire_addr != group)
28764 			continue;
28765 
28766 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
28767 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
28768 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
28769 		/* No resolver exists for the gateway; skip this ire. */
28770 		if (ire_gw == NULL)
28771 			continue;
28772 
28773 		/*
28774 		 * This function can return EINPROGRESS. If so the operation
28775 		 * will be restarted from ip_restart_optmgmt which will
28776 		 * call ip_opt_set and option processing will restart for
28777 		 * this option. So we may end up calling 'fn' more than once.
28778 		 * This requires that 'fn' is idempotent except for the
28779 		 * return value. The operation is considered a success if
28780 		 * it succeeds at least once on any one interface.
28781 		 */
28782 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
28783 		    NULL, fmode, src, first_mp);
28784 		if (error == 0)
28785 			or->or_private = CGTP_MCAST_SUCCESS;
28786 
28787 		if (ip_debug > 0) {
28788 			ulong_t	off;
28789 			char	*ksym;
28790 			ksym = kobj_getsymname((uintptr_t)fn, &off);
28791 			ip2dbg(("ip_multirt_apply_membership: "
28792 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
28793 			    "error %d [success %u]\n",
28794 			    ksym ? ksym : "?",
28795 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
28796 			    error, or->or_private));
28797 		}
28798 
28799 		ire_refrele(ire_gw);
28800 		if (error == EINPROGRESS) {
28801 			IRB_REFRELE(irb);
28802 			return (error);
28803 		}
28804 	}
28805 	IRB_REFRELE(irb);
28806 	/*
28807 	 * Consider the call as successful if we succeeded on at least
28808 	 * one interface. Otherwise, return the last encountered error.
28809 	 */
28810 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
28811 }
28812 
28813 
28814 /*
28815  * Issue a warning regarding a route crossing an interface with an
28816  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
28817  * amount of time is logged.
28818  */
28819 static void
28820 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
28821 {
28822 	hrtime_t	current = gethrtime();
28823 	char		buf[INET_ADDRSTRLEN];
28824 	ip_stack_t	*ipst = ire->ire_ipst;
28825 
28826 	/* Convert interval in ms to hrtime in ns */
28827 	if (ipst->ips_multirt_bad_mtu_last_time +
28828 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
28829 	    current) {
28830 		cmn_err(CE_WARN, "ip: ignoring multiroute "
28831 		    "to %s, incorrect MTU %u (expected %u)\n",
28832 		    ip_dot_addr(ire->ire_addr, buf),
28833 		    ire->ire_max_frag, max_frag);
28834 
28835 		ipst->ips_multirt_bad_mtu_last_time = current;
28836 	}
28837 }
28838 
28839 
28840 /*
28841  * Get the CGTP (multirouting) filtering status.
28842  * If 0, the CGTP hooks are transparent.
28843  */
28844 /* ARGSUSED */
28845 static int
28846 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
28847 {
28848 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28849 
28850 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
28851 	return (0);
28852 }
28853 
28854 
28855 /*
28856  * Set the CGTP (multirouting) filtering status.
28857  * If the status is changed from active to transparent
28858  * or from transparent to active, forward the new status
28859  * to the filtering module (if loaded).
28860  */
28861 /* ARGSUSED */
28862 static int
28863 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
28864     cred_t *ioc_cr)
28865 {
28866 	long		new_value;
28867 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28868 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
28869 
28870 	if (secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
28871 		return (EPERM);
28872 
28873 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
28874 	    new_value < 0 || new_value > 1) {
28875 		return (EINVAL);
28876 	}
28877 
28878 	if ((!*ip_cgtp_filter_value) && new_value) {
28879 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
28880 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28881 		    " (module not loaded)" : "");
28882 	}
28883 	if (*ip_cgtp_filter_value && (!new_value)) {
28884 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
28885 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28886 		    " (module not loaded)" : "");
28887 	}
28888 
28889 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
28890 		int	res;
28891 		netstackid_t stackid;
28892 
28893 		stackid = ipst->ips_netstack->netstack_stackid;
28894 		res = ipst->ips_ip_cgtp_filter_ops->cfo_change_state(stackid,
28895 		    new_value);
28896 		if (res)
28897 			return (res);
28898 	}
28899 
28900 	*ip_cgtp_filter_value = (boolean_t)new_value;
28901 
28902 	return (0);
28903 }
28904 
28905 
28906 /*
28907  * Return the expected CGTP hooks version number.
28908  */
28909 int
28910 ip_cgtp_filter_supported(void)
28911 {
28912 	return (ip_cgtp_filter_rev);
28913 }
28914 
28915 
28916 /*
28917  * CGTP hooks can be registered by invoking this function.
28918  * Checks that the version number matches.
28919  */
28920 int
28921 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
28922 {
28923 	netstack_t *ns;
28924 	ip_stack_t *ipst;
28925 
28926 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
28927 		return (ENOTSUP);
28928 
28929 	ns = netstack_find_by_stackid(stackid);
28930 	if (ns == NULL)
28931 		return (EINVAL);
28932 	ipst = ns->netstack_ip;
28933 	ASSERT(ipst != NULL);
28934 
28935 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
28936 		netstack_rele(ns);
28937 		return (EALREADY);
28938 	}
28939 
28940 	ipst->ips_ip_cgtp_filter_ops = ops;
28941 	netstack_rele(ns);
28942 	return (0);
28943 }
28944 
28945 /*
28946  * CGTP hooks can be unregistered by invoking this function.
28947  * Returns ENXIO if there was no registration.
28948  * Returns EBUSY if the ndd variable has not been turned off.
28949  */
28950 int
28951 ip_cgtp_filter_unregister(netstackid_t stackid)
28952 {
28953 	netstack_t *ns;
28954 	ip_stack_t *ipst;
28955 
28956 	ns = netstack_find_by_stackid(stackid);
28957 	if (ns == NULL)
28958 		return (EINVAL);
28959 	ipst = ns->netstack_ip;
28960 	ASSERT(ipst != NULL);
28961 
28962 	if (ipst->ips_ip_cgtp_filter) {
28963 		netstack_rele(ns);
28964 		return (EBUSY);
28965 	}
28966 
28967 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
28968 		netstack_rele(ns);
28969 		return (ENXIO);
28970 	}
28971 	ipst->ips_ip_cgtp_filter_ops = NULL;
28972 	netstack_rele(ns);
28973 	return (0);
28974 }
28975 
28976 /*
28977  * Check whether there is a CGTP filter registration.
28978  * Returns non-zero if there is a registration, otherwise returns zero.
28979  * Note: returns zero if bad stackid.
28980  */
28981 int
28982 ip_cgtp_filter_is_registered(netstackid_t stackid)
28983 {
28984 	netstack_t *ns;
28985 	ip_stack_t *ipst;
28986 	int ret;
28987 
28988 	ns = netstack_find_by_stackid(stackid);
28989 	if (ns == NULL)
28990 		return (0);
28991 	ipst = ns->netstack_ip;
28992 	ASSERT(ipst != NULL);
28993 
28994 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
28995 		ret = 1;
28996 	else
28997 		ret = 0;
28998 
28999 	netstack_rele(ns);
29000 	return (ret);
29001 }
29002 
29003 static squeue_func_t
29004 ip_squeue_switch(int val)
29005 {
29006 	squeue_func_t rval = squeue_fill;
29007 
29008 	switch (val) {
29009 	case IP_SQUEUE_ENTER_NODRAIN:
29010 		rval = squeue_enter_nodrain;
29011 		break;
29012 	case IP_SQUEUE_ENTER:
29013 		rval = squeue_enter;
29014 		break;
29015 	default:
29016 		break;
29017 	}
29018 	return (rval);
29019 }
29020 
29021 /* ARGSUSED */
29022 static int
29023 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
29024     caddr_t addr, cred_t *cr)
29025 {
29026 	int *v = (int *)addr;
29027 	long new_value;
29028 
29029 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29030 		return (EPERM);
29031 
29032 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29033 		return (EINVAL);
29034 
29035 	ip_input_proc = ip_squeue_switch(new_value);
29036 	*v = new_value;
29037 	return (0);
29038 }
29039 
29040 /*
29041  * Handle ndd set of variables which require PRIV_SYS_NET_CONFIG such as
29042  * ip_debug.
29043  */
29044 /* ARGSUSED */
29045 static int
29046 ip_int_set(queue_t *q, mblk_t *mp, char *value,
29047     caddr_t addr, cred_t *cr)
29048 {
29049 	int *v = (int *)addr;
29050 	long new_value;
29051 
29052 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29053 		return (EPERM);
29054 
29055 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29056 		return (EINVAL);
29057 
29058 	*v = new_value;
29059 	return (0);
29060 }
29061 
29062 /*
29063  * Handle changes to ipmp_hook_emulation ndd variable.
29064  * Need to update phyint_hook_ifindex.
29065  * Also generate a nic plumb event should a new ifidex be assigned to a group.
29066  */
29067 static void
29068 ipmp_hook_emulation_changed(ip_stack_t *ipst)
29069 {
29070 	phyint_t *phyi;
29071 	phyint_t *phyi_tmp;
29072 	char *groupname;
29073 	int namelen;
29074 	ill_t	*ill;
29075 	boolean_t new_group;
29076 
29077 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29078 	/*
29079 	 * Group indicies are stored in the phyint - a common structure
29080 	 * to both IPv4 and IPv6.
29081 	 */
29082 	phyi = avl_first(&ipst->ips_phyint_g_list->phyint_list_avl_by_index);
29083 	for (; phyi != NULL;
29084 	    phyi = avl_walk(&ipst->ips_phyint_g_list->phyint_list_avl_by_index,
29085 	    phyi, AVL_AFTER)) {
29086 		/* Ignore the ones that do not have a group */
29087 		if (phyi->phyint_groupname_len == 0)
29088 			continue;
29089 
29090 		/*
29091 		 * Look for other phyint in group.
29092 		 * Clear name/namelen so the lookup doesn't find ourselves.
29093 		 */
29094 		namelen = phyi->phyint_groupname_len;
29095 		groupname = phyi->phyint_groupname;
29096 		phyi->phyint_groupname_len = 0;
29097 		phyi->phyint_groupname = NULL;
29098 
29099 		phyi_tmp = phyint_lookup_group(groupname, B_FALSE, ipst);
29100 		/* Restore */
29101 		phyi->phyint_groupname_len = namelen;
29102 		phyi->phyint_groupname = groupname;
29103 
29104 		new_group = B_FALSE;
29105 		if (ipst->ips_ipmp_hook_emulation) {
29106 			/*
29107 			 * If the group already exists and has already
29108 			 * been assigned a group ifindex, we use the existing
29109 			 * group_ifindex, otherwise we pick a new group_ifindex
29110 			 * here.
29111 			 */
29112 			if (phyi_tmp != NULL &&
29113 			    phyi_tmp->phyint_group_ifindex != 0) {
29114 				phyi->phyint_group_ifindex =
29115 				    phyi_tmp->phyint_group_ifindex;
29116 			} else {
29117 				/* XXX We need a recovery strategy here. */
29118 				if (!ip_assign_ifindex(
29119 				    &phyi->phyint_group_ifindex, ipst))
29120 					cmn_err(CE_PANIC,
29121 					    "ip_assign_ifindex() failed");
29122 				new_group = B_TRUE;
29123 			}
29124 		} else {
29125 			phyi->phyint_group_ifindex = 0;
29126 		}
29127 		if (ipst->ips_ipmp_hook_emulation)
29128 			phyi->phyint_hook_ifindex = phyi->phyint_group_ifindex;
29129 		else
29130 			phyi->phyint_hook_ifindex = phyi->phyint_ifindex;
29131 
29132 		/*
29133 		 * For IP Filter to find out the relationship between
29134 		 * names and interface indicies, we need to generate
29135 		 * a NE_PLUMB event when a new group can appear.
29136 		 * We always generate events when a new interface appears
29137 		 * (even when ipmp_hook_emulation is set) so there
29138 		 * is no need to generate NE_PLUMB events when
29139 		 * ipmp_hook_emulation is turned off.
29140 		 * And since it isn't critical for IP Filter to get
29141 		 * the NE_UNPLUMB events we skip those here.
29142 		 */
29143 		if (new_group) {
29144 			/*
29145 			 * First phyint in group - generate group PLUMB event.
29146 			 * Since we are not running inside the ipsq we do
29147 			 * the dispatch immediately.
29148 			 */
29149 			if (phyi->phyint_illv4 != NULL)
29150 				ill = phyi->phyint_illv4;
29151 			else
29152 				ill = phyi->phyint_illv6;
29153 
29154 			if (ill != NULL) {
29155 				mutex_enter(&ill->ill_lock);
29156 				ill_nic_info_plumb(ill, B_TRUE);
29157 				ill_nic_info_dispatch(ill);
29158 				mutex_exit(&ill->ill_lock);
29159 			}
29160 		}
29161 	}
29162 	rw_exit(&ipst->ips_ill_g_lock);
29163 }
29164 
29165 /* ARGSUSED */
29166 static int
29167 ipmp_hook_emulation_set(queue_t *q, mblk_t *mp, char *value,
29168     caddr_t addr, cred_t *cr)
29169 {
29170 	int *v = (int *)addr;
29171 	long new_value;
29172 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29173 
29174 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29175 		return (EINVAL);
29176 
29177 	if (*v != new_value) {
29178 		*v = new_value;
29179 		ipmp_hook_emulation_changed(ipst);
29180 	}
29181 	return (0);
29182 }
29183 
29184 static void *
29185 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
29186 {
29187 	kstat_t *ksp;
29188 
29189 	ip_stat_t template = {
29190 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
29191 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
29192 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
29193 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
29194 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
29195 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
29196 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
29197 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
29198 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
29199 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
29200 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
29201 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
29202 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
29203 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
29204 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
29205 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
29206 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
29207 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
29208 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
29209 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
29210 		{ "ip_opt",			KSTAT_DATA_UINT64 },
29211 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
29212 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
29213 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29214 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29215 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29216 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29217 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29218 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29219 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29220 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29221 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29222 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29223 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29224 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29225 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29226 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29227 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29228 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29229 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29230 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29231 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29232 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29233 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29234 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29235 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29236 	};
29237 
29238 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29239 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29240 	    KSTAT_FLAG_VIRTUAL, stackid);
29241 
29242 	if (ksp == NULL)
29243 		return (NULL);
29244 
29245 	bcopy(&template, ip_statisticsp, sizeof (template));
29246 	ksp->ks_data = (void *)ip_statisticsp;
29247 	ksp->ks_private = (void *)(uintptr_t)stackid;
29248 
29249 	kstat_install(ksp);
29250 	return (ksp);
29251 }
29252 
29253 static void
29254 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29255 {
29256 	if (ksp != NULL) {
29257 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29258 		kstat_delete_netstack(ksp, stackid);
29259 	}
29260 }
29261 
29262 static void *
29263 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29264 {
29265 	kstat_t	*ksp;
29266 
29267 	ip_named_kstat_t template = {
29268 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29269 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29270 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29271 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29272 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29273 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29274 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29275 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29276 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29277 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29278 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29279 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29280 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29281 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29282 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29283 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29284 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29285 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29286 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29287 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29288 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29289 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29290 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29291 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29292 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29293 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29294 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29295 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29296 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29297 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29298 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29299 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29300 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29301 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29302 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29303 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29304 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29305 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29306 	};
29307 
29308 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29309 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
29310 	if (ksp == NULL || ksp->ks_data == NULL)
29311 		return (NULL);
29312 
29313 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29314 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29315 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29316 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29317 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29318 
29319 	template.netToMediaEntrySize.value.i32 =
29320 	    sizeof (mib2_ipNetToMediaEntry_t);
29321 
29322 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29323 
29324 	bcopy(&template, ksp->ks_data, sizeof (template));
29325 	ksp->ks_update = ip_kstat_update;
29326 	ksp->ks_private = (void *)(uintptr_t)stackid;
29327 
29328 	kstat_install(ksp);
29329 	return (ksp);
29330 }
29331 
29332 static void
29333 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29334 {
29335 	if (ksp != NULL) {
29336 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29337 		kstat_delete_netstack(ksp, stackid);
29338 	}
29339 }
29340 
29341 static int
29342 ip_kstat_update(kstat_t *kp, int rw)
29343 {
29344 	ip_named_kstat_t *ipkp;
29345 	mib2_ipIfStatsEntry_t ipmib;
29346 	ill_walk_context_t ctx;
29347 	ill_t *ill;
29348 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29349 	netstack_t	*ns;
29350 	ip_stack_t	*ipst;
29351 
29352 	if (kp == NULL || kp->ks_data == NULL)
29353 		return (EIO);
29354 
29355 	if (rw == KSTAT_WRITE)
29356 		return (EACCES);
29357 
29358 	ns = netstack_find_by_stackid(stackid);
29359 	if (ns == NULL)
29360 		return (-1);
29361 	ipst = ns->netstack_ip;
29362 	if (ipst == NULL) {
29363 		netstack_rele(ns);
29364 		return (-1);
29365 	}
29366 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29367 
29368 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29369 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29370 	ill = ILL_START_WALK_V4(&ctx, ipst);
29371 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29372 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29373 	rw_exit(&ipst->ips_ill_g_lock);
29374 
29375 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29376 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29377 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29378 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29379 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29380 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29381 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29382 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29383 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29384 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29385 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29386 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29387 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29388 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29389 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29390 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29391 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29392 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29393 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29394 
29395 	ipkp->routingDiscards.value.ui32 =	0;
29396 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29397 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29398 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29399 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29400 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29401 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29402 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29403 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29404 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29405 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29406 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29407 
29408 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29409 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29410 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29411 
29412 	netstack_rele(ns);
29413 
29414 	return (0);
29415 }
29416 
29417 static void *
29418 icmp_kstat_init(netstackid_t stackid)
29419 {
29420 	kstat_t	*ksp;
29421 
29422 	icmp_named_kstat_t template = {
29423 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29424 		{ "inErrors",		KSTAT_DATA_UINT32 },
29425 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29426 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29427 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29428 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29429 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29430 		{ "inEchos",		KSTAT_DATA_UINT32 },
29431 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29432 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29433 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29434 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29435 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29436 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29437 		{ "outErrors",		KSTAT_DATA_UINT32 },
29438 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29439 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29440 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29441 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29442 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29443 		{ "outEchos",		KSTAT_DATA_UINT32 },
29444 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29445 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29446 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29447 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29448 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29449 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29450 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29451 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29452 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29453 		{ "outDrops",		KSTAT_DATA_UINT32 },
29454 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29455 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29456 	};
29457 
29458 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29459 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
29460 	if (ksp == NULL || ksp->ks_data == NULL)
29461 		return (NULL);
29462 
29463 	bcopy(&template, ksp->ks_data, sizeof (template));
29464 
29465 	ksp->ks_update = icmp_kstat_update;
29466 	ksp->ks_private = (void *)(uintptr_t)stackid;
29467 
29468 	kstat_install(ksp);
29469 	return (ksp);
29470 }
29471 
29472 static void
29473 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29474 {
29475 	if (ksp != NULL) {
29476 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29477 		kstat_delete_netstack(ksp, stackid);
29478 	}
29479 }
29480 
29481 static int
29482 icmp_kstat_update(kstat_t *kp, int rw)
29483 {
29484 	icmp_named_kstat_t *icmpkp;
29485 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29486 	netstack_t	*ns;
29487 	ip_stack_t	*ipst;
29488 
29489 	if ((kp == NULL) || (kp->ks_data == NULL))
29490 		return (EIO);
29491 
29492 	if (rw == KSTAT_WRITE)
29493 		return (EACCES);
29494 
29495 	ns = netstack_find_by_stackid(stackid);
29496 	if (ns == NULL)
29497 		return (-1);
29498 	ipst = ns->netstack_ip;
29499 	if (ipst == NULL) {
29500 		netstack_rele(ns);
29501 		return (-1);
29502 	}
29503 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29504 
29505 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29506 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29507 	icmpkp->inDestUnreachs.value.ui32 =
29508 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29509 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29510 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29511 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29512 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29513 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29514 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29515 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29516 	icmpkp->inTimestampReps.value.ui32 =
29517 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29518 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29519 	icmpkp->inAddrMaskReps.value.ui32 =
29520 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29521 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29522 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29523 	icmpkp->outDestUnreachs.value.ui32 =
29524 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29525 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29526 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29527 	icmpkp->outSrcQuenchs.value.ui32 =
29528 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29529 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29530 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29531 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29532 	icmpkp->outTimestamps.value.ui32 =
29533 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29534 	icmpkp->outTimestampReps.value.ui32 =
29535 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29536 	icmpkp->outAddrMasks.value.ui32 =
29537 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29538 	icmpkp->outAddrMaskReps.value.ui32 =
29539 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29540 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29541 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29542 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29543 	icmpkp->outFragNeeded.value.ui32 =
29544 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29545 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29546 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29547 	icmpkp->inBadRedirects.value.ui32 =
29548 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29549 
29550 	netstack_rele(ns);
29551 	return (0);
29552 }
29553 
29554 /*
29555  * This is the fanout function for raw socket opened for SCTP.  Note
29556  * that it is called after SCTP checks that there is no socket which
29557  * wants a packet.  Then before SCTP handles this out of the blue packet,
29558  * this function is called to see if there is any raw socket for SCTP.
29559  * If there is and it is bound to the correct address, the packet will
29560  * be sent to that socket.  Note that only one raw socket can be bound to
29561  * a port.  This is assured in ipcl_sctp_hash_insert();
29562  */
29563 void
29564 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29565     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29566     zoneid_t zoneid)
29567 {
29568 	conn_t		*connp;
29569 	queue_t		*rq;
29570 	mblk_t		*first_mp;
29571 	boolean_t	secure;
29572 	ip6_t		*ip6h;
29573 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29574 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29575 
29576 	first_mp = mp;
29577 	if (mctl_present) {
29578 		mp = first_mp->b_cont;
29579 		secure = ipsec_in_is_secure(first_mp);
29580 		ASSERT(mp != NULL);
29581 	} else {
29582 		secure = B_FALSE;
29583 	}
29584 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29585 
29586 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29587 	if (connp == NULL) {
29588 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29589 		return;
29590 	}
29591 	rq = connp->conn_rq;
29592 	if (!canputnext(rq)) {
29593 		CONN_DEC_REF(connp);
29594 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29595 		freemsg(first_mp);
29596 		return;
29597 	}
29598 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29599 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29600 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29601 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29602 		if (first_mp == NULL) {
29603 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29604 			CONN_DEC_REF(connp);
29605 			return;
29606 		}
29607 	}
29608 	/*
29609 	 * We probably should not send M_CTL message up to
29610 	 * raw socket.
29611 	 */
29612 	if (mctl_present)
29613 		freeb(first_mp);
29614 
29615 	/* Initiate IPPF processing here if needed. */
29616 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
29617 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
29618 		ip_process(IPP_LOCAL_IN, &mp,
29619 		    recv_ill->ill_phyint->phyint_ifindex);
29620 		if (mp == NULL) {
29621 			CONN_DEC_REF(connp);
29622 			return;
29623 		}
29624 	}
29625 
29626 	if (connp->conn_recvif || connp->conn_recvslla ||
29627 	    ((connp->conn_ip_recvpktinfo ||
29628 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29629 	    (flags & IP_FF_IPINFO))) {
29630 		int in_flags = 0;
29631 
29632 		/*
29633 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29634 		 * IPF_RECVIF.
29635 		 */
29636 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29637 			in_flags = IPF_RECVIF;
29638 		}
29639 		if (connp->conn_recvslla) {
29640 			in_flags |= IPF_RECVSLLA;
29641 		}
29642 		if (isv4) {
29643 			mp = ip_add_info(mp, recv_ill, in_flags,
29644 			    IPCL_ZONEID(connp), ipst);
29645 		} else {
29646 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
29647 			if (mp == NULL) {
29648 				BUMP_MIB(recv_ill->ill_ip_mib,
29649 				    ipIfStatsInDiscards);
29650 				CONN_DEC_REF(connp);
29651 				return;
29652 			}
29653 		}
29654 	}
29655 
29656 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
29657 	/*
29658 	 * We are sending the IPSEC_IN message also up. Refer
29659 	 * to comments above this function.
29660 	 * This is the SOCK_RAW, IPPROTO_SCTP case.
29661 	 */
29662 	(connp->conn_recv)(connp, mp, NULL);
29663 	CONN_DEC_REF(connp);
29664 }
29665 
29666 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
29667 {									\
29668 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
29669 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
29670 }
29671 /*
29672  * This function should be called only if all packet processing
29673  * including fragmentation is complete. Callers of this function
29674  * must set mp->b_prev to one of these values:
29675  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
29676  * prior to handing over the mp as first argument to this function.
29677  *
29678  * If the ire passed by caller is incomplete, this function
29679  * queues the packet and if necessary, sends ARP request and bails.
29680  * If the ire passed is fully resolved, we simply prepend
29681  * the link-layer header to the packet, do ipsec hw acceleration
29682  * work if necessary, and send the packet out on the wire.
29683  *
29684  * NOTE: IPsec will only call this function with fully resolved
29685  * ires if hw acceleration is involved.
29686  * TODO list :
29687  * 	a Handle M_MULTIDATA so that
29688  *	  tcp_multisend->tcp_multisend_data can
29689  *	  call ip_xmit_v4 directly
29690  *	b Handle post-ARP work for fragments so that
29691  *	  ip_wput_frag can call this function.
29692  */
29693 ipxmit_state_t
29694 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io, boolean_t flow_ctl_enabled)
29695 {
29696 	nce_t		*arpce;
29697 	queue_t		*q;
29698 	int		ill_index;
29699 	mblk_t		*nxt_mp, *first_mp;
29700 	boolean_t	xmit_drop = B_FALSE;
29701 	ip_proc_t	proc;
29702 	ill_t		*out_ill;
29703 	int		pkt_len;
29704 
29705 	arpce = ire->ire_nce;
29706 	ASSERT(arpce != NULL);
29707 
29708 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
29709 
29710 	mutex_enter(&arpce->nce_lock);
29711 	switch (arpce->nce_state) {
29712 	case ND_REACHABLE:
29713 		/* If there are other queued packets, queue this packet */
29714 		if (arpce->nce_qd_mp != NULL) {
29715 			if (mp != NULL)
29716 				nce_queue_mp_common(arpce, mp, B_FALSE);
29717 			mp = arpce->nce_qd_mp;
29718 		}
29719 		arpce->nce_qd_mp = NULL;
29720 		mutex_exit(&arpce->nce_lock);
29721 
29722 		/*
29723 		 * Flush the queue.  In the common case, where the
29724 		 * ARP is already resolved,  it will go through the
29725 		 * while loop only once.
29726 		 */
29727 		while (mp != NULL) {
29728 
29729 			nxt_mp = mp->b_next;
29730 			mp->b_next = NULL;
29731 			ASSERT(mp->b_datap->db_type != M_CTL);
29732 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
29733 			/*
29734 			 * This info is needed for IPQOS to do COS marking
29735 			 * in ip_wput_attach_llhdr->ip_process.
29736 			 */
29737 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
29738 			mp->b_prev = NULL;
29739 
29740 			/* set up ill index for outbound qos processing */
29741 			out_ill = ire_to_ill(ire);
29742 			ill_index = out_ill->ill_phyint->phyint_ifindex;
29743 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
29744 			    ill_index);
29745 			if (first_mp == NULL) {
29746 				xmit_drop = B_TRUE;
29747 				BUMP_MIB(out_ill->ill_ip_mib,
29748 				    ipIfStatsOutDiscards);
29749 				goto next_mp;
29750 			}
29751 			/* non-ipsec hw accel case */
29752 			if (io == NULL || !io->ipsec_out_accelerated) {
29753 				/* send it */
29754 				q = ire->ire_stq;
29755 				if (proc == IPP_FWD_OUT) {
29756 					UPDATE_IB_PKT_COUNT(ire);
29757 				} else {
29758 					UPDATE_OB_PKT_COUNT(ire);
29759 				}
29760 				ire->ire_last_used_time = lbolt;
29761 
29762 				if (flow_ctl_enabled || canputnext(q)) {
29763 					if (proc == IPP_FWD_OUT) {
29764 
29765 					BUMP_MIB(out_ill->ill_ip_mib,
29766 					    ipIfStatsHCOutForwDatagrams);
29767 
29768 					}
29769 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
29770 					    pkt_len);
29771 
29772 					putnext(q, first_mp);
29773 				} else {
29774 					BUMP_MIB(out_ill->ill_ip_mib,
29775 					    ipIfStatsOutDiscards);
29776 					xmit_drop = B_TRUE;
29777 					freemsg(first_mp);
29778 				}
29779 			} else {
29780 				/*
29781 				 * Safety Pup says: make sure this
29782 				 *  is going to the right interface!
29783 				 */
29784 				ill_t *ill1 =
29785 				    (ill_t *)ire->ire_stq->q_ptr;
29786 				int ifindex =
29787 				    ill1->ill_phyint->phyint_ifindex;
29788 				if (ifindex !=
29789 				    io->ipsec_out_capab_ill_index) {
29790 					xmit_drop = B_TRUE;
29791 					freemsg(mp);
29792 				} else {
29793 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
29794 					    pkt_len);
29795 					ipsec_hw_putnext(ire->ire_stq, mp);
29796 				}
29797 			}
29798 next_mp:
29799 			mp = nxt_mp;
29800 		} /* while (mp != NULL) */
29801 		if (xmit_drop)
29802 			return (SEND_FAILED);
29803 		else
29804 			return (SEND_PASSED);
29805 
29806 	case ND_INITIAL:
29807 	case ND_INCOMPLETE:
29808 
29809 		/*
29810 		 * While we do send off packets to dests that
29811 		 * use fully-resolved CGTP routes, we do not
29812 		 * handle unresolved CGTP routes.
29813 		 */
29814 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
29815 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
29816 
29817 		if (mp != NULL) {
29818 			/* queue the packet */
29819 			nce_queue_mp_common(arpce, mp, B_FALSE);
29820 		}
29821 
29822 		if (arpce->nce_state == ND_INCOMPLETE) {
29823 			mutex_exit(&arpce->nce_lock);
29824 			DTRACE_PROBE3(ip__xmit__incomplete,
29825 			    (ire_t *), ire, (mblk_t *), mp,
29826 			    (ipsec_out_t *), io);
29827 			return (LOOKUP_IN_PROGRESS);
29828 		}
29829 
29830 		arpce->nce_state = ND_INCOMPLETE;
29831 		mutex_exit(&arpce->nce_lock);
29832 		/*
29833 		 * Note that ire_add() (called from ire_forward())
29834 		 * holds a ref on the ire until ARP is completed.
29835 		 */
29836 
29837 		ire_arpresolve(ire, ire_to_ill(ire));
29838 		return (LOOKUP_IN_PROGRESS);
29839 	default:
29840 		ASSERT(0);
29841 		mutex_exit(&arpce->nce_lock);
29842 		return (LLHDR_RESLV_FAILED);
29843 	}
29844 }
29845 
29846 #undef	UPDATE_IP_MIB_OB_COUNTERS
29847 
29848 /*
29849  * Return B_TRUE if the buffers differ in length or content.
29850  * This is used for comparing extension header buffers.
29851  * Note that an extension header would be declared different
29852  * even if all that changed was the next header value in that header i.e.
29853  * what really changed is the next extension header.
29854  */
29855 boolean_t
29856 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
29857     uint_t blen)
29858 {
29859 	if (!b_valid)
29860 		blen = 0;
29861 
29862 	if (alen != blen)
29863 		return (B_TRUE);
29864 	if (alen == 0)
29865 		return (B_FALSE);	/* Both zero length */
29866 	return (bcmp(abuf, bbuf, alen));
29867 }
29868 
29869 /*
29870  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
29871  * Return B_FALSE if memory allocation fails - don't change any state!
29872  */
29873 boolean_t
29874 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29875     const void *src, uint_t srclen)
29876 {
29877 	void *dst;
29878 
29879 	if (!src_valid)
29880 		srclen = 0;
29881 
29882 	ASSERT(*dstlenp == 0);
29883 	if (src != NULL && srclen != 0) {
29884 		dst = mi_alloc(srclen, BPRI_MED);
29885 		if (dst == NULL)
29886 			return (B_FALSE);
29887 	} else {
29888 		dst = NULL;
29889 	}
29890 	if (*dstp != NULL)
29891 		mi_free(*dstp);
29892 	*dstp = dst;
29893 	*dstlenp = dst == NULL ? 0 : srclen;
29894 	return (B_TRUE);
29895 }
29896 
29897 /*
29898  * Replace what is in *dst, *dstlen with the source.
29899  * Assumes ip_allocbuf has already been called.
29900  */
29901 void
29902 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29903     const void *src, uint_t srclen)
29904 {
29905 	if (!src_valid)
29906 		srclen = 0;
29907 
29908 	ASSERT(*dstlenp == srclen);
29909 	if (src != NULL && srclen != 0)
29910 		bcopy(src, *dstp, srclen);
29911 }
29912 
29913 /*
29914  * Free the storage pointed to by the members of an ip6_pkt_t.
29915  */
29916 void
29917 ip6_pkt_free(ip6_pkt_t *ipp)
29918 {
29919 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
29920 
29921 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
29922 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
29923 		ipp->ipp_hopopts = NULL;
29924 		ipp->ipp_hopoptslen = 0;
29925 	}
29926 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
29927 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
29928 		ipp->ipp_rtdstopts = NULL;
29929 		ipp->ipp_rtdstoptslen = 0;
29930 	}
29931 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
29932 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
29933 		ipp->ipp_dstopts = NULL;
29934 		ipp->ipp_dstoptslen = 0;
29935 	}
29936 	if (ipp->ipp_fields & IPPF_RTHDR) {
29937 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
29938 		ipp->ipp_rthdr = NULL;
29939 		ipp->ipp_rthdrlen = 0;
29940 	}
29941 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
29942 	    IPPF_RTHDR);
29943 }
29944