xref: /illumos-gate/usr/src/uts/common/inet/ip/ip.c (revision 9b4e3ac25d882519cad3fc11f0c53b07f4e60536)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 /* Copyright (c) 1990 Mentat Inc. */
27 
28 #include <sys/types.h>
29 #include <sys/stream.h>
30 #include <sys/dlpi.h>
31 #include <sys/stropts.h>
32 #include <sys/sysmacros.h>
33 #include <sys/strsubr.h>
34 #include <sys/strlog.h>
35 #include <sys/strsun.h>
36 #include <sys/zone.h>
37 #define	_SUN_TPI_VERSION 2
38 #include <sys/tihdr.h>
39 #include <sys/xti_inet.h>
40 #include <sys/ddi.h>
41 #include <sys/cmn_err.h>
42 #include <sys/debug.h>
43 #include <sys/kobj.h>
44 #include <sys/modctl.h>
45 #include <sys/atomic.h>
46 #include <sys/policy.h>
47 #include <sys/priv.h>
48 #include <sys/taskq.h>
49 
50 #include <sys/systm.h>
51 #include <sys/param.h>
52 #include <sys/kmem.h>
53 #include <sys/sdt.h>
54 #include <sys/socket.h>
55 #include <sys/vtrace.h>
56 #include <sys/isa_defs.h>
57 #include <sys/mac.h>
58 #include <net/if.h>
59 #include <net/if_arp.h>
60 #include <net/route.h>
61 #include <sys/sockio.h>
62 #include <netinet/in.h>
63 #include <net/if_dl.h>
64 
65 #include <inet/common.h>
66 #include <inet/mi.h>
67 #include <inet/mib2.h>
68 #include <inet/nd.h>
69 #include <inet/arp.h>
70 #include <inet/snmpcom.h>
71 #include <inet/optcom.h>
72 #include <inet/kstatcom.h>
73 
74 #include <netinet/igmp_var.h>
75 #include <netinet/ip6.h>
76 #include <netinet/icmp6.h>
77 #include <netinet/sctp.h>
78 
79 #include <inet/ip.h>
80 #include <inet/ip_impl.h>
81 #include <inet/ip6.h>
82 #include <inet/ip6_asp.h>
83 #include <inet/tcp.h>
84 #include <inet/tcp_impl.h>
85 #include <inet/ip_multi.h>
86 #include <inet/ip_if.h>
87 #include <inet/ip_ire.h>
88 #include <inet/ip_ftable.h>
89 #include <inet/ip_rts.h>
90 #include <inet/ip_ndp.h>
91 #include <inet/ip_listutils.h>
92 #include <netinet/igmp.h>
93 #include <netinet/ip_mroute.h>
94 #include <inet/ipp_common.h>
95 
96 #include <net/pfkeyv2.h>
97 #include <inet/ipsec_info.h>
98 #include <inet/sadb.h>
99 #include <inet/ipsec_impl.h>
100 #include <sys/iphada.h>
101 #include <inet/tun.h>
102 #include <inet/ipdrop.h>
103 #include <inet/ip_netinfo.h>
104 
105 #include <sys/ethernet.h>
106 #include <net/if_types.h>
107 #include <sys/cpuvar.h>
108 
109 #include <ipp/ipp.h>
110 #include <ipp/ipp_impl.h>
111 #include <ipp/ipgpc/ipgpc.h>
112 
113 #include <sys/multidata.h>
114 #include <sys/pattr.h>
115 
116 #include <inet/ipclassifier.h>
117 #include <inet/sctp_ip.h>
118 #include <inet/sctp/sctp_impl.h>
119 #include <inet/udp_impl.h>
120 #include <inet/rawip_impl.h>
121 #include <inet/rts_impl.h>
122 
123 #include <sys/tsol/label.h>
124 #include <sys/tsol/tnet.h>
125 
126 #include <rpc/pmap_prot.h>
127 #include <sys/squeue_impl.h>
128 
129 /*
130  * Values for squeue switch:
131  * IP_SQUEUE_ENTER_NODRAIN: SQ_NODRAIN
132  * IP_SQUEUE_ENTER: SQ_PROCESS
133  * IP_SQUEUE_FILL: SQ_FILL
134  */
135 int ip_squeue_enter = 2;	/* Setable in /etc/system */
136 
137 int ip_squeue_flag;
138 #define	SET_BPREV_FLAG(x)	((mblk_t *)(uintptr_t)(x))
139 
140 /*
141  * Setable in /etc/system
142  */
143 int ip_poll_normal_ms = 100;
144 int ip_poll_normal_ticks = 0;
145 int ip_modclose_ackwait_ms = 3000;
146 
147 /*
148  * It would be nice to have these present only in DEBUG systems, but the
149  * current design of the global symbol checking logic requires them to be
150  * unconditionally present.
151  */
152 uint_t ip_thread_data;			/* TSD key for debug support */
153 krwlock_t ip_thread_rwlock;
154 list_t	ip_thread_list;
155 
156 /*
157  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
158  */
159 
160 struct listptr_s {
161 	mblk_t	*lp_head;	/* pointer to the head of the list */
162 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
163 };
164 
165 typedef struct listptr_s listptr_t;
166 
167 /*
168  * This is used by ip_snmp_get_mib2_ip_route_media and
169  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
170  */
171 typedef struct iproutedata_s {
172 	uint_t		ird_idx;
173 	listptr_t	ird_route;	/* ipRouteEntryTable */
174 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
175 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
176 } iproutedata_t;
177 
178 /*
179  * Cluster specific hooks. These should be NULL when booted as a non-cluster
180  */
181 
182 /*
183  * Hook functions to enable cluster networking
184  * On non-clustered systems these vectors must always be NULL.
185  *
186  * Hook function to Check ip specified ip address is a shared ip address
187  * in the cluster
188  *
189  */
190 int (*cl_inet_isclusterwide)(uint8_t protocol,
191     sa_family_t addr_family, uint8_t *laddrp) = NULL;
192 
193 /*
194  * Hook function to generate cluster wide ip fragment identifier
195  */
196 uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
197     uint8_t *laddrp, uint8_t *faddrp) = NULL;
198 
199 /*
200  * Hook function to generate cluster wide SPI.
201  */
202 void (*cl_inet_getspi)(uint8_t, uint8_t *, size_t) = NULL;
203 
204 /*
205  * Hook function to verify if the SPI is already utlized.
206  */
207 
208 int (*cl_inet_checkspi)(uint8_t, uint32_t) = NULL;
209 
210 /*
211  * Hook function to delete the SPI from the cluster wide repository.
212  */
213 
214 void (*cl_inet_deletespi)(uint8_t, uint32_t) = NULL;
215 
216 /*
217  * Hook function to inform the cluster when packet received on an IDLE SA
218  */
219 
220 void (*cl_inet_idlesa)(uint8_t, uint32_t, sa_family_t, in6_addr_t,
221     in6_addr_t) = NULL;
222 
223 /*
224  * Synchronization notes:
225  *
226  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
227  * MT level protection given by STREAMS. IP uses a combination of its own
228  * internal serialization mechanism and standard Solaris locking techniques.
229  * The internal serialization is per phyint (no IPMP) or per IPMP group.
230  * This is used to serialize plumbing operations, IPMP operations, certain
231  * multicast operations, most set ioctls, igmp/mld timers etc.
232  *
233  * Plumbing is a long sequence of operations involving message
234  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
235  * involved in plumbing operations. A natural model is to serialize these
236  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
237  * parallel without any interference. But various set ioctls on hme0 are best
238  * serialized. However if the system uses IPMP, the operations are easier if
239  * they are serialized on a per IPMP group basis since IPMP operations
240  * happen across ill's of a group. Thus the lowest common denominator is to
241  * serialize most set ioctls, multicast join/leave operations, IPMP operations
242  * igmp/mld timer operations, and processing of DLPI control messages received
243  * from drivers on a per IPMP group basis. If the system does not employ
244  * IPMP the serialization is on a per phyint basis. This serialization is
245  * provided by the ipsq_t and primitives operating on this. Details can
246  * be found in ip_if.c above the core primitives operating on ipsq_t.
247  *
248  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
249  * Simiarly lookup of an ire by a thread also returns a refheld ire.
250  * In addition ipif's and ill's referenced by the ire are also indirectly
251  * refheld. Thus no ipif or ill can vanish nor can critical parameters like
252  * the ipif's address or netmask change as long as an ipif is refheld
253  * directly or indirectly. For example an SIOCLIFADDR ioctl that changes the
254  * address of an ipif has to go through the ipsq_t. This ensures that only
255  * 1 such exclusive operation proceeds at any time on the ipif. It then
256  * deletes all ires associated with this ipif, and waits for all refcnts
257  * associated with this ipif to come down to zero. The address is changed
258  * only after the ipif has been quiesced. Then the ipif is brought up again.
259  * More details are described above the comment in ip_sioctl_flags.
260  *
261  * Packet processing is based mostly on IREs and are fully multi-threaded
262  * using standard Solaris MT techniques.
263  *
264  * There are explicit locks in IP to handle:
265  * - The ip_g_head list maintained by mi_open_link() and friends.
266  *
267  * - The reassembly data structures (one lock per hash bucket)
268  *
269  * - conn_lock is meant to protect conn_t fields. The fields actually
270  *   protected by conn_lock are documented in the conn_t definition.
271  *
272  * - ire_lock to protect some of the fields of the ire, IRE tables
273  *   (one lock per hash bucket). Refer to ip_ire.c for details.
274  *
275  * - ndp_g_lock and nce_lock for protecting NCEs.
276  *
277  * - ill_lock protects fields of the ill and ipif. Details in ip.h
278  *
279  * - ill_g_lock: This is a global reader/writer lock. Protects the following
280  *	* The AVL tree based global multi list of all ills.
281  *	* The linked list of all ipifs of an ill
282  *	* The <ill-ipsq> mapping
283  *	* The ipsq->ipsq_phyint_list threaded by phyint_ipsq_next
284  *	* The illgroup list threaded by ill_group_next.
285  *	* <ill-phyint> association
286  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
287  *   into an ill, changing the <ill-ipsq> mapping of an ill, insertion/deletion
288  *   of an ill into the illgrp list, changing the <ill-phyint> assoc of an ill
289  *   will all have to hold the ill_g_lock as writer for the actual duration
290  *   of the insertion/deletion/change. More details about the <ill-ipsq> mapping
291  *   may be found in the IPMP section.
292  *
293  * - ill_lock:  This is a per ill mutex.
294  *   It protects some members of the ill and is documented below.
295  *   It also protects the <ill-ipsq> mapping
296  *   It also protects the illgroup list threaded by ill_group_next.
297  *   It also protects the <ill-phyint> assoc.
298  *   It also protects the list of ipifs hanging off the ill.
299  *
300  * - ipsq_lock: This is a per ipsq_t mutex lock.
301  *   This protects all the other members of the ipsq struct except
302  *   ipsq_refs and ipsq_phyint_list which are protected by ill_g_lock
303  *
304  * - illgrp_lock: This is a per ill_group mutex lock.
305  *   The only thing it protects is the illgrp_ill_schednext member of ill_group
306  *   which dictates which is the next ill in an ill_group that is to be chosen
307  *   for sending outgoing packets, through creation of an IRE_CACHE that
308  *   references this ill.
309  *
310  * - phyint_lock: This is a per phyint mutex lock. Protects just the
311  *   phyint_flags
312  *
313  * - ip_g_nd_lock: This is a global reader/writer lock.
314  *   Any call to nd_load to load a new parameter to the ND table must hold the
315  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
316  *   as reader.
317  *
318  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
319  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
320  *   uniqueness check also done atomically.
321  *
322  * - ipsec_capab_ills_lock: This readers/writer lock protects the global
323  *   lists of IPsec capable ills (ipsec_capab_ills_{ah,esp}). It is taken
324  *   as a writer when adding or deleting elements from these lists, and
325  *   as a reader when walking these lists to send a SADB update to the
326  *   IPsec capable ills.
327  *
328  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
329  *   group list linked by ill_usesrc_grp_next. It also protects the
330  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
331  *   group is being added or deleted.  This lock is taken as a reader when
332  *   walking the list/group(eg: to get the number of members in a usesrc group).
333  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
334  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
335  *   example, it is not necessary to take this lock in the initial portion
336  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_groupname and
337  *   ip_sioctl_flags since the these operations are executed exclusively and
338  *   that ensures that the "usesrc group state" cannot change. The "usesrc
339  *   group state" change can happen only in the latter part of
340  *   ip_sioctl_slifusesrc and in ill_delete.
341  *
342  * Changing <ill-phyint>, <ill-ipsq>, <ill-illgroup> assocications.
343  *
344  * To change the <ill-phyint> association, the ill_g_lock must be held
345  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
346  * must be held.
347  *
348  * To change the <ill-ipsq> association the ill_g_lock must be held as writer
349  * and the ill_lock of the ill in question must be held.
350  *
351  * To change the <ill-illgroup> association the ill_g_lock must be held as
352  * writer and the ill_lock of the ill in question must be held.
353  *
354  * To add or delete an ipif from the list of ipifs hanging off the ill,
355  * ill_g_lock (writer) and ill_lock must be held and the thread must be
356  * a writer on the associated ipsq,.
357  *
358  * To add or delete an ill to the system, the ill_g_lock must be held as
359  * writer and the thread must be a writer on the associated ipsq.
360  *
361  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
362  * must be a writer on the associated ipsq.
363  *
364  * Lock hierarchy
365  *
366  * Some lock hierarchy scenarios are listed below.
367  *
368  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock
369  * ill_g_lock -> illgrp_lock -> ill_lock
370  * ill_g_lock -> ill_lock(s) -> phyint_lock
371  * ill_g_lock -> ndp_g_lock -> ill_lock -> nce_lock
372  * ill_g_lock -> ip_addr_avail_lock
373  * conn_lock -> irb_lock -> ill_lock -> ire_lock
374  * ill_g_lock -> ip_g_nd_lock
375  *
376  * When more than 1 ill lock is needed to be held, all ill lock addresses
377  * are sorted on address and locked starting from highest addressed lock
378  * downward.
379  *
380  * IPsec scenarios
381  *
382  * ipsa_lock -> ill_g_lock -> ill_lock
383  * ipsec_capab_ills_lock -> ill_g_lock -> ill_lock
384  * ipsec_capab_ills_lock -> ipsa_lock
385  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
386  *
387  * Trusted Solaris scenarios
388  *
389  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
390  * igsa_lock -> gcdb_lock
391  * gcgrp_rwlock -> ire_lock
392  * gcgrp_rwlock -> gcdb_lock
393  *
394  * squeue(sq_lock), flow related (ft_lock, fe_lock) locking
395  *
396  * cpu_lock --> ill_lock --> sqset_lock --> sq_lock
397  * sq_lock -> conn_lock -> QLOCK(q)
398  * ill_lock -> ft_lock -> fe_lock
399  *
400  * Routing/forwarding table locking notes:
401  *
402  * Lock acquisition order: Radix tree lock, irb_lock.
403  * Requirements:
404  * i.  Walker must not hold any locks during the walker callback.
405  * ii  Walker must not see a truncated tree during the walk because of any node
406  *     deletion.
407  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
408  *     in many places in the code to walk the irb list. Thus even if all the
409  *     ires in a bucket have been deleted, we still can't free the radix node
410  *     until the ires have actually been inactive'd (freed).
411  *
412  * Tree traversal - Need to hold the global tree lock in read mode.
413  * Before dropping the global tree lock, need to either increment the ire_refcnt
414  * to ensure that the radix node can't be deleted.
415  *
416  * Tree add - Need to hold the global tree lock in write mode to add a
417  * radix node. To prevent the node from being deleted, increment the
418  * irb_refcnt, after the node is added to the tree. The ire itself is
419  * added later while holding the irb_lock, but not the tree lock.
420  *
421  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
422  * All associated ires must be inactive (i.e. freed), and irb_refcnt
423  * must be zero.
424  *
425  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
426  * global tree lock (read mode) for traversal.
427  *
428  * IPsec notes :
429  *
430  * IP interacts with the IPsec code (AH/ESP) by tagging a M_CTL message
431  * in front of the actual packet. For outbound datagrams, the M_CTL
432  * contains a ipsec_out_t (defined in ipsec_info.h), which has the
433  * information used by the IPsec code for applying the right level of
434  * protection. The information initialized by IP in the ipsec_out_t
435  * is determined by the per-socket policy or global policy in the system.
436  * For inbound datagrams, the M_CTL contains a ipsec_in_t (defined in
437  * ipsec_info.h) which starts out with nothing in it. It gets filled
438  * with the right information if it goes through the AH/ESP code, which
439  * happens if the incoming packet is secure. The information initialized
440  * by AH/ESP, is later used by IP(during fanouts to ULP) to see whether
441  * the policy requirements needed by per-socket policy or global policy
442  * is met or not.
443  *
444  * If there is both per-socket policy (set using setsockopt) and there
445  * is also global policy match for the 5 tuples of the socket,
446  * ipsec_override_policy() makes the decision of which one to use.
447  *
448  * For fully connected sockets i.e dst, src [addr, port] is known,
449  * conn_policy_cached is set indicating that policy has been cached.
450  * conn_in_enforce_policy may or may not be set depending on whether
451  * there is a global policy match or per-socket policy match.
452  * Policy inheriting happpens in ip_bind during the ipa_conn_t bind.
453  * Once the right policy is set on the conn_t, policy cannot change for
454  * this socket. This makes life simpler for TCP (UDP ?) where
455  * re-transmissions go out with the same policy. For symmetry, policy
456  * is cached for fully connected UDP sockets also. Thus if policy is cached,
457  * it also implies that policy is latched i.e policy cannot change
458  * on these sockets. As we have the right policy on the conn, we don't
459  * have to lookup global policy for every outbound and inbound datagram
460  * and thus serving as an optimization. Note that a global policy change
461  * does not affect fully connected sockets if they have policy. If fully
462  * connected sockets did not have any policy associated with it, global
463  * policy change may affect them.
464  *
465  * IP Flow control notes:
466  *
467  * Non-TCP streams are flow controlled by IP. On the send side, if the packet
468  * cannot be sent down to the driver by IP, because of a canput failure, IP
469  * does a putq on the conn_wq. This will cause ip_wsrv to run on the conn_wq.
470  * ip_wsrv in turn, inserts the conn in a list of conn's that need to be drained
471  * when the flowcontrol condition subsides. Ultimately STREAMS backenables the
472  * ip_wsrv on the IP module, which in turn does a qenable of the conn_wq of the
473  * first conn in the list of conn's to be drained. ip_wsrv on this conn drains
474  * the queued messages, and removes the conn from the drain list, if all
475  * messages were drained. It also qenables the next conn in the drain list to
476  * continue the drain process.
477  *
478  * In reality the drain list is not a single list, but a configurable number
479  * of lists. The ip_wsrv on the IP module, qenables the first conn in each
480  * list. If the ip_wsrv of the next qenabled conn does not run, because the
481  * stream closes, ip_close takes responsibility to qenable the next conn in
482  * the drain list. The directly called ip_wput path always does a putq, if
483  * it cannot putnext. Thus synchronization problems are handled between
484  * ip_wsrv and ip_close. conn_drain_insert and conn_drain_tail are the only
485  * functions that manipulate this drain list. Furthermore conn_drain_insert
486  * is called only from ip_wsrv, and there can be only 1 instance of ip_wsrv
487  * running on a queue at any time. conn_drain_tail can be simultaneously called
488  * from both ip_wsrv and ip_close.
489  *
490  * IPQOS notes:
491  *
492  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
493  * and IPQoS modules. IPPF includes hooks in IP at different control points
494  * (callout positions) which direct packets to IPQoS modules for policy
495  * processing. Policies, if present, are global.
496  *
497  * The callout positions are located in the following paths:
498  *		o local_in (packets destined for this host)
499  *		o local_out (packets orginating from this host )
500  *		o fwd_in  (packets forwarded by this m/c - inbound)
501  *		o fwd_out (packets forwarded by this m/c - outbound)
502  * Hooks at these callout points can be enabled/disabled using the ndd variable
503  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
504  * By default all the callout positions are enabled.
505  *
506  * Outbound (local_out)
507  * Hooks are placed in ip_wput_ire and ipsec_out_process.
508  *
509  * Inbound (local_in)
510  * Hooks are placed in ip_proto_input, icmp_inbound, ip_fanout_proto and
511  * TCP and UDP fanout routines.
512  *
513  * Forwarding (in and out)
514  * Hooks are placed in ip_rput_forward.
515  *
516  * IP Policy Framework processing (IPPF processing)
517  * Policy processing for a packet is initiated by ip_process, which ascertains
518  * that the classifier (ipgpc) is loaded and configured, failing which the
519  * packet resumes normal processing in IP. If the clasifier is present, the
520  * packet is acted upon by one or more IPQoS modules (action instances), per
521  * filters configured in ipgpc and resumes normal IP processing thereafter.
522  * An action instance can drop a packet in course of its processing.
523  *
524  * A boolean variable, ip_policy, is used in all the fanout routines that can
525  * invoke ip_process for a packet. This variable indicates if the packet should
526  * to be sent for policy processing. The variable is set to B_TRUE by default,
527  * i.e. when the routines are invoked in the normal ip procesing path for a
528  * packet. The two exceptions being ip_wput_local and icmp_inbound_error_fanout;
529  * ip_policy is set to B_FALSE for all the routines called in these two
530  * functions because, in the former case,  we don't process loopback traffic
531  * currently while in the latter, the packets have already been processed in
532  * icmp_inbound.
533  *
534  * Zones notes:
535  *
536  * The partitioning rules for networking are as follows:
537  * 1) Packets coming from a zone must have a source address belonging to that
538  * zone.
539  * 2) Packets coming from a zone can only be sent on a physical interface on
540  * which the zone has an IP address.
541  * 3) Between two zones on the same machine, packet delivery is only allowed if
542  * there's a matching route for the destination and zone in the forwarding
543  * table.
544  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
545  * different zones can bind to the same port with the wildcard address
546  * (INADDR_ANY).
547  *
548  * The granularity of interface partitioning is at the logical interface level.
549  * Therefore, every zone has its own IP addresses, and incoming packets can be
550  * attributed to a zone unambiguously. A logical interface is placed into a zone
551  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
552  * structure. Rule (1) is implemented by modifying the source address selection
553  * algorithm so that the list of eligible addresses is filtered based on the
554  * sending process zone.
555  *
556  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
557  * across all zones, depending on their type. Here is the break-up:
558  *
559  * IRE type				Shared/exclusive
560  * --------				----------------
561  * IRE_BROADCAST			Exclusive
562  * IRE_DEFAULT (default routes)		Shared (*)
563  * IRE_LOCAL				Exclusive (x)
564  * IRE_LOOPBACK				Exclusive
565  * IRE_PREFIX (net routes)		Shared (*)
566  * IRE_CACHE				Exclusive
567  * IRE_IF_NORESOLVER (interface routes)	Exclusive
568  * IRE_IF_RESOLVER (interface routes)	Exclusive
569  * IRE_HOST (host routes)		Shared (*)
570  *
571  * (*) A zone can only use a default or off-subnet route if the gateway is
572  * directly reachable from the zone, that is, if the gateway's address matches
573  * one of the zone's logical interfaces.
574  *
575  * (x) IRE_LOCAL are handled a bit differently, since for all other entries
576  * in ire_ctable and IRE_INTERFACE, ire_src_addr is what can be used as source
577  * when sending packets using the IRE. For IRE_LOCAL ire_src_addr is the IP
578  * address of the zone itself (the destination). Since IRE_LOCAL is used
579  * for communication between zones, ip_wput_ire has special logic to set
580  * the right source address when sending using an IRE_LOCAL.
581  *
582  * Furthermore, when ip_restrict_interzone_loopback is set (the default),
583  * ire_cache_lookup restricts loopback using an IRE_LOCAL
584  * between zone to the case when L2 would have conceptually looped the packet
585  * back, i.e. the loopback which is required since neither Ethernet drivers
586  * nor Ethernet hardware loops them back. This is the case when the normal
587  * routes (ignoring IREs with different zoneids) would send out the packet on
588  * the same ill (or ill group) as the ill with which is IRE_LOCAL is
589  * associated.
590  *
591  * Multiple zones can share a common broadcast address; typically all zones
592  * share the 255.255.255.255 address. Incoming as well as locally originated
593  * broadcast packets must be dispatched to all the zones on the broadcast
594  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
595  * since some zones may not be on the 10.16.72/24 network. To handle this, each
596  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
597  * sent to every zone that has an IRE_BROADCAST entry for the destination
598  * address on the input ill, see conn_wantpacket().
599  *
600  * Applications in different zones can join the same multicast group address.
601  * For IPv4, group memberships are per-logical interface, so they're already
602  * inherently part of a zone. For IPv6, group memberships are per-physical
603  * interface, so we distinguish IPv6 group memberships based on group address,
604  * interface and zoneid. In both cases, received multicast packets are sent to
605  * every zone for which a group membership entry exists. On IPv6 we need to
606  * check that the target zone still has an address on the receiving physical
607  * interface; it could have been removed since the application issued the
608  * IPV6_JOIN_GROUP.
609  */
610 
611 /*
612  * Squeue Fanout flags:
613  *	0: No fanout.
614  *	1: Fanout across all squeues
615  */
616 boolean_t	ip_squeue_fanout = 0;
617 
618 /*
619  * Maximum dups allowed per packet.
620  */
621 uint_t ip_max_frag_dups = 10;
622 
623 #define	IS_SIMPLE_IPH(ipha)						\
624 	((ipha)->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION)
625 
626 /* RFC 1122 Conformance */
627 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
628 
629 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
630 
631 static int	conn_set_held_ipif(conn_t *, ipif_t **, ipif_t *);
632 
633 static int	ip_open(queue_t *q, dev_t *devp, int flag, int sflag,
634 		    cred_t *credp, boolean_t isv6);
635 static mblk_t	*ip_wput_attach_llhdr(mblk_t *, ire_t *, ip_proc_t, uint32_t,
636 		    ipha_t **);
637 
638 static void	icmp_frag_needed(queue_t *, mblk_t *, int, zoneid_t,
639 		    ip_stack_t *);
640 static void	icmp_inbound(queue_t *, mblk_t *, boolean_t, ill_t *, int,
641 		    uint32_t, boolean_t, boolean_t, ill_t *, zoneid_t);
642 static ipaddr_t	icmp_get_nexthop_addr(ipha_t *, ill_t *, zoneid_t, mblk_t *mp);
643 static boolean_t icmp_inbound_too_big(icmph_t *, ipha_t *, ill_t *, zoneid_t,
644 		    mblk_t *, int, ip_stack_t *);
645 static void	icmp_inbound_error_fanout(queue_t *, ill_t *, mblk_t *,
646 		    icmph_t *, ipha_t *, int, int, boolean_t, boolean_t,
647 		    ill_t *, zoneid_t);
648 static void	icmp_options_update(ipha_t *);
649 static void	icmp_param_problem(queue_t *, mblk_t *, uint8_t, zoneid_t,
650 		    ip_stack_t *);
651 static void	icmp_pkt(queue_t *, mblk_t *, void *, size_t, boolean_t,
652 		    zoneid_t zoneid, ip_stack_t *);
653 static mblk_t	*icmp_pkt_err_ok(mblk_t *, ip_stack_t *);
654 static void	icmp_redirect(ill_t *, mblk_t *);
655 static void	icmp_send_redirect(queue_t *, mblk_t *, ipaddr_t,
656 		    ip_stack_t *);
657 
658 static void	ip_arp_news(queue_t *, mblk_t *);
659 static boolean_t ip_bind_get_ire_v4(mblk_t **, ire_t *, iulp_t *, ip_stack_t *);
660 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
661 char		*ip_dot_addr(ipaddr_t, char *);
662 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
663 int		ip_close(queue_t *, int);
664 static char	*ip_dot_saddr(uchar_t *, char *);
665 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
666 		    boolean_t, boolean_t, ill_t *, zoneid_t);
667 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
668 		    boolean_t, boolean_t, zoneid_t);
669 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
670 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
671 static void	ip_lrput(queue_t *, mblk_t *);
672 ipaddr_t	ip_net_mask(ipaddr_t);
673 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, conn_t *, zoneid_t,
674 		    ip_stack_t *);
675 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
676 		    conn_t *, uint32_t, zoneid_t, ip_opt_info_t *);
677 char		*ip_nv_lookup(nv_t *, int);
678 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
679 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
680 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
681 static boolean_t	ip_param_register(IDP *ndp, ipparam_t *, size_t,
682     ipndp_t *, size_t);
683 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
684 void	ip_rput(queue_t *, mblk_t *);
685 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
686 		    void *dummy_arg);
687 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
688 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *,
689     ip_stack_t *);
690 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
691 			    ire_t *, ip_stack_t *);
692 static boolean_t	ip_rput_multimblk_ipoptions(queue_t *, ill_t *,
693 			    mblk_t *, ipha_t **, ipaddr_t *, ip_stack_t *);
694 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *,
695     ip_stack_t *);
696 static boolean_t ip_rput_fragment(queue_t *, mblk_t **, ipha_t *, uint32_t *,
697 		    uint16_t *);
698 int		ip_snmp_get(queue_t *, mblk_t *, int);
699 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *,
700 		    mib2_ipIfStatsEntry_t *, ip_stack_t *);
701 static mblk_t	*ip_snmp_get_mib2_ip_traffic_stats(queue_t *, mblk_t *,
702 		    ip_stack_t *);
703 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *, ip_stack_t *);
704 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *, ip_stack_t *ipst);
705 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *, ip_stack_t *ipst);
706 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *, ip_stack_t *ipst);
707 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *, ip_stack_t *ipst);
708 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *,
709 		    ip_stack_t *ipst);
710 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *,
711 		    ip_stack_t *ipst);
712 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *,
713 		    ip_stack_t *ipst);
714 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *,
715 		    ip_stack_t *ipst);
716 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *,
717 		    ip_stack_t *ipst);
718 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *,
719 		    ip_stack_t *ipst);
720 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *,
721 		    ip_stack_t *ipst);
722 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *,
723 		    ip_stack_t *ipst);
724 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *,
725 		    ip_stack_t *ipst);
726 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *,
727 		    ip_stack_t *ipst);
728 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
729 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
730 static int	ip_snmp_get2_v6_media(nce_t *, iproutedata_t *);
731 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
732 static boolean_t	ip_source_routed(ipha_t *, ip_stack_t *);
733 static boolean_t	ip_source_route_included(ipha_t *);
734 static void	ip_trash_ire_reclaim_stack(ip_stack_t *);
735 
736 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t,
737 		    zoneid_t, ip_stack_t *, conn_t *);
738 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int, ip_stack_t *);
739 static void	ip_wput_local_options(ipha_t *, ip_stack_t *);
740 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
741 		    zoneid_t, ip_stack_t *);
742 
743 static void	conn_drain_init(ip_stack_t *);
744 static void	conn_drain_fini(ip_stack_t *);
745 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
746 
747 static void	conn_walk_drain(ip_stack_t *);
748 static void	conn_walk_fanout_table(connf_t *, uint_t, pfv_t, void *,
749     zoneid_t);
750 
751 static void	*ip_stack_init(netstackid_t stackid, netstack_t *ns);
752 static void	ip_stack_shutdown(netstackid_t stackid, void *arg);
753 static void	ip_stack_fini(netstackid_t stackid, void *arg);
754 
755 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
756     zoneid_t);
757 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
758     void *dummy_arg);
759 
760 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
761 
762 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
763     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
764     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
765 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
766 
767 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
768 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
769     caddr_t, cred_t *);
770 extern int	ip_helper_stream_setup(queue_t *, dev_t *, int, int,
771     cred_t *, boolean_t);
772 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
773     caddr_t cp, cred_t *cr);
774 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
775     cred_t *);
776 static int	ipmp_hook_emulation_set(queue_t *, mblk_t *, char *, caddr_t,
777     cred_t *);
778 static int	ip_squeue_switch(int);
779 
780 static void	*ip_kstat_init(netstackid_t, ip_stack_t *);
781 static void	ip_kstat_fini(netstackid_t, kstat_t *);
782 static int	ip_kstat_update(kstat_t *kp, int rw);
783 static void	*icmp_kstat_init(netstackid_t);
784 static void	icmp_kstat_fini(netstackid_t, kstat_t *);
785 static int	icmp_kstat_update(kstat_t *kp, int rw);
786 static void	*ip_kstat2_init(netstackid_t, ip_stat_t *);
787 static void	ip_kstat2_fini(netstackid_t, kstat_t *);
788 
789 static int	ip_conn_report(queue_t *, mblk_t *, caddr_t, cred_t *);
790 
791 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
792     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
793 
794 static void	ip_rput_process_forward(queue_t *, mblk_t *, ire_t *,
795     ipha_t *, ill_t *, boolean_t, boolean_t);
796 
797 static void ipobs_init(ip_stack_t *);
798 static void ipobs_fini(ip_stack_t *);
799 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
800 
801 /* How long, in seconds, we allow frags to hang around. */
802 #define	IP_FRAG_TIMEOUT	15
803 
804 /*
805  * Threshold which determines whether MDT should be used when
806  * generating IP fragments; payload size must be greater than
807  * this threshold for MDT to take place.
808  */
809 #define	IP_WPUT_FRAG_MDT_MIN	32768
810 
811 /* Setable in /etc/system only */
812 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
813 
814 static long ip_rput_pullups;
815 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
816 
817 vmem_t *ip_minor_arena_sa; /* for minor nos. from INET_MIN_DEV+2 thru 2^^18-1 */
818 vmem_t *ip_minor_arena_la; /* for minor nos. from 2^^18 thru 2^^32-1 */
819 
820 int	ip_debug;
821 
822 #ifdef DEBUG
823 uint32_t ipsechw_debug = 0;
824 #endif
825 
826 /*
827  * Multirouting/CGTP stuff
828  */
829 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
830 
831 /*
832  * XXX following really should only be in a header. Would need more
833  * header and .c clean up first.
834  */
835 extern optdb_obj_t	ip_opt_obj;
836 
837 ulong_t ip_squeue_enter_unbound = 0;
838 
839 /*
840  * Named Dispatch Parameter Table.
841  * All of these are alterable, within the min/max values given, at run time.
842  */
843 static ipparam_t	lcl_param_arr[] = {
844 	/* min	max	value	name */
845 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
846 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
847 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
848 	{  0,	1,	0,	"ip_respond_to_timestamp"},
849 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
850 	{  0,	1,	1,	"ip_send_redirects"},
851 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
852 	{  0,	10,	0,	"ip_mrtdebug"},
853 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
854 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
855 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
856 	{  1,	255,	255,	"ip_def_ttl" },
857 	{  0,	1,	0,	"ip_forward_src_routed"},
858 	{  0,	256,	32,	"ip_wroff_extra" },
859 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
860 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
861 	{  0,	1,	1,	"ip_path_mtu_discovery" },
862 	{  0,	240,	30,	"ip_ignore_delete_time" },
863 	{  0,	1,	0,	"ip_ignore_redirect" },
864 	{  0,	1,	1,	"ip_output_queue" },
865 	{  1,	254,	1,	"ip_broadcast_ttl" },
866 	{  0,	99999,	100,	"ip_icmp_err_interval" },
867 	{  1,	99999,	10,	"ip_icmp_err_burst" },
868 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
869 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
870 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
871 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
872 	{  0,	1,	1,	"icmp_accept_clear_messages" },
873 	{  0,	1,	1,	"igmp_accept_clear_messages" },
874 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
875 				"ip_ndp_delay_first_probe_time"},
876 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
877 				"ip_ndp_max_unicast_solicit"},
878 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
879 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
880 	{  0,	1,	0,	"ip6_forward_src_routed"},
881 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
882 	{  0,	1,	1,	"ip6_send_redirects"},
883 	{  0,	1,	0,	"ip6_ignore_redirect" },
884 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
885 
886 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
887 
888 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
889 
890 	{  0,	1,	1,	"pim_accept_clear_messages" },
891 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
892 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
893 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
894 	{  0,	15,	0,	"ip_policy_mask" },
895 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
896 	{  0,	255,	1,	"ip_multirt_ttl" },
897 	{  0,	1,	1,	"ip_multidata_outbound" },
898 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
899 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
900 	{  0,	1000,	1,	"ip_max_temp_defend" },
901 	{  0,	1000,	3,	"ip_max_defend" },
902 	{  0,	999999,	30,	"ip_defend_interval" },
903 	{  0,	3600000, 300000, "ip_dup_recovery" },
904 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
905 	{  0,	1,	1,	"ip_lso_outbound" },
906 	{  IGMP_V1_ROUTER, IGMP_V3_ROUTER, IGMP_V3_ROUTER, "igmp_max_version" },
907 	{  MLD_V1_ROUTER, MLD_V2_ROUTER, MLD_V2_ROUTER, "mld_max_version" },
908 	{ 68,	65535,	576,	"ip_pmtu_min" },
909 #ifdef DEBUG
910 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
911 #else
912 	{  0,	0,	0,	"" },
913 #endif
914 };
915 
916 /*
917  * Extended NDP table
918  * The addresses for the first two are filled in to be ips_ip_g_forward
919  * and ips_ipv6_forward at init time.
920  */
921 static ipndp_t	lcl_ndp_arr[] = {
922 	/* getf			setf		data			name */
923 #define	IPNDP_IP_FORWARDING_OFFSET	0
924 	{  ip_param_generic_get,	ip_forward_set,	NULL,
925 	    "ip_forwarding" },
926 #define	IPNDP_IP6_FORWARDING_OFFSET	1
927 	{  ip_param_generic_get,	ip_forward_set,	NULL,
928 	    "ip6_forwarding" },
929 	{  ip_ill_report,	NULL,		NULL,
930 	    "ip_ill_status" },
931 	{  ip_ipif_report,	NULL,		NULL,
932 	    "ip_ipif_status" },
933 	{  ip_conn_report,	NULL,		NULL,
934 	    "ip_conn_status" },
935 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
936 	    "ip_rput_pullups" },
937 	{  ip_srcid_report,	NULL,		NULL,
938 	    "ip_srcid_status" },
939 	{ ip_param_generic_get, ip_input_proc_set,
940 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
941 	{ ip_param_generic_get, ip_int_set,
942 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
943 #define	IPNDP_CGTP_FILTER_OFFSET	9
944 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, NULL,
945 	    "ip_cgtp_filter" },
946 #define	IPNDP_IPMP_HOOK_OFFSET		10
947 	{  ip_param_generic_get, ipmp_hook_emulation_set, NULL,
948 	    "ipmp_hook_emulation" },
949 	{  ip_param_generic_get, ip_int_set, (caddr_t)&ip_debug,
950 	    "ip_debug" },
951 };
952 
953 /*
954  * Table of IP ioctls encoding the various properties of the ioctl and
955  * indexed based on the last byte of the ioctl command. Occasionally there
956  * is a clash, and there is more than 1 ioctl with the same last byte.
957  * In such a case 1 ioctl is encoded in the ndx table and the remaining
958  * ioctls are encoded in the misc table. An entry in the ndx table is
959  * retrieved by indexing on the last byte of the ioctl command and comparing
960  * the ioctl command with the value in the ndx table. In the event of a
961  * mismatch the misc table is then searched sequentially for the desired
962  * ioctl command.
963  *
964  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
965  */
966 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
967 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
968 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
969 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
970 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
971 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
972 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
973 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
974 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
975 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
976 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
977 
978 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
979 			MISC_CMD, ip_siocaddrt, NULL },
980 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
981 			MISC_CMD, ip_siocdelrt, NULL },
982 
983 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
984 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
985 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
986 			IF_CMD, ip_sioctl_get_addr, NULL },
987 
988 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
989 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
990 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
991 			IPI_GET_CMD | IPI_REPL,
992 			IF_CMD, ip_sioctl_get_dstaddr, NULL },
993 
994 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
995 			IPI_PRIV | IPI_WR | IPI_REPL,
996 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
997 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
998 			IPI_MODOK | IPI_GET_CMD | IPI_REPL,
999 			IF_CMD, ip_sioctl_get_flags, NULL },
1000 
1001 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1002 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1003 
1004 	/* copyin size cannot be coded for SIOCGIFCONF */
1005 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD,
1006 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1007 
1008 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1009 			IF_CMD, ip_sioctl_mtu, NULL },
1010 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1011 			IF_CMD, ip_sioctl_get_mtu, NULL },
1012 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
1013 			IPI_GET_CMD | IPI_REPL,
1014 			IF_CMD, ip_sioctl_get_brdaddr, NULL },
1015 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1016 			IF_CMD, ip_sioctl_brdaddr, NULL },
1017 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
1018 			IPI_GET_CMD | IPI_REPL,
1019 			IF_CMD, ip_sioctl_get_netmask, NULL },
1020 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1021 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1022 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1023 			IPI_GET_CMD | IPI_REPL,
1024 			IF_CMD, ip_sioctl_get_metric, NULL },
1025 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1026 			IF_CMD, ip_sioctl_metric, NULL },
1027 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1028 
1029 	/* See 166-168 below for extended SIOC*XARP ioctls */
1030 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV,
1031 			ARP_CMD, ip_sioctl_arp, NULL },
1032 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD | IPI_REPL,
1033 			ARP_CMD, ip_sioctl_arp, NULL },
1034 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV,
1035 			ARP_CMD, ip_sioctl_arp, NULL },
1036 
1037 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1038 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1039 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1040 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1041 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1042 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1043 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1044 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1045 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1046 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1047 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1048 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1049 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1050 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1051 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1052 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1053 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1054 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1055 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1056 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1057 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1058 
1059 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1060 			MISC_CMD, if_unitsel, if_unitsel_restart },
1061 
1062 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1063 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1064 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1065 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1066 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1067 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1068 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1069 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1070 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1071 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1072 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1073 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1074 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1075 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1076 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1077 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1078 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1079 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1080 
1081 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1082 			IPI_PRIV | IPI_WR | IPI_MODOK,
1083 			IF_CMD, ip_sioctl_sifname, NULL },
1084 
1085 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1086 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1087 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1088 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1089 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1090 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1091 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1092 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1093 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1094 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1095 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1096 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1097 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1098 
1099 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD | IPI_REPL,
1100 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1101 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1102 			IF_CMD, ip_sioctl_get_muxid, NULL },
1103 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1104 			IPI_PRIV | IPI_WR | IPI_REPL,
1105 			IF_CMD, ip_sioctl_muxid, NULL },
1106 
1107 	/* Both if and lif variants share same func */
1108 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1109 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1110 	/* Both if and lif variants share same func */
1111 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1112 			IPI_PRIV | IPI_WR | IPI_REPL,
1113 			IF_CMD, ip_sioctl_slifindex, NULL },
1114 
1115 	/* copyin size cannot be coded for SIOCGIFCONF */
1116 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD,
1117 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1118 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1119 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1120 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1121 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1122 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1123 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1124 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1125 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1126 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1127 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1128 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1129 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1130 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1131 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1132 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1133 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1134 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1135 
1136 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1137 			IPI_PRIV | IPI_WR | IPI_REPL,
1138 			LIF_CMD, ip_sioctl_removeif,
1139 			ip_sioctl_removeif_restart },
1140 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1141 			IPI_GET_CMD | IPI_PRIV | IPI_WR | IPI_REPL,
1142 			LIF_CMD, ip_sioctl_addif, NULL },
1143 #define	SIOCLIFADDR_NDX 112
1144 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1145 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1146 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1147 			IPI_GET_CMD | IPI_REPL,
1148 			LIF_CMD, ip_sioctl_get_addr, NULL },
1149 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1150 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1151 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1152 			IPI_GET_CMD | IPI_REPL,
1153 			LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1154 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1155 			IPI_PRIV | IPI_WR | IPI_REPL,
1156 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1157 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1158 			IPI_GET_CMD | IPI_MODOK | IPI_REPL,
1159 			LIF_CMD, ip_sioctl_get_flags, NULL },
1160 
1161 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1162 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1163 
1164 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1165 			ip_sioctl_get_lifconf, NULL },
1166 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1167 			LIF_CMD, ip_sioctl_mtu, NULL },
1168 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD | IPI_REPL,
1169 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1170 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1171 			IPI_GET_CMD | IPI_REPL,
1172 			LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1173 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1174 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1175 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1176 			IPI_GET_CMD | IPI_REPL,
1177 			LIF_CMD, ip_sioctl_get_netmask, NULL },
1178 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1179 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1180 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1181 			IPI_GET_CMD | IPI_REPL,
1182 			LIF_CMD, ip_sioctl_get_metric, NULL },
1183 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1184 			LIF_CMD, ip_sioctl_metric, NULL },
1185 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1186 			IPI_PRIV | IPI_WR | IPI_MODOK | IPI_REPL,
1187 			LIF_CMD, ip_sioctl_slifname,
1188 			ip_sioctl_slifname_restart },
1189 
1190 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD | IPI_REPL,
1191 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1192 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1193 			IPI_GET_CMD | IPI_REPL,
1194 			LIF_CMD, ip_sioctl_get_muxid, NULL },
1195 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1196 			IPI_PRIV | IPI_WR | IPI_REPL,
1197 			LIF_CMD, ip_sioctl_muxid, NULL },
1198 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1199 			IPI_GET_CMD | IPI_REPL,
1200 			LIF_CMD, ip_sioctl_get_lifindex, 0 },
1201 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1202 			IPI_PRIV | IPI_WR | IPI_REPL,
1203 			LIF_CMD, ip_sioctl_slifindex, 0 },
1204 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1205 			LIF_CMD, ip_sioctl_token, NULL },
1206 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1207 			IPI_GET_CMD | IPI_REPL,
1208 			LIF_CMD, ip_sioctl_get_token, NULL },
1209 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1210 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1211 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1212 			IPI_GET_CMD | IPI_REPL,
1213 			LIF_CMD, ip_sioctl_get_subnet, NULL },
1214 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1215 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1216 
1217 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1218 			IPI_GET_CMD | IPI_REPL,
1219 			LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1220 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1221 			LIF_CMD, ip_siocdelndp_v6, NULL },
1222 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1223 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1224 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1225 			LIF_CMD, ip_siocsetndp_v6, NULL },
1226 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1227 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1228 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1229 			MISC_CMD, ip_sioctl_tonlink, NULL },
1230 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1231 			MISC_CMD, ip_sioctl_tmysite, NULL },
1232 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), IPI_REPL,
1233 		    TUN_CMD, ip_sioctl_tunparam, NULL },
1234 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1235 		    IPI_PRIV | IPI_WR,
1236 		    TUN_CMD, ip_sioctl_tunparam, NULL },
1237 
1238 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1239 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1240 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1241 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1242 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1243 
1244 	/* 153 */ { SIOCLIFFAILOVER, sizeof (struct lifreq),
1245 			IPI_PRIV | IPI_WR | IPI_REPL,
1246 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1247 	/* 154 */ { SIOCLIFFAILBACK, sizeof (struct lifreq),
1248 			IPI_PRIV | IPI_WR | IPI_REPL,
1249 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1250 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1251 			IPI_PRIV | IPI_WR | IPI_REPL,
1252 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1253 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1254 			IPI_GET_CMD | IPI_REPL,
1255 			LIF_CMD, ip_sioctl_get_groupname, NULL },
1256 	/* 157 */ { SIOCGLIFOINDEX, sizeof (struct lifreq),
1257 			IPI_GET_CMD | IPI_REPL,
1258 			LIF_CMD, ip_sioctl_get_oindex, NULL },
1259 
1260 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1261 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1262 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1263 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1264 
1265 	/* 161 */ { SIOCSLIFOINDEX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1266 		    LIF_CMD, ip_sioctl_slifoindex, NULL },
1267 
1268 	/* These are handled in ip_sioctl_copyin_setup itself */
1269 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1270 			MISC_CMD, NULL, NULL },
1271 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1272 			MISC_CMD, NULL, NULL },
1273 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1274 
1275 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1276 			ip_sioctl_get_lifconf, NULL },
1277 
1278 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV,
1279 			XARP_CMD, ip_sioctl_arp, NULL },
1280 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD | IPI_REPL,
1281 			XARP_CMD, ip_sioctl_arp, NULL },
1282 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV,
1283 			XARP_CMD, ip_sioctl_arp, NULL },
1284 
1285 	/* SIOCPOPSOCKFS is not handled by IP */
1286 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1287 
1288 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1289 			IPI_GET_CMD | IPI_REPL,
1290 			LIF_CMD, ip_sioctl_get_lifzone, NULL },
1291 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1292 			IPI_PRIV | IPI_WR | IPI_REPL,
1293 			LIF_CMD, ip_sioctl_slifzone,
1294 			ip_sioctl_slifzone_restart },
1295 	/* 172-174 are SCTP ioctls and not handled by IP */
1296 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1297 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1298 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1299 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1300 			IPI_GET_CMD, LIF_CMD,
1301 			ip_sioctl_get_lifusesrc, 0 },
1302 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1303 			IPI_PRIV | IPI_WR,
1304 			LIF_CMD, ip_sioctl_slifusesrc,
1305 			NULL },
1306 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1307 			ip_sioctl_get_lifsrcof, NULL },
1308 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1309 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1310 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1311 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1312 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1313 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1314 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1315 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1316 	/* 182 */ { SIOCSIPMPFAILBACK, sizeof (int), IPI_PRIV, MISC_CMD,
1317 			ip_sioctl_set_ipmpfailback, NULL },
1318 	/* SIOCSENABLESDP is handled by SDP */
1319 	/* 183 */ { IPI_DONTCARE /* SIOCSENABLESDP */, 0, 0, 0, NULL, NULL },
1320 	/* 184 */ { IPI_DONTCARE /* SIOCSQPTR */, 0, 0, 0, NULL, NULL },
1321 };
1322 
1323 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1324 
1325 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1326 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1327 		IPI_GET_CMD | IPI_REPL, TUN_CMD, ip_sioctl_tunparam, NULL },
1328 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1329 		TUN_CMD, ip_sioctl_tunparam, NULL },
1330 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1331 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1332 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1333 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1334 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1335 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1336 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1337 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_REPL | IPI_GET_CMD,
1338 		MISC_CMD, mrt_ioctl},
1339 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_REPL | IPI_GET_CMD,
1340 		MISC_CMD, mrt_ioctl},
1341 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_REPL | IPI_GET_CMD,
1342 		MISC_CMD, mrt_ioctl}
1343 };
1344 
1345 int ip_misc_ioctl_count =
1346     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1347 
1348 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1349 					/* Settable in /etc/system */
1350 /* Defined in ip_ire.c */
1351 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1352 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1353 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1354 
1355 static nv_t	ire_nv_arr[] = {
1356 	{ IRE_BROADCAST, "BROADCAST" },
1357 	{ IRE_LOCAL, "LOCAL" },
1358 	{ IRE_LOOPBACK, "LOOPBACK" },
1359 	{ IRE_CACHE, "CACHE" },
1360 	{ IRE_DEFAULT, "DEFAULT" },
1361 	{ IRE_PREFIX, "PREFIX" },
1362 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1363 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1364 	{ IRE_HOST, "HOST" },
1365 	{ 0 }
1366 };
1367 
1368 nv_t	*ire_nv_tbl = ire_nv_arr;
1369 
1370 /* Simple ICMP IP Header Template */
1371 static ipha_t icmp_ipha = {
1372 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1373 };
1374 
1375 struct module_info ip_mod_info = {
1376 	IP_MOD_ID, IP_MOD_NAME, IP_MOD_MINPSZ, IP_MOD_MAXPSZ, IP_MOD_HIWAT,
1377 	IP_MOD_LOWAT
1378 };
1379 
1380 /*
1381  * Duplicate static symbols within a module confuses mdb; so we avoid the
1382  * problem by making the symbols here distinct from those in udp.c.
1383  */
1384 
1385 /*
1386  * Entry points for IP as a device and as a module.
1387  * FIXME: down the road we might want a separate module and driver qinit.
1388  * We have separate open functions for the /dev/ip and /dev/ip6 devices.
1389  */
1390 static struct qinit iprinitv4 = {
1391 	(pfi_t)ip_rput, NULL, ip_openv4, ip_close, NULL,
1392 	&ip_mod_info
1393 };
1394 
1395 struct qinit iprinitv6 = {
1396 	(pfi_t)ip_rput_v6, NULL, ip_openv6, ip_close, NULL,
1397 	&ip_mod_info
1398 };
1399 
1400 static struct qinit ipwinitv4 = {
1401 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1402 	&ip_mod_info
1403 };
1404 
1405 struct qinit ipwinitv6 = {
1406 	(pfi_t)ip_wput_v6, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1407 	&ip_mod_info
1408 };
1409 
1410 static struct qinit iplrinit = {
1411 	(pfi_t)ip_lrput, NULL, ip_openv4, ip_close, NULL,
1412 	&ip_mod_info
1413 };
1414 
1415 static struct qinit iplwinit = {
1416 	(pfi_t)ip_lwput, NULL, NULL, NULL, NULL,
1417 	&ip_mod_info
1418 };
1419 
1420 /* For AF_INET aka /dev/ip */
1421 struct streamtab ipinfov4 = {
1422 	&iprinitv4, &ipwinitv4, &iplrinit, &iplwinit
1423 };
1424 
1425 /* For AF_INET6 aka /dev/ip6 */
1426 struct streamtab ipinfov6 = {
1427 	&iprinitv6, &ipwinitv6, &iplrinit, &iplwinit
1428 };
1429 
1430 #ifdef	DEBUG
1431 static boolean_t skip_sctp_cksum = B_FALSE;
1432 #endif
1433 
1434 /*
1435  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1436  * ip_rput_v6(), ip_output(), etc.  If the message
1437  * block already has a M_CTL at the front of it, then simply set the zoneid
1438  * appropriately.
1439  */
1440 mblk_t *
1441 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid, ip_stack_t *ipst)
1442 {
1443 	mblk_t		*first_mp;
1444 	ipsec_out_t	*io;
1445 
1446 	ASSERT(zoneid != ALL_ZONES);
1447 	if (mp->b_datap->db_type == M_CTL) {
1448 		io = (ipsec_out_t *)mp->b_rptr;
1449 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1450 		io->ipsec_out_zoneid = zoneid;
1451 		return (mp);
1452 	}
1453 
1454 	first_mp = ipsec_alloc_ipsec_out(ipst->ips_netstack);
1455 	if (first_mp == NULL)
1456 		return (NULL);
1457 	io = (ipsec_out_t *)first_mp->b_rptr;
1458 	/* This is not a secure packet */
1459 	io->ipsec_out_secure = B_FALSE;
1460 	io->ipsec_out_zoneid = zoneid;
1461 	first_mp->b_cont = mp;
1462 	return (first_mp);
1463 }
1464 
1465 /*
1466  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1467  */
1468 mblk_t *
1469 ip_copymsg(mblk_t *mp)
1470 {
1471 	mblk_t *nmp;
1472 	ipsec_info_t *in;
1473 
1474 	if (mp->b_datap->db_type != M_CTL)
1475 		return (copymsg(mp));
1476 
1477 	in = (ipsec_info_t *)mp->b_rptr;
1478 
1479 	/*
1480 	 * Note that M_CTL is also used for delivering ICMP error messages
1481 	 * upstream to transport layers.
1482 	 */
1483 	if (in->ipsec_info_type != IPSEC_OUT &&
1484 	    in->ipsec_info_type != IPSEC_IN)
1485 		return (copymsg(mp));
1486 
1487 	nmp = copymsg(mp->b_cont);
1488 
1489 	if (in->ipsec_info_type == IPSEC_OUT) {
1490 		return (ipsec_out_tag(mp, nmp,
1491 		    ((ipsec_out_t *)in)->ipsec_out_ns));
1492 	} else {
1493 		return (ipsec_in_tag(mp, nmp,
1494 		    ((ipsec_in_t *)in)->ipsec_in_ns));
1495 	}
1496 }
1497 
1498 /* Generate an ICMP fragmentation needed message. */
1499 static void
1500 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid,
1501     ip_stack_t *ipst)
1502 {
1503 	icmph_t	icmph;
1504 	mblk_t *first_mp;
1505 	boolean_t mctl_present;
1506 
1507 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1508 
1509 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
1510 		if (mctl_present)
1511 			freeb(first_mp);
1512 		return;
1513 	}
1514 
1515 	bzero(&icmph, sizeof (icmph_t));
1516 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1517 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1518 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1519 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1520 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1521 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
1522 	    ipst);
1523 }
1524 
1525 /*
1526  * icmp_inbound deals with ICMP messages in the following ways.
1527  *
1528  * 1) It needs to send a reply back and possibly delivering it
1529  *    to the "interested" upper clients.
1530  * 2) It needs to send it to the upper clients only.
1531  * 3) It needs to change some values in IP only.
1532  * 4) It needs to change some values in IP and upper layers e.g TCP.
1533  *
1534  * We need to accomodate icmp messages coming in clear until we get
1535  * everything secure from the wire. If icmp_accept_clear_messages
1536  * is zero we check with the global policy and act accordingly. If
1537  * it is non-zero, we accept the message without any checks. But
1538  * *this does not mean* that this will be delivered to the upper
1539  * clients. By accepting we might send replies back, change our MTU
1540  * value etc. but delivery to the ULP/clients depends on their policy
1541  * dispositions.
1542  *
1543  * We handle the above 4 cases in the context of IPsec in the
1544  * following way :
1545  *
1546  * 1) Send the reply back in the same way as the request came in.
1547  *    If it came in encrypted, it goes out encrypted. If it came in
1548  *    clear, it goes out in clear. Thus, this will prevent chosen
1549  *    plain text attack.
1550  * 2) The client may or may not expect things to come in secure.
1551  *    If it comes in secure, the policy constraints are checked
1552  *    before delivering it to the upper layers. If it comes in
1553  *    clear, ipsec_inbound_accept_clear will decide whether to
1554  *    accept this in clear or not. In both the cases, if the returned
1555  *    message (IP header + 8 bytes) that caused the icmp message has
1556  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1557  *    sending up. If there are only 8 bytes of returned message, then
1558  *    upper client will not be notified.
1559  * 3) Check with global policy to see whether it matches the constaints.
1560  *    But this will be done only if icmp_accept_messages_in_clear is
1561  *    zero.
1562  * 4) If we need to change both in IP and ULP, then the decision taken
1563  *    while affecting the values in IP and while delivering up to TCP
1564  *    should be the same.
1565  *
1566  * 	There are two cases.
1567  *
1568  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1569  *	   failed), we will not deliver it to the ULP, even though they
1570  *	   are *willing* to accept in *clear*. This is fine as our global
1571  *	   disposition to icmp messages asks us reject the datagram.
1572  *
1573  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1574  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1575  *	   to deliver it to ULP (policy failed), it can lead to
1576  *	   consistency problems. The cases known at this time are
1577  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1578  *	   values :
1579  *
1580  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1581  *	     and Upper layer rejects. Then the communication will
1582  *	     come to a stop. This is solved by making similar decisions
1583  *	     at both levels. Currently, when we are unable to deliver
1584  *	     to the Upper Layer (due to policy failures) while IP has
1585  *	     adjusted ire_max_frag, the next outbound datagram would
1586  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1587  *	     will be with the right level of protection. Thus the right
1588  *	     value will be communicated even if we are not able to
1589  *	     communicate when we get from the wire initially. But this
1590  *	     assumes there would be at least one outbound datagram after
1591  *	     IP has adjusted its ire_max_frag value. To make things
1592  *	     simpler, we accept in clear after the validation of
1593  *	     AH/ESP headers.
1594  *
1595  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1596  *	     upper layer depending on the level of protection the upper
1597  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1598  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1599  *	     should be accepted in clear when the Upper layer expects secure.
1600  *	     Thus the communication may get aborted by some bad ICMP
1601  *	     packets.
1602  *
1603  * IPQoS Notes:
1604  * The only instance when a packet is sent for processing is when there
1605  * isn't an ICMP client and if we are interested in it.
1606  * If there is a client, IPPF processing will take place in the
1607  * ip_fanout_proto routine.
1608  *
1609  * Zones notes:
1610  * The packet is only processed in the context of the specified zone: typically
1611  * only this zone will reply to an echo request, and only interested clients in
1612  * this zone will receive a copy of the packet. This means that the caller must
1613  * call icmp_inbound() for each relevant zone.
1614  */
1615 static void
1616 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1617     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1618     ill_t *recv_ill, zoneid_t zoneid)
1619 {
1620 	icmph_t	*icmph;
1621 	ipha_t	*ipha;
1622 	int	iph_hdr_length;
1623 	int	hdr_length;
1624 	boolean_t	interested;
1625 	uint32_t	ts;
1626 	uchar_t	*wptr;
1627 	ipif_t	*ipif;
1628 	mblk_t *first_mp;
1629 	ipsec_in_t *ii;
1630 	ire_t *src_ire;
1631 	boolean_t onlink;
1632 	timestruc_t now;
1633 	uint32_t ill_index;
1634 	ip_stack_t *ipst;
1635 
1636 	ASSERT(ill != NULL);
1637 	ipst = ill->ill_ipst;
1638 
1639 	first_mp = mp;
1640 	if (mctl_present) {
1641 		mp = first_mp->b_cont;
1642 		ASSERT(mp != NULL);
1643 	}
1644 
1645 	ipha = (ipha_t *)mp->b_rptr;
1646 	if (ipst->ips_icmp_accept_clear_messages == 0) {
1647 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1648 		    ipha, NULL, mctl_present, ipst->ips_netstack);
1649 		if (first_mp == NULL)
1650 			return;
1651 	}
1652 
1653 	/*
1654 	 * On a labeled system, we have to check whether the zone itself is
1655 	 * permitted to receive raw traffic.
1656 	 */
1657 	if (is_system_labeled()) {
1658 		if (zoneid == ALL_ZONES)
1659 			zoneid = tsol_packet_to_zoneid(mp);
1660 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1661 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1662 			    zoneid));
1663 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1664 			freemsg(first_mp);
1665 			return;
1666 		}
1667 	}
1668 
1669 	/*
1670 	 * We have accepted the ICMP message. It means that we will
1671 	 * respond to the packet if needed. It may not be delivered
1672 	 * to the upper client depending on the policy constraints
1673 	 * and the disposition in ipsec_inbound_accept_clear.
1674 	 */
1675 
1676 	ASSERT(ill != NULL);
1677 
1678 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1679 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1680 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1681 		/* Last chance to get real. */
1682 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1683 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1684 			freemsg(first_mp);
1685 			return;
1686 		}
1687 		/* Refresh iph following the pullup. */
1688 		ipha = (ipha_t *)mp->b_rptr;
1689 	}
1690 	/* ICMP header checksum, including checksum field, should be zero. */
1691 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1692 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1693 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInCksumErrs);
1694 		freemsg(first_mp);
1695 		return;
1696 	}
1697 	/* The IP header will always be a multiple of four bytes */
1698 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1699 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1700 	    icmph->icmph_code));
1701 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1702 	/* We will set "interested" to "true" if we want a copy */
1703 	interested = B_FALSE;
1704 	switch (icmph->icmph_type) {
1705 	case ICMP_ECHO_REPLY:
1706 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1707 		break;
1708 	case ICMP_DEST_UNREACHABLE:
1709 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1710 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1711 		interested = B_TRUE;	/* Pass up to transport */
1712 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1713 		break;
1714 	case ICMP_SOURCE_QUENCH:
1715 		interested = B_TRUE;	/* Pass up to transport */
1716 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1717 		break;
1718 	case ICMP_REDIRECT:
1719 		if (!ipst->ips_ip_ignore_redirect)
1720 			interested = B_TRUE;
1721 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1722 		break;
1723 	case ICMP_ECHO_REQUEST:
1724 		/*
1725 		 * Whether to respond to echo requests that come in as IP
1726 		 * broadcasts or as IP multicast is subject to debate
1727 		 * (what isn't?).  We aim to please, you pick it.
1728 		 * Default is do it.
1729 		 */
1730 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1731 			/* unicast: always respond */
1732 			interested = B_TRUE;
1733 		} else if (CLASSD(ipha->ipha_dst)) {
1734 			/* multicast: respond based on tunable */
1735 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1736 		} else if (broadcast) {
1737 			/* broadcast: respond based on tunable */
1738 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1739 		}
1740 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1741 		break;
1742 	case ICMP_ROUTER_ADVERTISEMENT:
1743 	case ICMP_ROUTER_SOLICITATION:
1744 		break;
1745 	case ICMP_TIME_EXCEEDED:
1746 		interested = B_TRUE;	/* Pass up to transport */
1747 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1748 		break;
1749 	case ICMP_PARAM_PROBLEM:
1750 		interested = B_TRUE;	/* Pass up to transport */
1751 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1752 		break;
1753 	case ICMP_TIME_STAMP_REQUEST:
1754 		/* Response to Time Stamp Requests is local policy. */
1755 		if (ipst->ips_ip_g_resp_to_timestamp &&
1756 		    /* So is whether to respond if it was an IP broadcast. */
1757 		    (!broadcast || ipst->ips_ip_g_resp_to_timestamp_bcast)) {
1758 			int tstamp_len = 3 * sizeof (uint32_t);
1759 
1760 			if (wptr +  tstamp_len > mp->b_wptr) {
1761 				if (!pullupmsg(mp, wptr + tstamp_len -
1762 				    mp->b_rptr)) {
1763 					BUMP_MIB(ill->ill_ip_mib,
1764 					    ipIfStatsInDiscards);
1765 					freemsg(first_mp);
1766 					return;
1767 				}
1768 				/* Refresh ipha following the pullup. */
1769 				ipha = (ipha_t *)mp->b_rptr;
1770 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1771 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1772 			}
1773 			interested = B_TRUE;
1774 		}
1775 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1776 		break;
1777 	case ICMP_TIME_STAMP_REPLY:
1778 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1779 		break;
1780 	case ICMP_INFO_REQUEST:
1781 		/* Per RFC 1122 3.2.2.7, ignore this. */
1782 	case ICMP_INFO_REPLY:
1783 		break;
1784 	case ICMP_ADDRESS_MASK_REQUEST:
1785 		if ((ipst->ips_ip_respond_to_address_mask_broadcast ||
1786 		    !broadcast) &&
1787 		    /* TODO m_pullup of complete header? */
1788 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN) {
1789 			interested = B_TRUE;
1790 		}
1791 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1792 		break;
1793 	case ICMP_ADDRESS_MASK_REPLY:
1794 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1795 		break;
1796 	default:
1797 		interested = B_TRUE;	/* Pass up to transport */
1798 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1799 		break;
1800 	}
1801 	/* See if there is an ICMP client. */
1802 	if (ipst->ips_ipcl_proto_fanout[IPPROTO_ICMP].connf_head != NULL) {
1803 		/* If there is an ICMP client and we want one too, copy it. */
1804 		mblk_t *first_mp1;
1805 
1806 		if (!interested) {
1807 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1808 			    ip_policy, recv_ill, zoneid);
1809 			return;
1810 		}
1811 		first_mp1 = ip_copymsg(first_mp);
1812 		if (first_mp1 != NULL) {
1813 			ip_fanout_proto(q, first_mp1, ill, ipha,
1814 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1815 		}
1816 	} else if (!interested) {
1817 		freemsg(first_mp);
1818 		return;
1819 	} else {
1820 		/*
1821 		 * Initiate policy processing for this packet if ip_policy
1822 		 * is true.
1823 		 */
1824 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
1825 			ill_index = ill->ill_phyint->phyint_ifindex;
1826 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1827 			if (mp == NULL) {
1828 				if (mctl_present) {
1829 					freeb(first_mp);
1830 				}
1831 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1832 				return;
1833 			}
1834 		}
1835 	}
1836 	/* We want to do something with it. */
1837 	/* Check db_ref to make sure we can modify the packet. */
1838 	if (mp->b_datap->db_ref > 1) {
1839 		mblk_t	*first_mp1;
1840 
1841 		first_mp1 = ip_copymsg(first_mp);
1842 		freemsg(first_mp);
1843 		if (!first_mp1) {
1844 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1845 			return;
1846 		}
1847 		first_mp = first_mp1;
1848 		if (mctl_present) {
1849 			mp = first_mp->b_cont;
1850 			ASSERT(mp != NULL);
1851 		} else {
1852 			mp = first_mp;
1853 		}
1854 		ipha = (ipha_t *)mp->b_rptr;
1855 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1856 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1857 	}
1858 	switch (icmph->icmph_type) {
1859 	case ICMP_ADDRESS_MASK_REQUEST:
1860 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1861 		if (ipif == NULL) {
1862 			freemsg(first_mp);
1863 			return;
1864 		}
1865 		/*
1866 		 * outging interface must be IPv4
1867 		 */
1868 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1869 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1870 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1871 		ipif_refrele(ipif);
1872 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1873 		break;
1874 	case ICMP_ECHO_REQUEST:
1875 		icmph->icmph_type = ICMP_ECHO_REPLY;
1876 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1877 		break;
1878 	case ICMP_TIME_STAMP_REQUEST: {
1879 		uint32_t *tsp;
1880 
1881 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1882 		tsp = (uint32_t *)wptr;
1883 		tsp++;		/* Skip past 'originate time' */
1884 		/* Compute # of milliseconds since midnight */
1885 		gethrestime(&now);
1886 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1887 		    now.tv_nsec / (NANOSEC / MILLISEC);
1888 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1889 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1890 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1891 		break;
1892 	}
1893 	default:
1894 		ipha = (ipha_t *)&icmph[1];
1895 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1896 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1897 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1898 				freemsg(first_mp);
1899 				return;
1900 			}
1901 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1902 			ipha = (ipha_t *)&icmph[1];
1903 		}
1904 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1905 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1906 			freemsg(first_mp);
1907 			return;
1908 		}
1909 		hdr_length = IPH_HDR_LENGTH(ipha);
1910 		if (hdr_length < sizeof (ipha_t)) {
1911 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1912 			freemsg(first_mp);
1913 			return;
1914 		}
1915 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1916 			if (!pullupmsg(mp,
1917 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1918 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1919 				freemsg(first_mp);
1920 				return;
1921 			}
1922 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1923 			ipha = (ipha_t *)&icmph[1];
1924 		}
1925 		switch (icmph->icmph_type) {
1926 		case ICMP_REDIRECT:
1927 			/*
1928 			 * As there is no upper client to deliver, we don't
1929 			 * need the first_mp any more.
1930 			 */
1931 			if (mctl_present) {
1932 				freeb(first_mp);
1933 			}
1934 			icmp_redirect(ill, mp);
1935 			return;
1936 		case ICMP_DEST_UNREACHABLE:
1937 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1938 				if (!icmp_inbound_too_big(icmph, ipha, ill,
1939 				    zoneid, mp, iph_hdr_length, ipst)) {
1940 					freemsg(first_mp);
1941 					return;
1942 				}
1943 				/*
1944 				 * icmp_inbound_too_big() may alter mp.
1945 				 * Resynch ipha and icmph accordingly.
1946 				 */
1947 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1948 				ipha = (ipha_t *)&icmph[1];
1949 			}
1950 			/* FALLTHRU */
1951 		default :
1952 			/*
1953 			 * IPQoS notes: Since we have already done IPQoS
1954 			 * processing we don't want to do it again in
1955 			 * the fanout routines called by
1956 			 * icmp_inbound_error_fanout, hence the last
1957 			 * argument, ip_policy, is B_FALSE.
1958 			 */
1959 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
1960 			    ipha, iph_hdr_length, hdr_length, mctl_present,
1961 			    B_FALSE, recv_ill, zoneid);
1962 		}
1963 		return;
1964 	}
1965 	/* Send out an ICMP packet */
1966 	icmph->icmph_checksum = 0;
1967 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
1968 	if (broadcast || CLASSD(ipha->ipha_dst)) {
1969 		ipif_t	*ipif_chosen;
1970 		/*
1971 		 * Make it look like it was directed to us, so we don't look
1972 		 * like a fool with a broadcast or multicast source address.
1973 		 */
1974 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1975 		/*
1976 		 * Make sure that we haven't grabbed an interface that's DOWN.
1977 		 */
1978 		if (ipif != NULL) {
1979 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
1980 			    ipha->ipha_src, zoneid);
1981 			if (ipif_chosen != NULL) {
1982 				ipif_refrele(ipif);
1983 				ipif = ipif_chosen;
1984 			}
1985 		}
1986 		if (ipif == NULL) {
1987 			ip0dbg(("icmp_inbound: "
1988 			    "No source for broadcast/multicast:\n"
1989 			    "\tsrc 0x%x dst 0x%x ill %p "
1990 			    "ipif_lcl_addr 0x%x\n",
1991 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
1992 			    (void *)ill,
1993 			    ill->ill_ipif->ipif_lcl_addr));
1994 			freemsg(first_mp);
1995 			return;
1996 		}
1997 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1998 		ipha->ipha_dst = ipif->ipif_src_addr;
1999 		ipif_refrele(ipif);
2000 	}
2001 	/* Reset time to live. */
2002 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
2003 	{
2004 		/* Swap source and destination addresses */
2005 		ipaddr_t tmp;
2006 
2007 		tmp = ipha->ipha_src;
2008 		ipha->ipha_src = ipha->ipha_dst;
2009 		ipha->ipha_dst = tmp;
2010 	}
2011 	ipha->ipha_ident = 0;
2012 	if (!IS_SIMPLE_IPH(ipha))
2013 		icmp_options_update(ipha);
2014 
2015 	/*
2016 	 * ICMP echo replies should go out on the same interface
2017 	 * the request came on as probes used by in.mpathd for detecting
2018 	 * NIC failures are ECHO packets. We turn-off load spreading
2019 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
2020 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
2021 	 * function. This is in turn handled by ip_wput and ip_newroute
2022 	 * to make sure that the packet goes out on the interface it came
2023 	 * in on. If we don't turnoff load spreading, the packets might get
2024 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
2025 	 * to go out and in.mpathd would wrongly detect a failure or
2026 	 * mis-detect a NIC failure for link failure. As load spreading
2027 	 * can happen only if ill_group is not NULL, we do only for
2028 	 * that case and this does not affect the normal case.
2029 	 *
2030 	 * We turn off load spreading only on echo packets that came from
2031 	 * on-link hosts. If the interface route has been deleted, this will
2032 	 * not be enforced as we can't do much. For off-link hosts, as the
2033 	 * default routes in IPv4 does not typically have an ire_ipif
2034 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
2035 	 * Moreover, expecting a default route through this interface may
2036 	 * not be correct. We use ipha_dst because of the swap above.
2037 	 */
2038 	onlink = B_FALSE;
2039 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
2040 		/*
2041 		 * First, we need to make sure that it is not one of our
2042 		 * local addresses. If we set onlink when it is one of
2043 		 * our local addresses, we will end up creating IRE_CACHES
2044 		 * for one of our local addresses. Then, we will never
2045 		 * accept packets for them afterwards.
2046 		 */
2047 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2048 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2049 		if (src_ire == NULL) {
2050 			ipif = ipif_get_next_ipif(NULL, ill);
2051 			if (ipif == NULL) {
2052 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2053 				freemsg(mp);
2054 				return;
2055 			}
2056 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2057 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2058 			    NULL, MATCH_IRE_ILL | MATCH_IRE_TYPE, ipst);
2059 			ipif_refrele(ipif);
2060 			if (src_ire != NULL) {
2061 				onlink = B_TRUE;
2062 				ire_refrele(src_ire);
2063 			}
2064 		} else {
2065 			ire_refrele(src_ire);
2066 		}
2067 	}
2068 	if (!mctl_present) {
2069 		/*
2070 		 * This packet should go out the same way as it
2071 		 * came in i.e in clear. To make sure that global
2072 		 * policy will not be applied to this in ip_wput_ire,
2073 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2074 		 */
2075 		ASSERT(first_mp == mp);
2076 		first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2077 		if (first_mp == NULL) {
2078 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2079 			freemsg(mp);
2080 			return;
2081 		}
2082 		ii = (ipsec_in_t *)first_mp->b_rptr;
2083 
2084 		/* This is not a secure packet */
2085 		ii->ipsec_in_secure = B_FALSE;
2086 		if (onlink) {
2087 			ii->ipsec_in_attach_if = B_TRUE;
2088 			ii->ipsec_in_ill_index =
2089 			    ill->ill_phyint->phyint_ifindex;
2090 			ii->ipsec_in_rill_index =
2091 			    recv_ill->ill_phyint->phyint_ifindex;
2092 		}
2093 		first_mp->b_cont = mp;
2094 	} else if (onlink) {
2095 		ii = (ipsec_in_t *)first_mp->b_rptr;
2096 		ii->ipsec_in_attach_if = B_TRUE;
2097 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2098 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2099 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2100 	} else {
2101 		ii = (ipsec_in_t *)first_mp->b_rptr;
2102 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2103 	}
2104 	ii->ipsec_in_zoneid = zoneid;
2105 	ASSERT(zoneid != ALL_ZONES);
2106 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2107 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2108 		return;
2109 	}
2110 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2111 	put(WR(q), first_mp);
2112 }
2113 
2114 static ipaddr_t
2115 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2116 {
2117 	conn_t *connp;
2118 	connf_t *connfp;
2119 	ipaddr_t nexthop_addr = INADDR_ANY;
2120 	int hdr_length = IPH_HDR_LENGTH(ipha);
2121 	uint16_t *up;
2122 	uint32_t ports;
2123 	ip_stack_t *ipst = ill->ill_ipst;
2124 
2125 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2126 	switch (ipha->ipha_protocol) {
2127 		case IPPROTO_TCP:
2128 		{
2129 			tcph_t *tcph;
2130 
2131 			/* do a reverse lookup */
2132 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2133 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2134 			    TCPS_LISTEN, ipst);
2135 			break;
2136 		}
2137 		case IPPROTO_UDP:
2138 		{
2139 			uint32_t dstport, srcport;
2140 
2141 			((uint16_t *)&ports)[0] = up[1];
2142 			((uint16_t *)&ports)[1] = up[0];
2143 
2144 			/* Extract ports in net byte order */
2145 			dstport = htons(ntohl(ports) & 0xFFFF);
2146 			srcport = htons(ntohl(ports) >> 16);
2147 
2148 			connfp = &ipst->ips_ipcl_udp_fanout[
2149 			    IPCL_UDP_HASH(dstport, ipst)];
2150 			mutex_enter(&connfp->connf_lock);
2151 			connp = connfp->connf_head;
2152 
2153 			/* do a reverse lookup */
2154 			while ((connp != NULL) &&
2155 			    (!IPCL_UDP_MATCH(connp, dstport,
2156 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2157 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2158 				connp = connp->conn_next;
2159 			}
2160 			if (connp != NULL)
2161 				CONN_INC_REF(connp);
2162 			mutex_exit(&connfp->connf_lock);
2163 			break;
2164 		}
2165 		case IPPROTO_SCTP:
2166 		{
2167 			in6_addr_t map_src, map_dst;
2168 
2169 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2170 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2171 			((uint16_t *)&ports)[0] = up[1];
2172 			((uint16_t *)&ports)[1] = up[0];
2173 
2174 			connp = sctp_find_conn(&map_src, &map_dst, ports,
2175 			    zoneid, ipst->ips_netstack->netstack_sctp);
2176 			if (connp == NULL) {
2177 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2178 				    zoneid, ports, ipha, ipst);
2179 			} else {
2180 				CONN_INC_REF(connp);
2181 				SCTP_REFRELE(CONN2SCTP(connp));
2182 			}
2183 			break;
2184 		}
2185 		default:
2186 		{
2187 			ipha_t ripha;
2188 
2189 			ripha.ipha_src = ipha->ipha_dst;
2190 			ripha.ipha_dst = ipha->ipha_src;
2191 			ripha.ipha_protocol = ipha->ipha_protocol;
2192 
2193 			connfp = &ipst->ips_ipcl_proto_fanout[
2194 			    ipha->ipha_protocol];
2195 			mutex_enter(&connfp->connf_lock);
2196 			connp = connfp->connf_head;
2197 			for (connp = connfp->connf_head; connp != NULL;
2198 			    connp = connp->conn_next) {
2199 				if (IPCL_PROTO_MATCH(connp,
2200 				    ipha->ipha_protocol, &ripha, ill,
2201 				    0, zoneid)) {
2202 					CONN_INC_REF(connp);
2203 					break;
2204 				}
2205 			}
2206 			mutex_exit(&connfp->connf_lock);
2207 		}
2208 	}
2209 	if (connp != NULL) {
2210 		if (connp->conn_nexthop_set)
2211 			nexthop_addr = connp->conn_nexthop_v4;
2212 		CONN_DEC_REF(connp);
2213 	}
2214 	return (nexthop_addr);
2215 }
2216 
2217 /* Table from RFC 1191 */
2218 static int icmp_frag_size_table[] =
2219 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2220 
2221 /*
2222  * Process received ICMP Packet too big.
2223  * After updating any IRE it does the fanout to any matching transport streams.
2224  * Assumes the message has been pulled up till the IP header that caused
2225  * the error.
2226  *
2227  * Returns B_FALSE on failure and B_TRUE on success.
2228  */
2229 static boolean_t
2230 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2231     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length,
2232     ip_stack_t *ipst)
2233 {
2234 	ire_t	*ire, *first_ire;
2235 	int	mtu, orig_mtu;
2236 	int	hdr_length;
2237 	ipaddr_t nexthop_addr;
2238 	boolean_t disable_pmtud;
2239 
2240 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2241 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2242 	ASSERT(ill != NULL);
2243 
2244 	hdr_length = IPH_HDR_LENGTH(ipha);
2245 
2246 	/* Drop if the original packet contained a source route */
2247 	if (ip_source_route_included(ipha)) {
2248 		return (B_FALSE);
2249 	}
2250 	/*
2251 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2252 	 * header.
2253 	 */
2254 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2255 	    mp->b_wptr) {
2256 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2257 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2258 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2259 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2260 			return (B_FALSE);
2261 		}
2262 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2263 		ipha = (ipha_t *)&icmph[1];
2264 	}
2265 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2266 	if (nexthop_addr != INADDR_ANY) {
2267 		/* nexthop set */
2268 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2269 		    nexthop_addr, 0, NULL, ALL_ZONES, MBLK_GETLABEL(mp),
2270 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW, ipst);
2271 	} else {
2272 		/* nexthop not set */
2273 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2274 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2275 	}
2276 
2277 	if (!first_ire) {
2278 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2279 		    ntohl(ipha->ipha_dst)));
2280 		return (B_FALSE);
2281 	}
2282 
2283 	/* Check for MTU discovery advice as described in RFC 1191 */
2284 	mtu = ntohs(icmph->icmph_du_mtu);
2285 	orig_mtu = mtu;
2286 	disable_pmtud = B_FALSE;
2287 
2288 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2289 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2290 	    ire = ire->ire_next) {
2291 		/*
2292 		 * Look for the connection to which this ICMP message is
2293 		 * directed. If it has the IP_NEXTHOP option set, then the
2294 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2295 		 * option. Else the search is limited to regular IREs.
2296 		 */
2297 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2298 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2299 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2300 		    (nexthop_addr != INADDR_ANY)))
2301 			continue;
2302 
2303 		mutex_enter(&ire->ire_lock);
2304 		if (icmph->icmph_du_zero != 0 || mtu < ipst->ips_ip_pmtu_min) {
2305 			uint32_t length;
2306 			int	i;
2307 
2308 			/*
2309 			 * Use the table from RFC 1191 to figure out
2310 			 * the next "plateau" based on the length in
2311 			 * the original IP packet.
2312 			 */
2313 			length = ntohs(ipha->ipha_length);
2314 			DTRACE_PROBE2(ip4__pmtu__guess, ire_t *, ire,
2315 			    uint32_t, length);
2316 			if (ire->ire_max_frag <= length &&
2317 			    ire->ire_max_frag >= length - hdr_length) {
2318 				/*
2319 				 * Handle broken BSD 4.2 systems that
2320 				 * return the wrong iph_length in ICMP
2321 				 * errors.
2322 				 */
2323 				length -= hdr_length;
2324 			}
2325 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2326 				if (length > icmp_frag_size_table[i])
2327 					break;
2328 			}
2329 			if (i == A_CNT(icmp_frag_size_table)) {
2330 				/* Smaller than 68! */
2331 				disable_pmtud = B_TRUE;
2332 				mtu = ipst->ips_ip_pmtu_min;
2333 			} else {
2334 				mtu = icmp_frag_size_table[i];
2335 				if (mtu < ipst->ips_ip_pmtu_min) {
2336 					mtu = ipst->ips_ip_pmtu_min;
2337 					disable_pmtud = B_TRUE;
2338 				}
2339 			}
2340 			/* Fool the ULP into believing our guessed PMTU. */
2341 			icmph->icmph_du_zero = 0;
2342 			icmph->icmph_du_mtu = htons(mtu);
2343 		}
2344 		if (disable_pmtud)
2345 			ire->ire_frag_flag = 0;
2346 		/* Reduce the IRE max frag value as advised. */
2347 		ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2348 		mutex_exit(&ire->ire_lock);
2349 		DTRACE_PROBE4(ip4__pmtu__change, icmph_t *, icmph, ire_t *,
2350 		    ire, int, orig_mtu, int, mtu);
2351 	}
2352 	rw_exit(&first_ire->ire_bucket->irb_lock);
2353 	ire_refrele(first_ire);
2354 	return (B_TRUE);
2355 }
2356 
2357 /*
2358  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2359  * calls this function.
2360  */
2361 static mblk_t *
2362 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2363 {
2364 	ipha_t *ipha;
2365 	icmph_t *icmph;
2366 	ipha_t *in_ipha;
2367 	int length;
2368 
2369 	ASSERT(mp->b_datap->db_type == M_DATA);
2370 
2371 	/*
2372 	 * For Self-encapsulated packets, we added an extra IP header
2373 	 * without the options. Inner IP header is the one from which
2374 	 * the outer IP header was formed. Thus, we need to remove the
2375 	 * outer IP header. To do this, we pullup the whole message
2376 	 * and overlay whatever follows the outer IP header over the
2377 	 * outer IP header.
2378 	 */
2379 
2380 	if (!pullupmsg(mp, -1))
2381 		return (NULL);
2382 
2383 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2384 	ipha = (ipha_t *)&icmph[1];
2385 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2386 
2387 	/*
2388 	 * The length that we want to overlay is following the inner
2389 	 * IP header. Subtracting the IP header + icmp header + outer
2390 	 * IP header's length should give us the length that we want to
2391 	 * overlay.
2392 	 */
2393 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2394 	    hdr_length;
2395 	/*
2396 	 * Overlay whatever follows the inner header over the
2397 	 * outer header.
2398 	 */
2399 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2400 
2401 	/* Set the wptr to account for the outer header */
2402 	mp->b_wptr -= hdr_length;
2403 	return (mp);
2404 }
2405 
2406 /*
2407  * Try to pass the ICMP message upstream in case the ULP cares.
2408  *
2409  * If the packet that caused the ICMP error is secure, we send
2410  * it to AH/ESP to make sure that the attached packet has a
2411  * valid association. ipha in the code below points to the
2412  * IP header of the packet that caused the error.
2413  *
2414  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2415  * in the context of IPsec. Normally we tell the upper layer
2416  * whenever we send the ire (including ip_bind), the IPsec header
2417  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2418  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2419  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2420  * same thing. As TCP has the IPsec options size that needs to be
2421  * adjusted, we just pass the MTU unchanged.
2422  *
2423  * IFN could have been generated locally or by some router.
2424  *
2425  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2426  *	    This happens because IP adjusted its value of MTU on an
2427  *	    earlier IFN message and could not tell the upper layer,
2428  *	    the new adjusted value of MTU e.g. Packet was encrypted
2429  *	    or there was not enough information to fanout to upper
2430  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2431  *	    generates the IFN, where IPsec processing has *not* been
2432  *	    done.
2433  *
2434  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2435  *	    could have generated this. This happens because ire_max_frag
2436  *	    value in IP was set to a new value, while the IPsec processing
2437  *	    was being done and after we made the fragmentation check in
2438  *	    ip_wput_ire. Thus on return from IPsec processing,
2439  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2440  *	    and generates the IFN. As IPsec processing is over, we fanout
2441  *	    to AH/ESP to remove the header.
2442  *
2443  *	    In both these cases, ipsec_in_loopback will be set indicating
2444  *	    that IFN was generated locally.
2445  *
2446  * ROUTER : IFN could be secure or non-secure.
2447  *
2448  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2449  *	      packet in error has AH/ESP headers to validate the AH/ESP
2450  *	      headers. AH/ESP will verify whether there is a valid SA or
2451  *	      not and send it back. We will fanout again if we have more
2452  *	      data in the packet.
2453  *
2454  *	      If the packet in error does not have AH/ESP, we handle it
2455  *	      like any other case.
2456  *
2457  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2458  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2459  *	      for validation. AH/ESP will verify whether there is a
2460  *	      valid SA or not and send it back. We will fanout again if
2461  *	      we have more data in the packet.
2462  *
2463  *	      If the packet in error does not have AH/ESP, we handle it
2464  *	      like any other case.
2465  */
2466 static void
2467 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2468     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2469     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2470     zoneid_t zoneid)
2471 {
2472 	uint16_t *up;	/* Pointer to ports in ULP header */
2473 	uint32_t ports;	/* reversed ports for fanout */
2474 	ipha_t ripha;	/* With reversed addresses */
2475 	mblk_t *first_mp;
2476 	ipsec_in_t *ii;
2477 	tcph_t	*tcph;
2478 	conn_t	*connp;
2479 	ip_stack_t *ipst;
2480 
2481 	ASSERT(ill != NULL);
2482 
2483 	ASSERT(recv_ill != NULL);
2484 	ipst = recv_ill->ill_ipst;
2485 
2486 	first_mp = mp;
2487 	if (mctl_present) {
2488 		mp = first_mp->b_cont;
2489 		ASSERT(mp != NULL);
2490 
2491 		ii = (ipsec_in_t *)first_mp->b_rptr;
2492 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2493 	} else {
2494 		ii = NULL;
2495 	}
2496 
2497 	switch (ipha->ipha_protocol) {
2498 	case IPPROTO_UDP:
2499 		/*
2500 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2501 		 * transport header.
2502 		 */
2503 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2504 		    mp->b_wptr) {
2505 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2506 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2507 				goto discard_pkt;
2508 			}
2509 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2510 			ipha = (ipha_t *)&icmph[1];
2511 		}
2512 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2513 
2514 		/*
2515 		 * Attempt to find a client stream based on port.
2516 		 * Note that we do a reverse lookup since the header is
2517 		 * in the form we sent it out.
2518 		 * The ripha header is only used for the IP_UDP_MATCH and we
2519 		 * only set the src and dst addresses and protocol.
2520 		 */
2521 		ripha.ipha_src = ipha->ipha_dst;
2522 		ripha.ipha_dst = ipha->ipha_src;
2523 		ripha.ipha_protocol = ipha->ipha_protocol;
2524 		((uint16_t *)&ports)[0] = up[1];
2525 		((uint16_t *)&ports)[1] = up[0];
2526 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2527 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2528 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2529 		    icmph->icmph_type, icmph->icmph_code));
2530 
2531 		/* Have to change db_type after any pullupmsg */
2532 		DB_TYPE(mp) = M_CTL;
2533 
2534 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2535 		    mctl_present, ip_policy, recv_ill, zoneid);
2536 		return;
2537 
2538 	case IPPROTO_TCP:
2539 		/*
2540 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2541 		 * transport header.
2542 		 */
2543 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2544 		    mp->b_wptr) {
2545 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2546 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2547 				goto discard_pkt;
2548 			}
2549 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2550 			ipha = (ipha_t *)&icmph[1];
2551 		}
2552 		/*
2553 		 * Find a TCP client stream for this packet.
2554 		 * Note that we do a reverse lookup since the header is
2555 		 * in the form we sent it out.
2556 		 */
2557 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2558 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN,
2559 		    ipst);
2560 		if (connp == NULL)
2561 			goto discard_pkt;
2562 
2563 		/* Have to change db_type after any pullupmsg */
2564 		DB_TYPE(mp) = M_CTL;
2565 		SQUEUE_ENTER_ONE(connp->conn_sqp, first_mp, tcp_input, connp,
2566 		    SQ_FILL, SQTAG_TCP_INPUT_ICMP_ERR);
2567 		return;
2568 
2569 	case IPPROTO_SCTP:
2570 		/*
2571 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2572 		 * transport header.
2573 		 */
2574 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2575 		    mp->b_wptr) {
2576 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2577 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2578 				goto discard_pkt;
2579 			}
2580 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2581 			ipha = (ipha_t *)&icmph[1];
2582 		}
2583 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2584 		/*
2585 		 * Find a SCTP client stream for this packet.
2586 		 * Note that we do a reverse lookup since the header is
2587 		 * in the form we sent it out.
2588 		 * The ripha header is only used for the matching and we
2589 		 * only set the src and dst addresses, protocol, and version.
2590 		 */
2591 		ripha.ipha_src = ipha->ipha_dst;
2592 		ripha.ipha_dst = ipha->ipha_src;
2593 		ripha.ipha_protocol = ipha->ipha_protocol;
2594 		ripha.ipha_version_and_hdr_length =
2595 		    ipha->ipha_version_and_hdr_length;
2596 		((uint16_t *)&ports)[0] = up[1];
2597 		((uint16_t *)&ports)[1] = up[0];
2598 
2599 		/* Have to change db_type after any pullupmsg */
2600 		DB_TYPE(mp) = M_CTL;
2601 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2602 		    mctl_present, ip_policy, zoneid);
2603 		return;
2604 
2605 	case IPPROTO_ESP:
2606 	case IPPROTO_AH: {
2607 		int ipsec_rc;
2608 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
2609 
2610 		/*
2611 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2612 		 * We will re-use the IPSEC_IN if it is already present as
2613 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2614 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2615 		 * one and attach it in the front.
2616 		 */
2617 		if (ii != NULL) {
2618 			/*
2619 			 * ip_fanout_proto_again converts the ICMP errors
2620 			 * that come back from AH/ESP to M_DATA so that
2621 			 * if it is non-AH/ESP and we do a pullupmsg in
2622 			 * this function, it would work. Convert it back
2623 			 * to M_CTL before we send up as this is a ICMP
2624 			 * error. This could have been generated locally or
2625 			 * by some router. Validate the inner IPsec
2626 			 * headers.
2627 			 *
2628 			 * NOTE : ill_index is used by ip_fanout_proto_again
2629 			 * to locate the ill.
2630 			 */
2631 			ASSERT(ill != NULL);
2632 			ii->ipsec_in_ill_index =
2633 			    ill->ill_phyint->phyint_ifindex;
2634 			ii->ipsec_in_rill_index =
2635 			    recv_ill->ill_phyint->phyint_ifindex;
2636 			DB_TYPE(first_mp->b_cont) = M_CTL;
2637 		} else {
2638 			/*
2639 			 * IPSEC_IN is not present. We attach a ipsec_in
2640 			 * message and send up to IPsec for validating
2641 			 * and removing the IPsec headers. Clear
2642 			 * ipsec_in_secure so that when we return
2643 			 * from IPsec, we don't mistakenly think that this
2644 			 * is a secure packet came from the network.
2645 			 *
2646 			 * NOTE : ill_index is used by ip_fanout_proto_again
2647 			 * to locate the ill.
2648 			 */
2649 			ASSERT(first_mp == mp);
2650 			first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2651 			if (first_mp == NULL) {
2652 				freemsg(mp);
2653 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2654 				return;
2655 			}
2656 			ii = (ipsec_in_t *)first_mp->b_rptr;
2657 
2658 			/* This is not a secure packet */
2659 			ii->ipsec_in_secure = B_FALSE;
2660 			first_mp->b_cont = mp;
2661 			DB_TYPE(mp) = M_CTL;
2662 			ASSERT(ill != NULL);
2663 			ii->ipsec_in_ill_index =
2664 			    ill->ill_phyint->phyint_ifindex;
2665 			ii->ipsec_in_rill_index =
2666 			    recv_ill->ill_phyint->phyint_ifindex;
2667 		}
2668 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2669 
2670 		if (!ipsec_loaded(ipss)) {
2671 			ip_proto_not_sup(q, first_mp, 0, zoneid, ipst);
2672 			return;
2673 		}
2674 
2675 		if (ipha->ipha_protocol == IPPROTO_ESP)
2676 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2677 		else
2678 			ipsec_rc = ipsecah_icmp_error(first_mp);
2679 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2680 			return;
2681 
2682 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2683 		return;
2684 	}
2685 	default:
2686 		/*
2687 		 * The ripha header is only used for the lookup and we
2688 		 * only set the src and dst addresses and protocol.
2689 		 */
2690 		ripha.ipha_src = ipha->ipha_dst;
2691 		ripha.ipha_dst = ipha->ipha_src;
2692 		ripha.ipha_protocol = ipha->ipha_protocol;
2693 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2694 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2695 		    ntohl(ipha->ipha_dst),
2696 		    icmph->icmph_type, icmph->icmph_code));
2697 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2698 			ipha_t *in_ipha;
2699 
2700 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2701 			    mp->b_wptr) {
2702 				if (!pullupmsg(mp, (uchar_t *)ipha +
2703 				    hdr_length + sizeof (ipha_t) -
2704 				    mp->b_rptr)) {
2705 					goto discard_pkt;
2706 				}
2707 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2708 				ipha = (ipha_t *)&icmph[1];
2709 			}
2710 			/*
2711 			 * Caller has verified that length has to be
2712 			 * at least the size of IP header.
2713 			 */
2714 			ASSERT(hdr_length >= sizeof (ipha_t));
2715 			/*
2716 			 * Check the sanity of the inner IP header like
2717 			 * we did for the outer header.
2718 			 */
2719 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2720 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2721 				goto discard_pkt;
2722 			}
2723 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2724 				goto discard_pkt;
2725 			}
2726 			/* Check for Self-encapsulated tunnels */
2727 			if (in_ipha->ipha_src == ipha->ipha_src &&
2728 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2729 
2730 				mp = icmp_inbound_self_encap_error(mp,
2731 				    iph_hdr_length, hdr_length);
2732 				if (mp == NULL)
2733 					goto discard_pkt;
2734 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2735 				ipha = (ipha_t *)&icmph[1];
2736 				hdr_length = IPH_HDR_LENGTH(ipha);
2737 				/*
2738 				 * The packet in error is self-encapsualted.
2739 				 * And we are finding it further encapsulated
2740 				 * which we could not have possibly generated.
2741 				 */
2742 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2743 					goto discard_pkt;
2744 				}
2745 				icmp_inbound_error_fanout(q, ill, first_mp,
2746 				    icmph, ipha, iph_hdr_length, hdr_length,
2747 				    mctl_present, ip_policy, recv_ill, zoneid);
2748 				return;
2749 			}
2750 		}
2751 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2752 		    ipha->ipha_protocol == IPPROTO_IPV6) &&
2753 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2754 		    ii != NULL &&
2755 		    ii->ipsec_in_loopback &&
2756 		    ii->ipsec_in_secure) {
2757 			/*
2758 			 * For IP tunnels that get a looped-back
2759 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2760 			 * reported new MTU to take into account the IPsec
2761 			 * headers protecting this configured tunnel.
2762 			 *
2763 			 * This allows the tunnel module (tun.c) to blindly
2764 			 * accept the MTU reported in an ICMP "too big"
2765 			 * message.
2766 			 *
2767 			 * Non-looped back ICMP messages will just be
2768 			 * handled by the security protocols (if needed),
2769 			 * and the first subsequent packet will hit this
2770 			 * path.
2771 			 */
2772 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2773 			    ipsec_in_extra_length(first_mp));
2774 		}
2775 		/* Have to change db_type after any pullupmsg */
2776 		DB_TYPE(mp) = M_CTL;
2777 
2778 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2779 		    ip_policy, recv_ill, zoneid);
2780 		return;
2781 	}
2782 	/* NOTREACHED */
2783 discard_pkt:
2784 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2785 drop_pkt:;
2786 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2787 	freemsg(first_mp);
2788 }
2789 
2790 /*
2791  * Common IP options parser.
2792  *
2793  * Setup routine: fill in *optp with options-parsing state, then
2794  * tail-call ipoptp_next to return the first option.
2795  */
2796 uint8_t
2797 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2798 {
2799 	uint32_t totallen; /* total length of all options */
2800 
2801 	totallen = ipha->ipha_version_and_hdr_length -
2802 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2803 	totallen <<= 2;
2804 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2805 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2806 	optp->ipoptp_flags = 0;
2807 	return (ipoptp_next(optp));
2808 }
2809 
2810 /*
2811  * Common IP options parser: extract next option.
2812  */
2813 uint8_t
2814 ipoptp_next(ipoptp_t *optp)
2815 {
2816 	uint8_t *end = optp->ipoptp_end;
2817 	uint8_t *cur = optp->ipoptp_next;
2818 	uint8_t opt, len, pointer;
2819 
2820 	/*
2821 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2822 	 * has been corrupted.
2823 	 */
2824 	ASSERT(cur <= end);
2825 
2826 	if (cur == end)
2827 		return (IPOPT_EOL);
2828 
2829 	opt = cur[IPOPT_OPTVAL];
2830 
2831 	/*
2832 	 * Skip any NOP options.
2833 	 */
2834 	while (opt == IPOPT_NOP) {
2835 		cur++;
2836 		if (cur == end)
2837 			return (IPOPT_EOL);
2838 		opt = cur[IPOPT_OPTVAL];
2839 	}
2840 
2841 	if (opt == IPOPT_EOL)
2842 		return (IPOPT_EOL);
2843 
2844 	/*
2845 	 * Option requiring a length.
2846 	 */
2847 	if ((cur + 1) >= end) {
2848 		optp->ipoptp_flags |= IPOPTP_ERROR;
2849 		return (IPOPT_EOL);
2850 	}
2851 	len = cur[IPOPT_OLEN];
2852 	if (len < 2) {
2853 		optp->ipoptp_flags |= IPOPTP_ERROR;
2854 		return (IPOPT_EOL);
2855 	}
2856 	optp->ipoptp_cur = cur;
2857 	optp->ipoptp_len = len;
2858 	optp->ipoptp_next = cur + len;
2859 	if (cur + len > end) {
2860 		optp->ipoptp_flags |= IPOPTP_ERROR;
2861 		return (IPOPT_EOL);
2862 	}
2863 
2864 	/*
2865 	 * For the options which require a pointer field, make sure
2866 	 * its there, and make sure it points to either something
2867 	 * inside this option, or the end of the option.
2868 	 */
2869 	switch (opt) {
2870 	case IPOPT_RR:
2871 	case IPOPT_TS:
2872 	case IPOPT_LSRR:
2873 	case IPOPT_SSRR:
2874 		if (len <= IPOPT_OFFSET) {
2875 			optp->ipoptp_flags |= IPOPTP_ERROR;
2876 			return (opt);
2877 		}
2878 		pointer = cur[IPOPT_OFFSET];
2879 		if (pointer - 1 > len) {
2880 			optp->ipoptp_flags |= IPOPTP_ERROR;
2881 			return (opt);
2882 		}
2883 		break;
2884 	}
2885 
2886 	/*
2887 	 * Sanity check the pointer field based on the type of the
2888 	 * option.
2889 	 */
2890 	switch (opt) {
2891 	case IPOPT_RR:
2892 	case IPOPT_SSRR:
2893 	case IPOPT_LSRR:
2894 		if (pointer < IPOPT_MINOFF_SR)
2895 			optp->ipoptp_flags |= IPOPTP_ERROR;
2896 		break;
2897 	case IPOPT_TS:
2898 		if (pointer < IPOPT_MINOFF_IT)
2899 			optp->ipoptp_flags |= IPOPTP_ERROR;
2900 		/*
2901 		 * Note that the Internet Timestamp option also
2902 		 * contains two four bit fields (the Overflow field,
2903 		 * and the Flag field), which follow the pointer
2904 		 * field.  We don't need to check that these fields
2905 		 * fall within the length of the option because this
2906 		 * was implicitely done above.  We've checked that the
2907 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2908 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2909 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2910 		 */
2911 		ASSERT(len > IPOPT_POS_OV_FLG);
2912 		break;
2913 	}
2914 
2915 	return (opt);
2916 }
2917 
2918 /*
2919  * Use the outgoing IP header to create an IP_OPTIONS option the way
2920  * it was passed down from the application.
2921  */
2922 int
2923 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2924 {
2925 	ipoptp_t	opts;
2926 	const uchar_t	*opt;
2927 	uint8_t		optval;
2928 	uint8_t		optlen;
2929 	uint32_t	len = 0;
2930 	uchar_t	*buf1 = buf;
2931 
2932 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2933 	len += IP_ADDR_LEN;
2934 	bzero(buf1, IP_ADDR_LEN);
2935 
2936 	/*
2937 	 * OK to cast away const here, as we don't store through the returned
2938 	 * opts.ipoptp_cur pointer.
2939 	 */
2940 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
2941 	    optval != IPOPT_EOL;
2942 	    optval = ipoptp_next(&opts)) {
2943 		int	off;
2944 
2945 		opt = opts.ipoptp_cur;
2946 		optlen = opts.ipoptp_len;
2947 		switch (optval) {
2948 		case IPOPT_SSRR:
2949 		case IPOPT_LSRR:
2950 
2951 			/*
2952 			 * Insert ipha_dst as the first entry in the source
2953 			 * route and move down the entries on step.
2954 			 * The last entry gets placed at buf1.
2955 			 */
2956 			buf[IPOPT_OPTVAL] = optval;
2957 			buf[IPOPT_OLEN] = optlen;
2958 			buf[IPOPT_OFFSET] = optlen;
2959 
2960 			off = optlen - IP_ADDR_LEN;
2961 			if (off < 0) {
2962 				/* No entries in source route */
2963 				break;
2964 			}
2965 			/* Last entry in source route */
2966 			bcopy(opt + off, buf1, IP_ADDR_LEN);
2967 			off -= IP_ADDR_LEN;
2968 
2969 			while (off > 0) {
2970 				bcopy(opt + off,
2971 				    buf + off + IP_ADDR_LEN,
2972 				    IP_ADDR_LEN);
2973 				off -= IP_ADDR_LEN;
2974 			}
2975 			/* ipha_dst into first slot */
2976 			bcopy(&ipha->ipha_dst,
2977 			    buf + off + IP_ADDR_LEN,
2978 			    IP_ADDR_LEN);
2979 			buf += optlen;
2980 			len += optlen;
2981 			break;
2982 
2983 		case IPOPT_COMSEC:
2984 		case IPOPT_SECURITY:
2985 			/* if passing up a label is not ok, then remove */
2986 			if (is_system_labeled())
2987 				break;
2988 			/* FALLTHROUGH */
2989 		default:
2990 			bcopy(opt, buf, optlen);
2991 			buf += optlen;
2992 			len += optlen;
2993 			break;
2994 		}
2995 	}
2996 done:
2997 	/* Pad the resulting options */
2998 	while (len & 0x3) {
2999 		*buf++ = IPOPT_EOL;
3000 		len++;
3001 	}
3002 	return (len);
3003 }
3004 
3005 /*
3006  * Update any record route or timestamp options to include this host.
3007  * Reverse any source route option.
3008  * This routine assumes that the options are well formed i.e. that they
3009  * have already been checked.
3010  */
3011 static void
3012 icmp_options_update(ipha_t *ipha)
3013 {
3014 	ipoptp_t	opts;
3015 	uchar_t		*opt;
3016 	uint8_t		optval;
3017 	ipaddr_t	src;		/* Our local address */
3018 	ipaddr_t	dst;
3019 
3020 	ip2dbg(("icmp_options_update\n"));
3021 	src = ipha->ipha_src;
3022 	dst = ipha->ipha_dst;
3023 
3024 	for (optval = ipoptp_first(&opts, ipha);
3025 	    optval != IPOPT_EOL;
3026 	    optval = ipoptp_next(&opts)) {
3027 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
3028 		opt = opts.ipoptp_cur;
3029 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
3030 		    optval, opts.ipoptp_len));
3031 		switch (optval) {
3032 			int off1, off2;
3033 		case IPOPT_SSRR:
3034 		case IPOPT_LSRR:
3035 			/*
3036 			 * Reverse the source route.  The first entry
3037 			 * should be the next to last one in the current
3038 			 * source route (the last entry is our address).
3039 			 * The last entry should be the final destination.
3040 			 */
3041 			off1 = IPOPT_MINOFF_SR - 1;
3042 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
3043 			if (off2 < 0) {
3044 				/* No entries in source route */
3045 				ip1dbg((
3046 				    "icmp_options_update: bad src route\n"));
3047 				break;
3048 			}
3049 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3050 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3051 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3052 			off2 -= IP_ADDR_LEN;
3053 
3054 			while (off1 < off2) {
3055 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3056 				bcopy((char *)opt + off2, (char *)opt + off1,
3057 				    IP_ADDR_LEN);
3058 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3059 				off1 += IP_ADDR_LEN;
3060 				off2 -= IP_ADDR_LEN;
3061 			}
3062 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3063 			break;
3064 		}
3065 	}
3066 }
3067 
3068 /*
3069  * Process received ICMP Redirect messages.
3070  */
3071 static void
3072 icmp_redirect(ill_t *ill, mblk_t *mp)
3073 {
3074 	ipha_t	*ipha;
3075 	int	iph_hdr_length;
3076 	icmph_t	*icmph;
3077 	ipha_t	*ipha_err;
3078 	ire_t	*ire;
3079 	ire_t	*prev_ire;
3080 	ire_t	*save_ire;
3081 	ipaddr_t  src, dst, gateway;
3082 	iulp_t	ulp_info = { 0 };
3083 	int	error;
3084 	ip_stack_t *ipst;
3085 
3086 	ASSERT(ill != NULL);
3087 	ipst = ill->ill_ipst;
3088 
3089 	ipha = (ipha_t *)mp->b_rptr;
3090 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3091 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3092 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3093 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3094 		freemsg(mp);
3095 		return;
3096 	}
3097 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3098 	ipha_err = (ipha_t *)&icmph[1];
3099 	src = ipha->ipha_src;
3100 	dst = ipha_err->ipha_dst;
3101 	gateway = icmph->icmph_rd_gateway;
3102 	/* Make sure the new gateway is reachable somehow. */
3103 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3104 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3105 	/*
3106 	 * Make sure we had a route for the dest in question and that
3107 	 * that route was pointing to the old gateway (the source of the
3108 	 * redirect packet.)
3109 	 */
3110 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3111 	    NULL, MATCH_IRE_GW, ipst);
3112 	/*
3113 	 * Check that
3114 	 *	the redirect was not from ourselves
3115 	 *	the new gateway and the old gateway are directly reachable
3116 	 */
3117 	if (!prev_ire ||
3118 	    !ire ||
3119 	    ire->ire_type == IRE_LOCAL) {
3120 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3121 		freemsg(mp);
3122 		if (ire != NULL)
3123 			ire_refrele(ire);
3124 		if (prev_ire != NULL)
3125 			ire_refrele(prev_ire);
3126 		return;
3127 	}
3128 
3129 	/*
3130 	 * Should we use the old ULP info to create the new gateway?  From
3131 	 * a user's perspective, we should inherit the info so that it
3132 	 * is a "smooth" transition.  If we do not do that, then new
3133 	 * connections going thru the new gateway will have no route metrics,
3134 	 * which is counter-intuitive to user.  From a network point of
3135 	 * view, this may or may not make sense even though the new gateway
3136 	 * is still directly connected to us so the route metrics should not
3137 	 * change much.
3138 	 *
3139 	 * But if the old ire_uinfo is not initialized, we do another
3140 	 * recursive lookup on the dest using the new gateway.  There may
3141 	 * be a route to that.  If so, use it to initialize the redirect
3142 	 * route.
3143 	 */
3144 	if (prev_ire->ire_uinfo.iulp_set) {
3145 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3146 	} else {
3147 		ire_t *tmp_ire;
3148 		ire_t *sire;
3149 
3150 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3151 		    ALL_ZONES, 0, NULL,
3152 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT),
3153 		    ipst);
3154 		if (sire != NULL) {
3155 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3156 			/*
3157 			 * If sire != NULL, ire_ftable_lookup() should not
3158 			 * return a NULL value.
3159 			 */
3160 			ASSERT(tmp_ire != NULL);
3161 			ire_refrele(tmp_ire);
3162 			ire_refrele(sire);
3163 		} else if (tmp_ire != NULL) {
3164 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3165 			    sizeof (iulp_t));
3166 			ire_refrele(tmp_ire);
3167 		}
3168 	}
3169 	if (prev_ire->ire_type == IRE_CACHE)
3170 		ire_delete(prev_ire);
3171 	ire_refrele(prev_ire);
3172 	/*
3173 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3174 	 * require TOS routing
3175 	 */
3176 	switch (icmph->icmph_code) {
3177 	case 0:
3178 	case 1:
3179 		/* TODO: TOS specificity for cases 2 and 3 */
3180 	case 2:
3181 	case 3:
3182 		break;
3183 	default:
3184 		freemsg(mp);
3185 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3186 		ire_refrele(ire);
3187 		return;
3188 	}
3189 	/*
3190 	 * Create a Route Association.  This will allow us to remember that
3191 	 * someone we believe told us to use the particular gateway.
3192 	 */
3193 	save_ire = ire;
3194 	ire = ire_create(
3195 	    (uchar_t *)&dst,			/* dest addr */
3196 	    (uchar_t *)&ip_g_all_ones,		/* mask */
3197 	    (uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3198 	    (uchar_t *)&gateway,		/* gateway addr */
3199 	    &save_ire->ire_max_frag,		/* max frag */
3200 	    NULL,				/* no src nce */
3201 	    NULL,				/* no rfq */
3202 	    NULL,				/* no stq */
3203 	    IRE_HOST,
3204 	    NULL,				/* ipif */
3205 	    0,					/* cmask */
3206 	    0,					/* phandle */
3207 	    0,					/* ihandle */
3208 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3209 	    &ulp_info,
3210 	    NULL,				/* tsol_gc_t */
3211 	    NULL,				/* gcgrp */
3212 	    ipst);
3213 
3214 	if (ire == NULL) {
3215 		freemsg(mp);
3216 		ire_refrele(save_ire);
3217 		return;
3218 	}
3219 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3220 	ire_refrele(save_ire);
3221 	atomic_inc_32(&ipst->ips_ip_redirect_cnt);
3222 
3223 	if (error == 0) {
3224 		ire_refrele(ire);		/* Held in ire_add_v4 */
3225 		/* tell routing sockets that we received a redirect */
3226 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3227 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3228 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
3229 	}
3230 
3231 	/*
3232 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3233 	 * This together with the added IRE has the effect of
3234 	 * modifying an existing redirect.
3235 	 */
3236 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3237 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), ipst);
3238 	if (prev_ire != NULL) {
3239 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3240 			ire_delete(prev_ire);
3241 		ire_refrele(prev_ire);
3242 	}
3243 
3244 	freemsg(mp);
3245 }
3246 
3247 /*
3248  * Generate an ICMP parameter problem message.
3249  */
3250 static void
3251 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid,
3252 	ip_stack_t *ipst)
3253 {
3254 	icmph_t	icmph;
3255 	boolean_t mctl_present;
3256 	mblk_t *first_mp;
3257 
3258 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3259 
3260 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3261 		if (mctl_present)
3262 			freeb(first_mp);
3263 		return;
3264 	}
3265 
3266 	bzero(&icmph, sizeof (icmph_t));
3267 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3268 	icmph.icmph_pp_ptr = ptr;
3269 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
3270 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3271 	    ipst);
3272 }
3273 
3274 /*
3275  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3276  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3277  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3278  * an icmp error packet can be sent.
3279  * Assigns an appropriate source address to the packet. If ipha_dst is
3280  * one of our addresses use it for source. Otherwise pick a source based
3281  * on a route lookup back to ipha_src.
3282  * Note that ipha_src must be set here since the
3283  * packet is likely to arrive on an ill queue in ip_wput() which will
3284  * not set a source address.
3285  */
3286 static void
3287 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3288     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
3289 {
3290 	ipaddr_t dst;
3291 	icmph_t	*icmph;
3292 	ipha_t	*ipha;
3293 	uint_t	len_needed;
3294 	size_t	msg_len;
3295 	mblk_t	*mp1;
3296 	ipaddr_t src;
3297 	ire_t	*ire;
3298 	mblk_t *ipsec_mp;
3299 	ipsec_out_t	*io = NULL;
3300 
3301 	if (mctl_present) {
3302 		/*
3303 		 * If it is :
3304 		 *
3305 		 * 1) a IPSEC_OUT, then this is caused by outbound
3306 		 *    datagram originating on this host. IPsec processing
3307 		 *    may or may not have been done. Refer to comments above
3308 		 *    icmp_inbound_error_fanout for details.
3309 		 *
3310 		 * 2) a IPSEC_IN if we are generating a icmp_message
3311 		 *    for an incoming datagram destined for us i.e called
3312 		 *    from ip_fanout_send_icmp.
3313 		 */
3314 		ipsec_info_t *in;
3315 		ipsec_mp = mp;
3316 		mp = ipsec_mp->b_cont;
3317 
3318 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3319 		ipha = (ipha_t *)mp->b_rptr;
3320 
3321 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3322 		    in->ipsec_info_type == IPSEC_IN);
3323 
3324 		if (in->ipsec_info_type == IPSEC_IN) {
3325 			/*
3326 			 * Convert the IPSEC_IN to IPSEC_OUT.
3327 			 */
3328 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3329 				BUMP_MIB(&ipst->ips_ip_mib,
3330 				    ipIfStatsOutDiscards);
3331 				return;
3332 			}
3333 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3334 		} else {
3335 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3336 			io = (ipsec_out_t *)in;
3337 			/*
3338 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3339 			 * ire lookup.
3340 			 */
3341 			io->ipsec_out_proc_begin = B_FALSE;
3342 		}
3343 		ASSERT(zoneid == io->ipsec_out_zoneid);
3344 		ASSERT(zoneid != ALL_ZONES);
3345 	} else {
3346 		/*
3347 		 * This is in clear. The icmp message we are building
3348 		 * here should go out in clear.
3349 		 *
3350 		 * Pardon the convolution of it all, but it's easier to
3351 		 * allocate a "use cleartext" IPSEC_IN message and convert
3352 		 * it than it is to allocate a new one.
3353 		 */
3354 		ipsec_in_t *ii;
3355 		ASSERT(DB_TYPE(mp) == M_DATA);
3356 		ipsec_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
3357 		if (ipsec_mp == NULL) {
3358 			freemsg(mp);
3359 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3360 			return;
3361 		}
3362 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3363 
3364 		/* This is not a secure packet */
3365 		ii->ipsec_in_secure = B_FALSE;
3366 		/*
3367 		 * For trusted extensions using a shared IP address we can
3368 		 * send using any zoneid.
3369 		 */
3370 		if (zoneid == ALL_ZONES)
3371 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3372 		else
3373 			ii->ipsec_in_zoneid = zoneid;
3374 		ipsec_mp->b_cont = mp;
3375 		ipha = (ipha_t *)mp->b_rptr;
3376 		/*
3377 		 * Convert the IPSEC_IN to IPSEC_OUT.
3378 		 */
3379 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3380 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3381 			return;
3382 		}
3383 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3384 	}
3385 
3386 	/* Remember our eventual destination */
3387 	dst = ipha->ipha_src;
3388 
3389 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3390 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE, ipst);
3391 	if (ire != NULL &&
3392 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3393 		src = ipha->ipha_dst;
3394 	} else {
3395 		if (ire != NULL)
3396 			ire_refrele(ire);
3397 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3398 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY),
3399 		    ipst);
3400 		if (ire == NULL) {
3401 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3402 			freemsg(ipsec_mp);
3403 			return;
3404 		}
3405 		src = ire->ire_src_addr;
3406 	}
3407 
3408 	if (ire != NULL)
3409 		ire_refrele(ire);
3410 
3411 	/*
3412 	 * Check if we can send back more then 8 bytes in addition to
3413 	 * the IP header.  We try to send 64 bytes of data and the internal
3414 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
3415 	 */
3416 	len_needed = IPH_HDR_LENGTH(ipha);
3417 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
3418 	    ipha->ipha_protocol == IPPROTO_IPV6) {
3419 
3420 		if (!pullupmsg(mp, -1)) {
3421 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3422 			freemsg(ipsec_mp);
3423 			return;
3424 		}
3425 		ipha = (ipha_t *)mp->b_rptr;
3426 
3427 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
3428 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
3429 			    len_needed));
3430 		} else {
3431 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
3432 
3433 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
3434 			len_needed += ip_hdr_length_v6(mp, ip6h);
3435 		}
3436 	}
3437 	len_needed += ipst->ips_ip_icmp_return;
3438 	msg_len = msgdsize(mp);
3439 	if (msg_len > len_needed) {
3440 		(void) adjmsg(mp, len_needed - msg_len);
3441 		msg_len = len_needed;
3442 	}
3443 	mp1 = allocb_tmpl(sizeof (icmp_ipha) + len, mp);
3444 	if (mp1 == NULL) {
3445 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
3446 		freemsg(ipsec_mp);
3447 		return;
3448 	}
3449 	mp1->b_cont = mp;
3450 	mp = mp1;
3451 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3452 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3453 	    io->ipsec_out_type == IPSEC_OUT);
3454 	ipsec_mp->b_cont = mp;
3455 
3456 	/*
3457 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3458 	 * node generates be accepted in peace by all on-host destinations.
3459 	 * If we do NOT assume that all on-host destinations trust
3460 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3461 	 * (Look for ipsec_out_icmp_loopback).
3462 	 */
3463 	io->ipsec_out_icmp_loopback = B_TRUE;
3464 
3465 	ipha = (ipha_t *)mp->b_rptr;
3466 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3467 	*ipha = icmp_ipha;
3468 	ipha->ipha_src = src;
3469 	ipha->ipha_dst = dst;
3470 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
3471 	msg_len += sizeof (icmp_ipha) + len;
3472 	if (msg_len > IP_MAXPACKET) {
3473 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3474 		msg_len = IP_MAXPACKET;
3475 	}
3476 	ipha->ipha_length = htons((uint16_t)msg_len);
3477 	icmph = (icmph_t *)&ipha[1];
3478 	bcopy(stuff, icmph, len);
3479 	icmph->icmph_checksum = 0;
3480 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3481 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
3482 	put(q, ipsec_mp);
3483 }
3484 
3485 /*
3486  * Determine if an ICMP error packet can be sent given the rate limit.
3487  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3488  * in milliseconds) and a burst size. Burst size number of packets can
3489  * be sent arbitrarely closely spaced.
3490  * The state is tracked using two variables to implement an approximate
3491  * token bucket filter:
3492  *	icmp_pkt_err_last - lbolt value when the last burst started
3493  *	icmp_pkt_err_sent - number of packets sent in current burst
3494  */
3495 boolean_t
3496 icmp_err_rate_limit(ip_stack_t *ipst)
3497 {
3498 	clock_t now = TICK_TO_MSEC(lbolt);
3499 	uint_t refilled; /* Number of packets refilled in tbf since last */
3500 	/* Guard against changes by loading into local variable */
3501 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
3502 
3503 	if (err_interval == 0)
3504 		return (B_FALSE);
3505 
3506 	if (ipst->ips_icmp_pkt_err_last > now) {
3507 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3508 		ipst->ips_icmp_pkt_err_last = 0;
3509 		ipst->ips_icmp_pkt_err_sent = 0;
3510 	}
3511 	/*
3512 	 * If we are in a burst update the token bucket filter.
3513 	 * Update the "last" time to be close to "now" but make sure
3514 	 * we don't loose precision.
3515 	 */
3516 	if (ipst->ips_icmp_pkt_err_sent != 0) {
3517 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
3518 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
3519 			ipst->ips_icmp_pkt_err_sent = 0;
3520 		} else {
3521 			ipst->ips_icmp_pkt_err_sent -= refilled;
3522 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
3523 		}
3524 	}
3525 	if (ipst->ips_icmp_pkt_err_sent == 0) {
3526 		/* Start of new burst */
3527 		ipst->ips_icmp_pkt_err_last = now;
3528 	}
3529 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
3530 		ipst->ips_icmp_pkt_err_sent++;
3531 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3532 		    ipst->ips_icmp_pkt_err_sent));
3533 		return (B_FALSE);
3534 	}
3535 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3536 	return (B_TRUE);
3537 }
3538 
3539 /*
3540  * Check if it is ok to send an IPv4 ICMP error packet in
3541  * response to the IPv4 packet in mp.
3542  * Free the message and return null if no
3543  * ICMP error packet should be sent.
3544  */
3545 static mblk_t *
3546 icmp_pkt_err_ok(mblk_t *mp, ip_stack_t *ipst)
3547 {
3548 	icmph_t	*icmph;
3549 	ipha_t	*ipha;
3550 	uint_t	len_needed;
3551 	ire_t	*src_ire;
3552 	ire_t	*dst_ire;
3553 
3554 	if (!mp)
3555 		return (NULL);
3556 	ipha = (ipha_t *)mp->b_rptr;
3557 	if (ip_csum_hdr(ipha)) {
3558 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
3559 		freemsg(mp);
3560 		return (NULL);
3561 	}
3562 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3563 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3564 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3565 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3566 	if (src_ire != NULL || dst_ire != NULL ||
3567 	    CLASSD(ipha->ipha_dst) ||
3568 	    CLASSD(ipha->ipha_src) ||
3569 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3570 		/* Note: only errors to the fragment with offset 0 */
3571 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3572 		freemsg(mp);
3573 		if (src_ire != NULL)
3574 			ire_refrele(src_ire);
3575 		if (dst_ire != NULL)
3576 			ire_refrele(dst_ire);
3577 		return (NULL);
3578 	}
3579 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3580 		/*
3581 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3582 		 * errors in response to any ICMP errors.
3583 		 */
3584 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3585 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3586 			if (!pullupmsg(mp, len_needed)) {
3587 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3588 				freemsg(mp);
3589 				return (NULL);
3590 			}
3591 			ipha = (ipha_t *)mp->b_rptr;
3592 		}
3593 		icmph = (icmph_t *)
3594 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3595 		switch (icmph->icmph_type) {
3596 		case ICMP_DEST_UNREACHABLE:
3597 		case ICMP_SOURCE_QUENCH:
3598 		case ICMP_TIME_EXCEEDED:
3599 		case ICMP_PARAM_PROBLEM:
3600 		case ICMP_REDIRECT:
3601 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3602 			freemsg(mp);
3603 			return (NULL);
3604 		default:
3605 			break;
3606 		}
3607 	}
3608 	/*
3609 	 * If this is a labeled system, then check to see if we're allowed to
3610 	 * send a response to this particular sender.  If not, then just drop.
3611 	 */
3612 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3613 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3614 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3615 		freemsg(mp);
3616 		return (NULL);
3617 	}
3618 	if (icmp_err_rate_limit(ipst)) {
3619 		/*
3620 		 * Only send ICMP error packets every so often.
3621 		 * This should be done on a per port/source basis,
3622 		 * but for now this will suffice.
3623 		 */
3624 		freemsg(mp);
3625 		return (NULL);
3626 	}
3627 	return (mp);
3628 }
3629 
3630 /*
3631  * Generate an ICMP redirect message.
3632  */
3633 static void
3634 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway, ip_stack_t *ipst)
3635 {
3636 	icmph_t	icmph;
3637 
3638 	/*
3639 	 * We are called from ip_rput where we could
3640 	 * not have attached an IPSEC_IN.
3641 	 */
3642 	ASSERT(mp->b_datap->db_type == M_DATA);
3643 
3644 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3645 		return;
3646 	}
3647 
3648 	bzero(&icmph, sizeof (icmph_t));
3649 	icmph.icmph_type = ICMP_REDIRECT;
3650 	icmph.icmph_code = 1;
3651 	icmph.icmph_rd_gateway = gateway;
3652 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3653 	/* Redirects sent by router, and router is global zone */
3654 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID, ipst);
3655 }
3656 
3657 /*
3658  * Generate an ICMP time exceeded message.
3659  */
3660 void
3661 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3662     ip_stack_t *ipst)
3663 {
3664 	icmph_t	icmph;
3665 	boolean_t mctl_present;
3666 	mblk_t *first_mp;
3667 
3668 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3669 
3670 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3671 		if (mctl_present)
3672 			freeb(first_mp);
3673 		return;
3674 	}
3675 
3676 	bzero(&icmph, sizeof (icmph_t));
3677 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3678 	icmph.icmph_code = code;
3679 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3680 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3681 	    ipst);
3682 }
3683 
3684 /*
3685  * Generate an ICMP unreachable message.
3686  */
3687 void
3688 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3689     ip_stack_t *ipst)
3690 {
3691 	icmph_t	icmph;
3692 	mblk_t *first_mp;
3693 	boolean_t mctl_present;
3694 
3695 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3696 
3697 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3698 		if (mctl_present)
3699 			freeb(first_mp);
3700 		return;
3701 	}
3702 
3703 	bzero(&icmph, sizeof (icmph_t));
3704 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3705 	icmph.icmph_code = code;
3706 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3707 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3708 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3709 	    zoneid, ipst);
3710 }
3711 
3712 /*
3713  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3714  * duplicate.  As long as someone else holds the address, the interface will
3715  * stay down.  When that conflict goes away, the interface is brought back up.
3716  * This is done so that accidental shutdowns of addresses aren't made
3717  * permanent.  Your server will recover from a failure.
3718  *
3719  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3720  * user space process (dhcpagent).
3721  *
3722  * Recovery completes if ARP reports that the address is now ours (via
3723  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3724  *
3725  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3726  */
3727 static void
3728 ipif_dup_recovery(void *arg)
3729 {
3730 	ipif_t *ipif = arg;
3731 	ill_t *ill = ipif->ipif_ill;
3732 	mblk_t *arp_add_mp;
3733 	mblk_t *arp_del_mp;
3734 	area_t *area;
3735 	ip_stack_t *ipst = ill->ill_ipst;
3736 
3737 	ipif->ipif_recovery_id = 0;
3738 
3739 	/*
3740 	 * No lock needed for moving or condemned check, as this is just an
3741 	 * optimization.
3742 	 */
3743 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3744 	    (ipif->ipif_flags & IPIF_POINTOPOINT) ||
3745 	    (ipif->ipif_state_flags & (IPIF_MOVING | IPIF_CONDEMNED))) {
3746 		/* No reason to try to bring this address back. */
3747 		return;
3748 	}
3749 
3750 	if ((arp_add_mp = ipif_area_alloc(ipif)) == NULL)
3751 		goto alloc_fail;
3752 
3753 	if (ipif->ipif_arp_del_mp == NULL) {
3754 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3755 			goto alloc_fail;
3756 		ipif->ipif_arp_del_mp = arp_del_mp;
3757 	}
3758 
3759 	/* Setting the 'unverified' flag restarts DAD */
3760 	area = (area_t *)arp_add_mp->b_rptr;
3761 	area->area_flags = ACE_F_PERMANENT | ACE_F_PUBLISH | ACE_F_MYADDR |
3762 	    ACE_F_UNVERIFIED;
3763 	putnext(ill->ill_rq, arp_add_mp);
3764 	return;
3765 
3766 alloc_fail:
3767 	/*
3768 	 * On allocation failure, just restart the timer.  Note that the ipif
3769 	 * is down here, so no other thread could be trying to start a recovery
3770 	 * timer.  The ill_lock protects the condemned flag and the recovery
3771 	 * timer ID.
3772 	 */
3773 	freemsg(arp_add_mp);
3774 	mutex_enter(&ill->ill_lock);
3775 	if (ipst->ips_ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0 &&
3776 	    !(ipif->ipif_state_flags & IPIF_CONDEMNED)) {
3777 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3778 		    MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3779 	}
3780 	mutex_exit(&ill->ill_lock);
3781 }
3782 
3783 /*
3784  * This is for exclusive changes due to ARP.  Either tear down an interface due
3785  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3786  */
3787 /* ARGSUSED */
3788 static void
3789 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3790 {
3791 	ill_t	*ill = rq->q_ptr;
3792 	arh_t *arh;
3793 	ipaddr_t src;
3794 	ipif_t	*ipif;
3795 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3796 	char hbuf[MAC_STR_LEN];
3797 	char sbuf[INET_ADDRSTRLEN];
3798 	const char *failtype;
3799 	boolean_t bring_up;
3800 	ip_stack_t *ipst = ill->ill_ipst;
3801 
3802 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3803 	case AR_CN_READY:
3804 		failtype = NULL;
3805 		bring_up = B_TRUE;
3806 		break;
3807 	case AR_CN_FAILED:
3808 		failtype = "in use";
3809 		bring_up = B_FALSE;
3810 		break;
3811 	default:
3812 		failtype = "claimed";
3813 		bring_up = B_FALSE;
3814 		break;
3815 	}
3816 
3817 	arh = (arh_t *)mp->b_cont->b_rptr;
3818 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3819 
3820 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3821 	    sizeof (hbuf));
3822 	(void) ip_dot_addr(src, sbuf);
3823 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3824 
3825 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3826 		    ipif->ipif_lcl_addr != src) {
3827 			continue;
3828 		}
3829 
3830 		/*
3831 		 * If we failed on a recovery probe, then restart the timer to
3832 		 * try again later.
3833 		 */
3834 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3835 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3836 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3837 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3838 		    ipst->ips_ip_dup_recovery > 0 &&
3839 		    ipif->ipif_recovery_id == 0) {
3840 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3841 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3842 			continue;
3843 		}
3844 
3845 		/*
3846 		 * If what we're trying to do has already been done, then do
3847 		 * nothing.
3848 		 */
3849 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3850 			continue;
3851 
3852 		ipif_get_name(ipif, ibuf, sizeof (ibuf));
3853 
3854 		if (failtype == NULL) {
3855 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3856 			    ibuf);
3857 		} else {
3858 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3859 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3860 		}
3861 
3862 		if (bring_up) {
3863 			ASSERT(ill->ill_dl_up);
3864 			/*
3865 			 * Free up the ARP delete message so we can allocate
3866 			 * a fresh one through the normal path.
3867 			 */
3868 			freemsg(ipif->ipif_arp_del_mp);
3869 			ipif->ipif_arp_del_mp = NULL;
3870 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3871 			    EINPROGRESS) {
3872 				ipif->ipif_addr_ready = 1;
3873 				(void) ipif_up_done(ipif);
3874 			}
3875 			continue;
3876 		}
3877 
3878 		mutex_enter(&ill->ill_lock);
3879 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3880 		ipif->ipif_flags |= IPIF_DUPLICATE;
3881 		ill->ill_ipif_dup_count++;
3882 		mutex_exit(&ill->ill_lock);
3883 		/*
3884 		 * Already exclusive on the ill; no need to handle deferred
3885 		 * processing here.
3886 		 */
3887 		(void) ipif_down(ipif, NULL, NULL);
3888 		ipif_down_tail(ipif);
3889 		mutex_enter(&ill->ill_lock);
3890 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3891 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3892 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3893 		    ipst->ips_ip_dup_recovery > 0) {
3894 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3895 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3896 		}
3897 		mutex_exit(&ill->ill_lock);
3898 	}
3899 	freemsg(mp);
3900 }
3901 
3902 /* ARGSUSED */
3903 static void
3904 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3905 {
3906 	ill_t	*ill = rq->q_ptr;
3907 	arh_t *arh;
3908 	ipaddr_t src;
3909 	ipif_t	*ipif;
3910 
3911 	arh = (arh_t *)mp->b_cont->b_rptr;
3912 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3913 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3914 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3915 			(void) ipif_resolver_up(ipif, Res_act_defend);
3916 	}
3917 	freemsg(mp);
3918 }
3919 
3920 /*
3921  * News from ARP.  ARP sends notification of interesting events down
3922  * to its clients using M_CTL messages with the interesting ARP packet
3923  * attached via b_cont.
3924  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3925  * queue as opposed to ARP sending the message to all the clients, i.e. all
3926  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3927  * table if a cache IRE is found to delete all the entries for the address in
3928  * the packet.
3929  */
3930 static void
3931 ip_arp_news(queue_t *q, mblk_t *mp)
3932 {
3933 	arcn_t		*arcn;
3934 	arh_t		*arh;
3935 	ire_t		*ire = NULL;
3936 	char		hbuf[MAC_STR_LEN];
3937 	char		sbuf[INET_ADDRSTRLEN];
3938 	ipaddr_t	src;
3939 	in6_addr_t	v6src;
3940 	boolean_t	isv6 = B_FALSE;
3941 	ipif_t		*ipif;
3942 	ill_t		*ill;
3943 	ip_stack_t	*ipst;
3944 
3945 	if (CONN_Q(q)) {
3946 		conn_t *connp = Q_TO_CONN(q);
3947 
3948 		ipst = connp->conn_netstack->netstack_ip;
3949 	} else {
3950 		ill_t *ill = (ill_t *)q->q_ptr;
3951 
3952 		ipst = ill->ill_ipst;
3953 	}
3954 
3955 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3956 		if (q->q_next) {
3957 			putnext(q, mp);
3958 		} else
3959 			freemsg(mp);
3960 		return;
3961 	}
3962 	arh = (arh_t *)mp->b_cont->b_rptr;
3963 	/* Is it one we are interested in? */
3964 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3965 		isv6 = B_TRUE;
3966 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3967 		    IPV6_ADDR_LEN);
3968 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3969 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3970 		    IP_ADDR_LEN);
3971 	} else {
3972 		freemsg(mp);
3973 		return;
3974 	}
3975 
3976 	ill = q->q_ptr;
3977 
3978 	arcn = (arcn_t *)mp->b_rptr;
3979 	switch (arcn->arcn_code) {
3980 	case AR_CN_BOGON:
3981 		/*
3982 		 * Someone is sending ARP packets with a source protocol
3983 		 * address that we have published and for which we believe our
3984 		 * entry is authoritative and (when ill_arp_extend is set)
3985 		 * verified to be unique on the network.
3986 		 *
3987 		 * The ARP module internally handles the cases where the sender
3988 		 * is just probing (for DAD) and where the hardware address of
3989 		 * a non-authoritative entry has changed.  Thus, these are the
3990 		 * real conflicts, and we have to do resolution.
3991 		 *
3992 		 * We back away quickly from the address if it's from DHCP or
3993 		 * otherwise temporary and hasn't been used recently (or at
3994 		 * all).  We'd like to include "deprecated" addresses here as
3995 		 * well (as there's no real reason to defend something we're
3996 		 * discarding), but IPMP "reuses" this flag to mean something
3997 		 * other than the standard meaning.
3998 		 *
3999 		 * If the ARP module above is not extended (meaning that it
4000 		 * doesn't know how to defend the address), then we just log
4001 		 * the problem as we always did and continue on.  It's not
4002 		 * right, but there's little else we can do, and those old ATM
4003 		 * users are going away anyway.
4004 		 */
4005 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
4006 		    hbuf, sizeof (hbuf));
4007 		(void) ip_dot_addr(src, sbuf);
4008 		if (isv6) {
4009 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL,
4010 			    ipst);
4011 		} else {
4012 			ire = ire_cache_lookup(src, ALL_ZONES, NULL, ipst);
4013 		}
4014 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
4015 			uint32_t now;
4016 			uint32_t maxage;
4017 			clock_t lused;
4018 			uint_t maxdefense;
4019 			uint_t defs;
4020 
4021 			/*
4022 			 * First, figure out if this address hasn't been used
4023 			 * in a while.  If it hasn't, then it's a better
4024 			 * candidate for abandoning.
4025 			 */
4026 			ipif = ire->ire_ipif;
4027 			ASSERT(ipif != NULL);
4028 			now = gethrestime_sec();
4029 			maxage = now - ire->ire_create_time;
4030 			if (maxage > ipst->ips_ip_max_temp_idle)
4031 				maxage = ipst->ips_ip_max_temp_idle;
4032 			lused = drv_hztousec(ddi_get_lbolt() -
4033 			    ire->ire_last_used_time) / MICROSEC + 1;
4034 			if (lused >= maxage && (ipif->ipif_flags &
4035 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
4036 				maxdefense = ipst->ips_ip_max_temp_defend;
4037 			else
4038 				maxdefense = ipst->ips_ip_max_defend;
4039 
4040 			/*
4041 			 * Now figure out how many times we've defended
4042 			 * ourselves.  Ignore defenses that happened long in
4043 			 * the past.
4044 			 */
4045 			mutex_enter(&ire->ire_lock);
4046 			if ((defs = ire->ire_defense_count) > 0 &&
4047 			    now - ire->ire_defense_time >
4048 			    ipst->ips_ip_defend_interval) {
4049 				ire->ire_defense_count = defs = 0;
4050 			}
4051 			ire->ire_defense_count++;
4052 			ire->ire_defense_time = now;
4053 			mutex_exit(&ire->ire_lock);
4054 			ill_refhold(ill);
4055 			ire_refrele(ire);
4056 
4057 			/*
4058 			 * If we've defended ourselves too many times already,
4059 			 * then give up and tear down the interface(s) using
4060 			 * this address.  Otherwise, defend by sending out a
4061 			 * gratuitous ARP.
4062 			 */
4063 			if (defs >= maxdefense && ill->ill_arp_extend) {
4064 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4065 				    B_FALSE);
4066 			} else {
4067 				cmn_err(CE_WARN,
4068 				    "node %s is using our IP address %s on %s",
4069 				    hbuf, sbuf, ill->ill_name);
4070 				/*
4071 				 * If this is an old (ATM) ARP module, then
4072 				 * don't try to defend the address.  Remain
4073 				 * compatible with the old behavior.  Defend
4074 				 * only with new ARP.
4075 				 */
4076 				if (ill->ill_arp_extend) {
4077 					qwriter_ip(ill, q, mp, ip_arp_defend,
4078 					    NEW_OP, B_FALSE);
4079 				} else {
4080 					ill_refrele(ill);
4081 				}
4082 			}
4083 			return;
4084 		}
4085 		cmn_err(CE_WARN,
4086 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4087 		    hbuf, sbuf, ill->ill_name);
4088 		if (ire != NULL)
4089 			ire_refrele(ire);
4090 		break;
4091 	case AR_CN_ANNOUNCE:
4092 		if (isv6) {
4093 			/*
4094 			 * For XRESOLV interfaces.
4095 			 * Delete the IRE cache entry and NCE for this
4096 			 * v6 address
4097 			 */
4098 			ip_ire_clookup_and_delete_v6(&v6src, ipst);
4099 			/*
4100 			 * If v6src is a non-zero, it's a router address
4101 			 * as below. Do the same sort of thing to clean
4102 			 * out off-net IRE_CACHE entries that go through
4103 			 * the router.
4104 			 */
4105 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4106 				ire_walk_v6(ire_delete_cache_gw_v6,
4107 				    (char *)&v6src, ALL_ZONES, ipst);
4108 			}
4109 		} else {
4110 			nce_hw_map_t hwm;
4111 
4112 			/*
4113 			 * ARP gives us a copy of any packet where it thinks
4114 			 * the address has changed, so that we can update our
4115 			 * caches.  We're responsible for caching known answers
4116 			 * in the current design.  We check whether the
4117 			 * hardware address really has changed in all of our
4118 			 * entries that have cached this mapping, and if so, we
4119 			 * blow them away.  This way we will immediately pick
4120 			 * up the rare case of a host changing hardware
4121 			 * address.
4122 			 */
4123 			if (src == 0)
4124 				break;
4125 			hwm.hwm_addr = src;
4126 			hwm.hwm_hwlen = arh->arh_hlen;
4127 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4128 			NDP_HW_CHANGE_INCR(ipst->ips_ndp4);
4129 			ndp_walk_common(ipst->ips_ndp4, NULL,
4130 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4131 			NDP_HW_CHANGE_DECR(ipst->ips_ndp4);
4132 		}
4133 		break;
4134 	case AR_CN_READY:
4135 		/* No external v6 resolver has a contract to use this */
4136 		if (isv6)
4137 			break;
4138 		/* If the link is down, we'll retry this later */
4139 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4140 			break;
4141 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4142 		    NULL, NULL, ipst);
4143 		if (ipif != NULL) {
4144 			/*
4145 			 * If this is a duplicate recovery, then we now need to
4146 			 * go exclusive to bring this thing back up.
4147 			 */
4148 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4149 			    IPIF_DUPLICATE) {
4150 				ipif_refrele(ipif);
4151 				ill_refhold(ill);
4152 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4153 				    B_FALSE);
4154 				return;
4155 			}
4156 			/*
4157 			 * If this is the first notice that this address is
4158 			 * ready, then let the user know now.
4159 			 */
4160 			if ((ipif->ipif_flags & IPIF_UP) &&
4161 			    !ipif->ipif_addr_ready) {
4162 				ipif_mask_reply(ipif);
4163 				ipif_up_notify(ipif);
4164 			}
4165 			ipif->ipif_addr_ready = 1;
4166 			ipif_refrele(ipif);
4167 		}
4168 		ire = ire_cache_lookup(src, ALL_ZONES, MBLK_GETLABEL(mp), ipst);
4169 		if (ire != NULL) {
4170 			ire->ire_defense_count = 0;
4171 			ire_refrele(ire);
4172 		}
4173 		break;
4174 	case AR_CN_FAILED:
4175 		/* No external v6 resolver has a contract to use this */
4176 		if (isv6)
4177 			break;
4178 		ill_refhold(ill);
4179 		qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP, B_FALSE);
4180 		return;
4181 	}
4182 	freemsg(mp);
4183 }
4184 
4185 /*
4186  * Create a mblk suitable for carrying the interface index and/or source link
4187  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4188  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4189  * application.
4190  */
4191 mblk_t *
4192 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags, zoneid_t zoneid,
4193     ip_stack_t *ipst)
4194 {
4195 	mblk_t		*mp;
4196 	ip_pktinfo_t	*pinfo;
4197 	ipha_t *ipha;
4198 	struct ether_header *pether;
4199 
4200 	mp = allocb(sizeof (ip_pktinfo_t), BPRI_MED);
4201 	if (mp == NULL) {
4202 		ip1dbg(("ip_add_info: allocation failure.\n"));
4203 		return (data_mp);
4204 	}
4205 
4206 	ipha	= (ipha_t *)data_mp->b_rptr;
4207 	pinfo = (ip_pktinfo_t *)mp->b_rptr;
4208 	bzero(pinfo, sizeof (ip_pktinfo_t));
4209 	pinfo->ip_pkt_flags = (uchar_t)flags;
4210 	pinfo->ip_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4211 
4212 	if (flags & (IPF_RECVIF | IPF_RECVADDR))
4213 		pinfo->ip_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4214 	if (flags & IPF_RECVADDR) {
4215 		ipif_t	*ipif;
4216 		ire_t	*ire;
4217 
4218 		/*
4219 		 * Only valid for V4
4220 		 */
4221 		ASSERT((ipha->ipha_version_and_hdr_length & 0xf0) ==
4222 		    (IPV4_VERSION << 4));
4223 
4224 		ipif = ipif_get_next_ipif(NULL, ill);
4225 		if (ipif != NULL) {
4226 			/*
4227 			 * Since a decision has already been made to deliver the
4228 			 * packet, there is no need to test for SECATTR and
4229 			 * ZONEONLY.
4230 			 * When a multicast packet is transmitted
4231 			 * a cache entry is created for the multicast address.
4232 			 * When delivering a copy of the packet or when new
4233 			 * packets are received we do not want to match on the
4234 			 * cached entry so explicitly match on
4235 			 * IRE_LOCAL and IRE_LOOPBACK
4236 			 */
4237 			ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4238 			    IRE_LOCAL | IRE_LOOPBACK,
4239 			    ipif, zoneid, NULL,
4240 			    MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP, ipst);
4241 			if (ire == NULL) {
4242 				/*
4243 				 * packet must have come on a different
4244 				 * interface.
4245 				 * Since a decision has already been made to
4246 				 * deliver the packet, there is no need to test
4247 				 * for SECATTR and ZONEONLY.
4248 				 * Only match on local and broadcast ire's.
4249 				 * See detailed comment above.
4250 				 */
4251 				ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4252 				    IRE_LOCAL | IRE_LOOPBACK, ipif, zoneid,
4253 				    NULL, MATCH_IRE_TYPE, ipst);
4254 			}
4255 
4256 			if (ire == NULL) {
4257 				/*
4258 				 * This is either a multicast packet or
4259 				 * the address has been removed since
4260 				 * the packet was received.
4261 				 * Return INADDR_ANY so that normal source
4262 				 * selection occurs for the response.
4263 				 */
4264 
4265 				pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4266 			} else {
4267 				pinfo->ip_pkt_match_addr.s_addr =
4268 				    ire->ire_src_addr;
4269 				ire_refrele(ire);
4270 			}
4271 			ipif_refrele(ipif);
4272 		} else {
4273 			pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4274 		}
4275 	}
4276 
4277 	pether = (struct ether_header *)((char *)ipha
4278 	    - sizeof (struct ether_header));
4279 	/*
4280 	 * Make sure the interface is an ethernet type, since this option
4281 	 * is currently supported only on this type of interface. Also make
4282 	 * sure we are pointing correctly above db_base.
4283 	 */
4284 
4285 	if ((flags & IPF_RECVSLLA) &&
4286 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4287 	    (ill->ill_type == IFT_ETHER) &&
4288 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4289 
4290 		pinfo->ip_pkt_slla.sdl_type = IFT_ETHER;
4291 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
4292 		    (uchar_t *)pinfo->ip_pkt_slla.sdl_data, ETHERADDRL);
4293 	} else {
4294 		/*
4295 		 * Clear the bit. Indicate to upper layer that IP is not
4296 		 * sending this ancillary info.
4297 		 */
4298 		pinfo->ip_pkt_flags = pinfo->ip_pkt_flags & ~IPF_RECVSLLA;
4299 	}
4300 
4301 	mp->b_datap->db_type = M_CTL;
4302 	mp->b_wptr += sizeof (ip_pktinfo_t);
4303 	mp->b_cont = data_mp;
4304 
4305 	return (mp);
4306 }
4307 
4308 /*
4309  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4310  * part of the bind request.
4311  */
4312 
4313 boolean_t
4314 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4315 {
4316 	ipsec_in_t *ii;
4317 
4318 	ASSERT(policy_mp != NULL);
4319 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4320 
4321 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4322 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4323 
4324 	connp->conn_policy = ii->ipsec_in_policy;
4325 	ii->ipsec_in_policy = NULL;
4326 
4327 	if (ii->ipsec_in_action != NULL) {
4328 		if (connp->conn_latch == NULL) {
4329 			connp->conn_latch = iplatch_create();
4330 			if (connp->conn_latch == NULL)
4331 				return (B_FALSE);
4332 		}
4333 		ipsec_latch_inbound(connp->conn_latch, ii);
4334 	}
4335 	return (B_TRUE);
4336 }
4337 
4338 static void
4339 ip_bind_post_handling(conn_t *connp, mblk_t *mp, boolean_t ire_requested)
4340 {
4341 	/*
4342 	 * Pass the IPsec headers size in ire_ipsec_overhead.
4343 	 * We can't do this in ip_bind_get_ire because the policy
4344 	 * may not have been inherited at that point in time and hence
4345 	 * conn_out_enforce_policy may not be set.
4346 	 */
4347 	if (ire_requested && connp->conn_out_enforce_policy &&
4348 	    mp != NULL && DB_TYPE(mp) == IRE_DB_REQ_TYPE) {
4349 		ire_t *ire = (ire_t *)mp->b_rptr;
4350 		ASSERT(MBLKL(mp) >= sizeof (ire_t));
4351 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4352 	}
4353 }
4354 
4355 /*
4356  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4357  * and to arrange for power-fanout assist.  The ULP is identified by
4358  * adding a single byte at the end of the original bind message.
4359  * A ULP other than UDP or TCP that wishes to be recognized passes
4360  * down a bind with a zero length address.
4361  *
4362  * The binding works as follows:
4363  * - A zero byte address means just bind to the protocol.
4364  * - A four byte address is treated as a request to validate
4365  *   that the address is a valid local address, appropriate for
4366  *   an application to bind to. This does not affect any fanout
4367  *   information in IP.
4368  * - A sizeof sin_t byte address is used to bind to only the local address
4369  *   and port.
4370  * - A sizeof ipa_conn_t byte address contains complete fanout information
4371  *   consisting of local and remote addresses and ports.  In
4372  *   this case, the addresses are both validated as appropriate
4373  *   for this operation, and, if so, the information is retained
4374  *   for use in the inbound fanout.
4375  *
4376  * The ULP (except in the zero-length bind) can append an
4377  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4378  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4379  * a copy of the source or destination IRE (source for local bind;
4380  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4381  * policy information contained should be copied on to the conn.
4382  *
4383  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4384  */
4385 mblk_t *
4386 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4387 {
4388 	ssize_t		len;
4389 	struct T_bind_req	*tbr;
4390 	sin_t		*sin;
4391 	ipa_conn_t	*ac;
4392 	uchar_t		*ucp;
4393 	mblk_t		*mp1;
4394 	boolean_t	ire_requested;
4395 	int		error = 0;
4396 	int		protocol;
4397 	ipa_conn_x_t	*acx;
4398 
4399 	ASSERT(!connp->conn_af_isv6);
4400 	connp->conn_pkt_isv6 = B_FALSE;
4401 
4402 	len = MBLKL(mp);
4403 	if (len < (sizeof (*tbr) + 1)) {
4404 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4405 		    "ip_bind: bogus msg, len %ld", len);
4406 		/* XXX: Need to return something better */
4407 		goto bad_addr;
4408 	}
4409 	/* Back up and extract the protocol identifier. */
4410 	mp->b_wptr--;
4411 	protocol = *mp->b_wptr & 0xFF;
4412 	tbr = (struct T_bind_req *)mp->b_rptr;
4413 	/* Reset the message type in preparation for shipping it back. */
4414 	DB_TYPE(mp) = M_PCPROTO;
4415 
4416 	connp->conn_ulp = (uint8_t)protocol;
4417 
4418 	/*
4419 	 * Check for a zero length address.  This is from a protocol that
4420 	 * wants to register to receive all packets of its type.
4421 	 */
4422 	if (tbr->ADDR_length == 0) {
4423 		/*
4424 		 * These protocols are now intercepted in ip_bind_v6().
4425 		 * Reject protocol-level binds here for now.
4426 		 *
4427 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4428 		 * so that the protocol type cannot be SCTP.
4429 		 */
4430 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4431 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4432 			goto bad_addr;
4433 		}
4434 
4435 		/*
4436 		 *
4437 		 * The udp module never sends down a zero-length address,
4438 		 * and allowing this on a labeled system will break MLP
4439 		 * functionality.
4440 		 */
4441 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4442 			goto bad_addr;
4443 
4444 		if (connp->conn_mac_exempt)
4445 			goto bad_addr;
4446 
4447 		/* No hash here really.  The table is big enough. */
4448 		connp->conn_srcv6 = ipv6_all_zeros;
4449 
4450 		ipcl_proto_insert(connp, protocol);
4451 
4452 		tbr->PRIM_type = T_BIND_ACK;
4453 		return (mp);
4454 	}
4455 
4456 	/* Extract the address pointer from the message. */
4457 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4458 	    tbr->ADDR_length);
4459 	if (ucp == NULL) {
4460 		ip1dbg(("ip_bind: no address\n"));
4461 		goto bad_addr;
4462 	}
4463 	if (!OK_32PTR(ucp)) {
4464 		ip1dbg(("ip_bind: unaligned address\n"));
4465 		goto bad_addr;
4466 	}
4467 	/*
4468 	 * Check for trailing mps.
4469 	 */
4470 
4471 	mp1 = mp->b_cont;
4472 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4473 
4474 	switch (tbr->ADDR_length) {
4475 	default:
4476 		ip1dbg(("ip_bind: bad address length %d\n",
4477 		    (int)tbr->ADDR_length));
4478 		goto bad_addr;
4479 
4480 	case IP_ADDR_LEN:
4481 		/* Verification of local address only */
4482 		error = ip_bind_laddr_v4(connp, &mp1, protocol,
4483 		    *(ipaddr_t *)ucp, 0, B_FALSE);
4484 		break;
4485 
4486 	case sizeof (sin_t):
4487 		sin = (sin_t *)ucp;
4488 		error = ip_bind_laddr_v4(connp, &mp1, protocol,
4489 		    sin->sin_addr.s_addr, sin->sin_port, B_TRUE);
4490 		break;
4491 
4492 	case sizeof (ipa_conn_t):
4493 		ac = (ipa_conn_t *)ucp;
4494 		/* For raw socket, the local port is not set. */
4495 		if (ac->ac_lport == 0)
4496 			ac->ac_lport = connp->conn_lport;
4497 		/* Always verify destination reachability. */
4498 		error = ip_bind_connected_v4(connp, &mp1, protocol,
4499 		    &ac->ac_laddr, ac->ac_lport, ac->ac_faddr, ac->ac_fport,
4500 		    B_TRUE, B_TRUE);
4501 		break;
4502 
4503 	case sizeof (ipa_conn_x_t):
4504 		acx = (ipa_conn_x_t *)ucp;
4505 		/*
4506 		 * Whether or not to verify destination reachability depends
4507 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4508 		 */
4509 		error = ip_bind_connected_v4(connp, &mp1, protocol,
4510 		    &acx->acx_conn.ac_laddr, acx->acx_conn.ac_lport,
4511 		    acx->acx_conn.ac_faddr, acx->acx_conn.ac_fport,
4512 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
4513 		break;
4514 	}
4515 	ASSERT(error != EINPROGRESS);
4516 	if (error != 0)
4517 		goto bad_addr;
4518 
4519 	ip_bind_post_handling(connp, mp->b_cont, ire_requested);
4520 
4521 	/* Send it home. */
4522 	mp->b_datap->db_type = M_PCPROTO;
4523 	tbr->PRIM_type = T_BIND_ACK;
4524 	return (mp);
4525 
4526 bad_addr:
4527 	/*
4528 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4529 	 * a unix errno.
4530 	 */
4531 	if (error > 0)
4532 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4533 	else
4534 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4535 	return (mp);
4536 }
4537 
4538 /*
4539  * Here address is verified to be a valid local address.
4540  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4541  * address is also considered a valid local address.
4542  * In the case of a broadcast/multicast address, however, the
4543  * upper protocol is expected to reset the src address
4544  * to 0 if it sees a IRE_BROADCAST type returned so that
4545  * no packets are emitted with broadcast/multicast address as
4546  * source address (that violates hosts requirements RFC 1122)
4547  * The addresses valid for bind are:
4548  *	(1) - INADDR_ANY (0)
4549  *	(2) - IP address of an UP interface
4550  *	(3) - IP address of a DOWN interface
4551  *	(4) - valid local IP broadcast addresses. In this case
4552  *	the conn will only receive packets destined to
4553  *	the specified broadcast address.
4554  *	(5) - a multicast address. In this case
4555  *	the conn will only receive packets destined to
4556  *	the specified multicast address. Note: the
4557  *	application still has to issue an
4558  *	IP_ADD_MEMBERSHIP socket option.
4559  *
4560  * On error, return -1 for TBADADDR otherwise pass the
4561  * errno with TSYSERR reply.
4562  *
4563  * In all the above cases, the bound address must be valid in the current zone.
4564  * When the address is loopback, multicast or broadcast, there might be many
4565  * matching IREs so bind has to look up based on the zone.
4566  *
4567  * Note: lport is in network byte order.
4568  *
4569  */
4570 int
4571 ip_bind_laddr_v4(conn_t *connp, mblk_t **mpp, uint8_t protocol,
4572     ipaddr_t src_addr, uint16_t lport, boolean_t fanout_insert)
4573 {
4574 	int		error = 0;
4575 	ire_t		*src_ire;
4576 	zoneid_t	zoneid;
4577 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4578 	mblk_t		*mp = NULL;
4579 	boolean_t	ire_requested = B_FALSE;
4580 	boolean_t	ipsec_policy_set = B_FALSE;
4581 
4582 	if (mpp)
4583 		mp = *mpp;
4584 
4585 	if (mp != NULL) {
4586 		ire_requested = (DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4587 		ipsec_policy_set = (DB_TYPE(mp) == IPSEC_POLICY_SET);
4588 	}
4589 
4590 	/*
4591 	 * If it was previously connected, conn_fully_bound would have
4592 	 * been set.
4593 	 */
4594 	connp->conn_fully_bound = B_FALSE;
4595 
4596 	src_ire = NULL;
4597 
4598 	zoneid = IPCL_ZONEID(connp);
4599 
4600 	if (src_addr) {
4601 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4602 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
4603 		/*
4604 		 * If an address other than 0.0.0.0 is requested,
4605 		 * we verify that it is a valid address for bind
4606 		 * Note: Following code is in if-else-if form for
4607 		 * readability compared to a condition check.
4608 		 */
4609 		/* LINTED - statement has no consequence */
4610 		if (IRE_IS_LOCAL(src_ire)) {
4611 			/*
4612 			 * (2) Bind to address of local UP interface
4613 			 */
4614 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4615 			/*
4616 			 * (4) Bind to broadcast address
4617 			 * Note: permitted only from transports that
4618 			 * request IRE
4619 			 */
4620 			if (!ire_requested)
4621 				error = EADDRNOTAVAIL;
4622 		} else {
4623 			/*
4624 			 * (3) Bind to address of local DOWN interface
4625 			 * (ipif_lookup_addr() looks up all interfaces
4626 			 * but we do not get here for UP interfaces
4627 			 * - case (2) above)
4628 			 */
4629 			/* LINTED - statement has no consequent */
4630 			if (ip_addr_exists(src_addr, zoneid, ipst)) {
4631 				/* The address exists */
4632 			} else if (CLASSD(src_addr)) {
4633 				error = 0;
4634 				if (src_ire != NULL)
4635 					ire_refrele(src_ire);
4636 				/*
4637 				 * (5) bind to multicast address.
4638 				 * Fake out the IRE returned to upper
4639 				 * layer to be a broadcast IRE.
4640 				 */
4641 				src_ire = ire_ctable_lookup(
4642 				    INADDR_BROADCAST, INADDR_ANY,
4643 				    IRE_BROADCAST, NULL, zoneid, NULL,
4644 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY),
4645 				    ipst);
4646 				if (src_ire == NULL || !ire_requested)
4647 					error = EADDRNOTAVAIL;
4648 			} else {
4649 				/*
4650 				 * Not a valid address for bind
4651 				 */
4652 				error = EADDRNOTAVAIL;
4653 			}
4654 		}
4655 		if (error) {
4656 			/* Red Alert!  Attempting to be a bogon! */
4657 			ip1dbg(("ip_bind_laddr_v4: bad src address 0x%x\n",
4658 			    ntohl(src_addr)));
4659 			goto bad_addr;
4660 		}
4661 	}
4662 
4663 
4664 	/*
4665 	 * Allow setting new policies. For example, disconnects come
4666 	 * down as ipa_t bind. As we would have set conn_policy_cached
4667 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4668 	 * can change after the disconnect.
4669 	 */
4670 	connp->conn_policy_cached = B_FALSE;
4671 
4672 	/*
4673 	 * If not fanout_insert this was just an address verification
4674 	 */
4675 	if (fanout_insert) {
4676 		/*
4677 		 * The addresses have been verified. Time to insert in
4678 		 * the correct fanout list.
4679 		 */
4680 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4681 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4682 		connp->conn_lport = lport;
4683 		connp->conn_fport = 0;
4684 		/*
4685 		 * Do we need to add a check to reject Multicast packets
4686 		 */
4687 		error = ipcl_bind_insert(connp, protocol, src_addr, lport);
4688 	}
4689 
4690 	if (error == 0) {
4691 		if (ire_requested) {
4692 			if (!ip_bind_get_ire_v4(mpp, src_ire, NULL, ipst)) {
4693 				error = -1;
4694 				/* Falls through to bad_addr */
4695 			}
4696 		} else if (ipsec_policy_set) {
4697 			if (!ip_bind_ipsec_policy_set(connp, mp)) {
4698 				error = -1;
4699 				/* Falls through to bad_addr */
4700 			}
4701 		}
4702 	}
4703 bad_addr:
4704 	if (error != 0) {
4705 		if (connp->conn_anon_port) {
4706 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4707 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4708 			    B_FALSE);
4709 		}
4710 		connp->conn_mlp_type = mlptSingle;
4711 	}
4712 	if (src_ire != NULL)
4713 		IRE_REFRELE(src_ire);
4714 	return (error);
4715 }
4716 
4717 int
4718 ip_proto_bind_laddr_v4(conn_t *connp, mblk_t **ire_mpp, uint8_t protocol,
4719     ipaddr_t src_addr, uint16_t lport, boolean_t fanout_insert)
4720 {
4721 	int error;
4722 	mblk_t	*mp = NULL;
4723 	boolean_t ire_requested;
4724 
4725 	if (ire_mpp)
4726 		mp = *ire_mpp;
4727 	ire_requested = (mp != NULL && DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4728 
4729 	ASSERT(!connp->conn_af_isv6);
4730 	connp->conn_pkt_isv6 = B_FALSE;
4731 	connp->conn_ulp = protocol;
4732 
4733 	error = ip_bind_laddr_v4(connp, ire_mpp, protocol, src_addr, lport,
4734 	    fanout_insert);
4735 	if (error == 0) {
4736 		ip_bind_post_handling(connp, ire_mpp ? *ire_mpp : NULL,
4737 		    ire_requested);
4738 	} else if (error < 0) {
4739 		error = -TBADADDR;
4740 	}
4741 	return (error);
4742 }
4743 
4744 /*
4745  * Verify that both the source and destination addresses
4746  * are valid.  If verify_dst is false, then the destination address may be
4747  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4748  * destination reachability, while tunnels do not.
4749  * Note that we allow connect to broadcast and multicast
4750  * addresses when ire_requested is set. Thus the ULP
4751  * has to check for IRE_BROADCAST and multicast.
4752  *
4753  * Returns zero if ok.
4754  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4755  * (for use with TSYSERR reply).
4756  *
4757  * Note: lport and fport are in network byte order.
4758  */
4759 int
4760 ip_bind_connected_v4(conn_t *connp, mblk_t **mpp, uint8_t protocol,
4761     ipaddr_t *src_addrp, uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4762     boolean_t fanout_insert, boolean_t verify_dst)
4763 {
4764 
4765 	ire_t		*src_ire;
4766 	ire_t		*dst_ire;
4767 	int		error = 0;
4768 	ire_t		*sire = NULL;
4769 	ire_t		*md_dst_ire = NULL;
4770 	ire_t		*lso_dst_ire = NULL;
4771 	ill_t		*ill = NULL;
4772 	zoneid_t	zoneid;
4773 	ipaddr_t	src_addr = *src_addrp;
4774 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4775 	mblk_t		*mp = NULL;
4776 	boolean_t	ire_requested = B_FALSE;
4777 	boolean_t	ipsec_policy_set = B_FALSE;
4778 	ts_label_t	*tsl = NULL;
4779 
4780 	if (mpp)
4781 		mp = *mpp;
4782 
4783 	if (mp != NULL) {
4784 		ire_requested = (DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4785 		ipsec_policy_set = (DB_TYPE(mp) == IPSEC_POLICY_SET);
4786 		tsl = MBLK_GETLABEL(mp);
4787 	}
4788 
4789 	src_ire = dst_ire = NULL;
4790 
4791 	/*
4792 	 * If we never got a disconnect before, clear it now.
4793 	 */
4794 	connp->conn_fully_bound = B_FALSE;
4795 
4796 	zoneid = IPCL_ZONEID(connp);
4797 
4798 	if (CLASSD(dst_addr)) {
4799 		/* Pick up an IRE_BROADCAST */
4800 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4801 		    NULL, zoneid, tsl,
4802 		    (MATCH_IRE_RECURSIVE |
4803 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4804 		    MATCH_IRE_SECATTR), ipst);
4805 	} else {
4806 		/*
4807 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4808 		 * and onlink ipif is not found set ENETUNREACH error.
4809 		 */
4810 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4811 			ipif_t *ipif;
4812 
4813 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4814 			    dst_addr : connp->conn_nexthop_v4, zoneid, ipst);
4815 			if (ipif == NULL) {
4816 				error = ENETUNREACH;
4817 				goto bad_addr;
4818 			}
4819 			ipif_refrele(ipif);
4820 		}
4821 
4822 		if (connp->conn_nexthop_set) {
4823 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4824 			    0, 0, NULL, NULL, zoneid, tsl,
4825 			    MATCH_IRE_SECATTR, ipst);
4826 		} else {
4827 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4828 			    &sire, zoneid, tsl,
4829 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4830 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4831 			    MATCH_IRE_SECATTR), ipst);
4832 		}
4833 	}
4834 	/*
4835 	 * dst_ire can't be a broadcast when not ire_requested.
4836 	 * We also prevent ire's with src address INADDR_ANY to
4837 	 * be used, which are created temporarily for
4838 	 * sending out packets from endpoints that have
4839 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4840 	 * reachable.  If verify_dst is false, the destination needn't be
4841 	 * reachable.
4842 	 *
4843 	 * If we match on a reject or black hole, then we've got a
4844 	 * local failure.  May as well fail out the connect() attempt,
4845 	 * since it's never going to succeed.
4846 	 */
4847 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4848 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4849 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4850 		/*
4851 		 * If we're verifying destination reachability, we always want
4852 		 * to complain here.
4853 		 *
4854 		 * If we're not verifying destination reachability but the
4855 		 * destination has a route, we still want to fail on the
4856 		 * temporary address and broadcast address tests.
4857 		 */
4858 		if (verify_dst || (dst_ire != NULL)) {
4859 			if (ip_debug > 2) {
4860 				pr_addr_dbg("ip_bind_connected_v4:"
4861 				    "bad connected dst %s\n",
4862 				    AF_INET, &dst_addr);
4863 			}
4864 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4865 				error = ENETUNREACH;
4866 			else
4867 				error = EHOSTUNREACH;
4868 			goto bad_addr;
4869 		}
4870 	}
4871 
4872 	/*
4873 	 * We now know that routing will allow us to reach the destination.
4874 	 * Check whether Trusted Solaris policy allows communication with this
4875 	 * host, and pretend that the destination is unreachable if not.
4876 	 *
4877 	 * This is never a problem for TCP, since that transport is known to
4878 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4879 	 * handling.  If the remote is unreachable, it will be detected at that
4880 	 * point, so there's no reason to check it here.
4881 	 *
4882 	 * Note that for sendto (and other datagram-oriented friends), this
4883 	 * check is done as part of the data path label computation instead.
4884 	 * The check here is just to make non-TCP connect() report the right
4885 	 * error.
4886 	 */
4887 	if (dst_ire != NULL && is_system_labeled() &&
4888 	    !IPCL_IS_TCP(connp) &&
4889 	    tsol_compute_label(DB_CREDDEF(mp, connp->conn_cred), dst_addr, NULL,
4890 	    connp->conn_mac_exempt, ipst) != 0) {
4891 		error = EHOSTUNREACH;
4892 		if (ip_debug > 2) {
4893 			pr_addr_dbg("ip_bind_connected_v4:"
4894 			    " no label for dst %s\n",
4895 			    AF_INET, &dst_addr);
4896 		}
4897 		goto bad_addr;
4898 	}
4899 
4900 	/*
4901 	 * If the app does a connect(), it means that it will most likely
4902 	 * send more than 1 packet to the destination.  It makes sense
4903 	 * to clear the temporary flag.
4904 	 */
4905 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4906 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4907 		irb_t *irb = dst_ire->ire_bucket;
4908 
4909 		rw_enter(&irb->irb_lock, RW_WRITER);
4910 		/*
4911 		 * We need to recheck for IRE_MARK_TEMPORARY after acquiring
4912 		 * the lock to guarantee irb_tmp_ire_cnt.
4913 		 */
4914 		if (dst_ire->ire_marks & IRE_MARK_TEMPORARY) {
4915 			dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4916 			irb->irb_tmp_ire_cnt--;
4917 		}
4918 		rw_exit(&irb->irb_lock);
4919 	}
4920 
4921 	/*
4922 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4923 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4924 	 * eligibility tests for passive connects are handled separately
4925 	 * through tcp_adapt_ire().  We do this before the source address
4926 	 * selection, because dst_ire may change after a call to
4927 	 * ipif_select_source().  This is a best-effort check, as the
4928 	 * packet for this connection may not actually go through
4929 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4930 	 * calling ip_newroute().  This is why we further check on the
4931 	 * IRE during LSO/Multidata packet transmission in
4932 	 * tcp_lsosend()/tcp_multisend().
4933 	 */
4934 	if (!ipsec_policy_set && dst_ire != NULL &&
4935 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4936 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4937 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4938 			lso_dst_ire = dst_ire;
4939 			IRE_REFHOLD(lso_dst_ire);
4940 		} else if (ipst->ips_ip_multidata_outbound &&
4941 		    ILL_MDT_CAPABLE(ill)) {
4942 			md_dst_ire = dst_ire;
4943 			IRE_REFHOLD(md_dst_ire);
4944 		}
4945 	}
4946 
4947 	if (dst_ire != NULL &&
4948 	    dst_ire->ire_type == IRE_LOCAL &&
4949 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4950 		/*
4951 		 * If the IRE belongs to a different zone, look for a matching
4952 		 * route in the forwarding table and use the source address from
4953 		 * that route.
4954 		 */
4955 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4956 		    zoneid, 0, NULL,
4957 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4958 		    MATCH_IRE_RJ_BHOLE, ipst);
4959 		if (src_ire == NULL) {
4960 			error = EHOSTUNREACH;
4961 			goto bad_addr;
4962 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4963 			if (!(src_ire->ire_type & IRE_HOST))
4964 				error = ENETUNREACH;
4965 			else
4966 				error = EHOSTUNREACH;
4967 			goto bad_addr;
4968 		}
4969 		if (src_addr == INADDR_ANY)
4970 			src_addr = src_ire->ire_src_addr;
4971 		ire_refrele(src_ire);
4972 		src_ire = NULL;
4973 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4974 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4975 			src_addr = sire->ire_src_addr;
4976 			ire_refrele(dst_ire);
4977 			dst_ire = sire;
4978 			sire = NULL;
4979 		} else {
4980 			/*
4981 			 * Pick a source address so that a proper inbound
4982 			 * load spreading would happen.
4983 			 */
4984 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4985 			ipif_t *src_ipif = NULL;
4986 			ire_t *ipif_ire;
4987 
4988 			/*
4989 			 * Supply a local source address such that inbound
4990 			 * load spreading happens.
4991 			 *
4992 			 * Determine the best source address on this ill for
4993 			 * the destination.
4994 			 *
4995 			 * 1) For broadcast, we should return a broadcast ire
4996 			 *    found above so that upper layers know that the
4997 			 *    destination address is a broadcast address.
4998 			 *
4999 			 * 2) If this is part of a group, select a better
5000 			 *    source address so that better inbound load
5001 			 *    balancing happens. Do the same if the ipif
5002 			 *    is DEPRECATED.
5003 			 *
5004 			 * 3) If the outgoing interface is part of a usesrc
5005 			 *    group, then try selecting a source address from
5006 			 *    the usesrc ILL.
5007 			 */
5008 			if ((dst_ire->ire_zoneid != zoneid &&
5009 			    dst_ire->ire_zoneid != ALL_ZONES) ||
5010 			    (!(dst_ire->ire_flags & RTF_SETSRC)) &&
5011 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
5012 			    ((dst_ill->ill_group != NULL) ||
5013 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
5014 			    (dst_ill->ill_usesrc_ifindex != 0)))) {
5015 				/*
5016 				 * If the destination is reachable via a
5017 				 * given gateway, the selected source address
5018 				 * should be in the same subnet as the gateway.
5019 				 * Otherwise, the destination is not reachable.
5020 				 *
5021 				 * If there are no interfaces on the same subnet
5022 				 * as the destination, ipif_select_source gives
5023 				 * first non-deprecated interface which might be
5024 				 * on a different subnet than the gateway.
5025 				 * This is not desirable. Hence pass the dst_ire
5026 				 * source address to ipif_select_source.
5027 				 * It is sure that the destination is reachable
5028 				 * with the dst_ire source address subnet.
5029 				 * So passing dst_ire source address to
5030 				 * ipif_select_source will make sure that the
5031 				 * selected source will be on the same subnet
5032 				 * as dst_ire source address.
5033 				 */
5034 				ipaddr_t saddr =
5035 				    dst_ire->ire_ipif->ipif_src_addr;
5036 				src_ipif = ipif_select_source(dst_ill,
5037 				    saddr, zoneid);
5038 				if (src_ipif != NULL) {
5039 					if (IS_VNI(src_ipif->ipif_ill)) {
5040 						/*
5041 						 * For VNI there is no
5042 						 * interface route
5043 						 */
5044 						src_addr =
5045 						    src_ipif->ipif_src_addr;
5046 					} else {
5047 						ipif_ire =
5048 						    ipif_to_ire(src_ipif);
5049 						if (ipif_ire != NULL) {
5050 							IRE_REFRELE(dst_ire);
5051 							dst_ire = ipif_ire;
5052 						}
5053 						src_addr =
5054 						    dst_ire->ire_src_addr;
5055 					}
5056 					ipif_refrele(src_ipif);
5057 				} else {
5058 					src_addr = dst_ire->ire_src_addr;
5059 				}
5060 			} else {
5061 				src_addr = dst_ire->ire_src_addr;
5062 			}
5063 		}
5064 	}
5065 
5066 	/*
5067 	 * We do ire_route_lookup() here (and not
5068 	 * interface lookup as we assert that
5069 	 * src_addr should only come from an
5070 	 * UP interface for hard binding.
5071 	 */
5072 	ASSERT(src_ire == NULL);
5073 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5074 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
5075 	/* src_ire must be a local|loopback */
5076 	if (!IRE_IS_LOCAL(src_ire)) {
5077 		if (ip_debug > 2) {
5078 			pr_addr_dbg("ip_bind_connected_v4: bad connected "
5079 			    "src %s\n", AF_INET, &src_addr);
5080 		}
5081 		error = EADDRNOTAVAIL;
5082 		goto bad_addr;
5083 	}
5084 
5085 	/*
5086 	 * If the source address is a loopback address, the
5087 	 * destination had best be local or multicast.
5088 	 * The transports that can't handle multicast will reject
5089 	 * those addresses.
5090 	 */
5091 	if (src_ire->ire_type == IRE_LOOPBACK &&
5092 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5093 		ip1dbg(("ip_bind_connected_v4: bad connected loopback\n"));
5094 		error = -1;
5095 		goto bad_addr;
5096 	}
5097 
5098 	/*
5099 	 * Allow setting new policies. For example, disconnects come
5100 	 * down as ipa_t bind. As we would have set conn_policy_cached
5101 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5102 	 * can change after the disconnect.
5103 	 */
5104 	connp->conn_policy_cached = B_FALSE;
5105 
5106 	/*
5107 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5108 	 * can handle their passed-in conn's.
5109 	 */
5110 
5111 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5112 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5113 	connp->conn_lport = lport;
5114 	connp->conn_fport = fport;
5115 	*src_addrp = src_addr;
5116 
5117 	ASSERT(!(ipsec_policy_set && ire_requested));
5118 	if (ire_requested) {
5119 		iulp_t *ulp_info = NULL;
5120 
5121 		/*
5122 		 * Note that sire will not be NULL if this is an off-link
5123 		 * connection and there is not cache for that dest yet.
5124 		 *
5125 		 * XXX Because of an existing bug, if there are multiple
5126 		 * default routes, the IRE returned now may not be the actual
5127 		 * default route used (default routes are chosen in a
5128 		 * round robin fashion).  So if the metrics for different
5129 		 * default routes are different, we may return the wrong
5130 		 * metrics.  This will not be a problem if the existing
5131 		 * bug is fixed.
5132 		 */
5133 		if (sire != NULL) {
5134 			ulp_info = &(sire->ire_uinfo);
5135 		}
5136 		if (!ip_bind_get_ire_v4(mpp, dst_ire, ulp_info, ipst)) {
5137 			error = -1;
5138 			goto bad_addr;
5139 		}
5140 		mp = *mpp;
5141 	} else if (ipsec_policy_set) {
5142 		if (!ip_bind_ipsec_policy_set(connp, mp)) {
5143 			error = -1;
5144 			goto bad_addr;
5145 		}
5146 	}
5147 
5148 	/*
5149 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5150 	 * we'll cache that.  If we don't, we'll inherit global policy.
5151 	 *
5152 	 * We can't insert until the conn reflects the policy. Note that
5153 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5154 	 * connections where we don't have a policy. This is to prevent
5155 	 * global policy lookups in the inbound path.
5156 	 *
5157 	 * If we insert before we set conn_policy_cached,
5158 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5159 	 * because global policy cound be non-empty. We normally call
5160 	 * ipsec_check_policy() for conn_policy_cached connections only if
5161 	 * ipc_in_enforce_policy is set. But in this case,
5162 	 * conn_policy_cached can get set anytime since we made the
5163 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5164 	 * called, which will make the above assumption false.  Thus, we
5165 	 * need to insert after we set conn_policy_cached.
5166 	 */
5167 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5168 		goto bad_addr;
5169 
5170 	if (fanout_insert) {
5171 		/*
5172 		 * The addresses have been verified. Time to insert in
5173 		 * the correct fanout list.
5174 		 */
5175 		error = ipcl_conn_insert(connp, protocol, src_addr,
5176 		    dst_addr, connp->conn_ports);
5177 	}
5178 
5179 	if (error == 0) {
5180 		connp->conn_fully_bound = B_TRUE;
5181 		/*
5182 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5183 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5184 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5185 		 * ip_xxinfo_return(), which performs further checks
5186 		 * against them and upon success, returns the LSO/MDT info
5187 		 * mblk which we will attach to the bind acknowledgment.
5188 		 */
5189 		if (lso_dst_ire != NULL) {
5190 			mblk_t *lsoinfo_mp;
5191 
5192 			ASSERT(ill->ill_lso_capab != NULL);
5193 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5194 			    ill->ill_name, ill->ill_lso_capab)) != NULL) {
5195 				if (mp == NULL) {
5196 					*mpp = lsoinfo_mp;
5197 				} else {
5198 					linkb(mp, lsoinfo_mp);
5199 				}
5200 			}
5201 		} else if (md_dst_ire != NULL) {
5202 			mblk_t *mdinfo_mp;
5203 
5204 			ASSERT(ill->ill_mdt_capab != NULL);
5205 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5206 			    ill->ill_name, ill->ill_mdt_capab)) != NULL) {
5207 				if (mp == NULL) {
5208 					*mpp = mdinfo_mp;
5209 				} else {
5210 					linkb(mp, mdinfo_mp);
5211 				}
5212 			}
5213 		}
5214 	}
5215 bad_addr:
5216 	if (ipsec_policy_set) {
5217 		ASSERT(mp != NULL);
5218 		freeb(mp);
5219 		/*
5220 		 * As of now assume that nothing else accompanies
5221 		 * IPSEC_POLICY_SET.
5222 		 */
5223 		*mpp = NULL;
5224 	}
5225 	if (src_ire != NULL)
5226 		IRE_REFRELE(src_ire);
5227 	if (dst_ire != NULL)
5228 		IRE_REFRELE(dst_ire);
5229 	if (sire != NULL)
5230 		IRE_REFRELE(sire);
5231 	if (md_dst_ire != NULL)
5232 		IRE_REFRELE(md_dst_ire);
5233 	if (lso_dst_ire != NULL)
5234 		IRE_REFRELE(lso_dst_ire);
5235 	return (error);
5236 }
5237 
5238 int
5239 ip_proto_bind_connected_v4(conn_t *connp, mblk_t **ire_mpp, uint8_t protocol,
5240     ipaddr_t *src_addrp, uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
5241     boolean_t fanout_insert, boolean_t verify_dst)
5242 {
5243 	int error;
5244 	mblk_t	*mp = NULL;
5245 	boolean_t ire_requested;
5246 
5247 	if (ire_mpp)
5248 		mp = *ire_mpp;
5249 	ire_requested = (mp != NULL && DB_TYPE(mp) == IRE_DB_REQ_TYPE);
5250 
5251 	ASSERT(!connp->conn_af_isv6);
5252 	connp->conn_pkt_isv6 = B_FALSE;
5253 	connp->conn_ulp = protocol;
5254 
5255 	/* For raw socket, the local port is not set. */
5256 	if (lport == 0)
5257 		lport = connp->conn_lport;
5258 	error = ip_bind_connected_v4(connp, ire_mpp, protocol,
5259 	    src_addrp, lport, dst_addr, fport, fanout_insert, verify_dst);
5260 	if (error == 0) {
5261 		ip_bind_post_handling(connp, ire_mpp ? *ire_mpp : NULL,
5262 		    ire_requested);
5263 	} else if (error < 0) {
5264 		error = -TBADADDR;
5265 	}
5266 	return (error);
5267 }
5268 
5269 /*
5270  * Get the ire in *mpp. Returns false if it fails (due to lack of space).
5271  * Prefers dst_ire over src_ire.
5272  */
5273 static boolean_t
5274 ip_bind_get_ire_v4(mblk_t **mpp, ire_t *ire, iulp_t *ulp_info, ip_stack_t *ipst)
5275 {
5276 	mblk_t	*mp = *mpp;
5277 	ire_t	*ret_ire;
5278 
5279 	ASSERT(mp != NULL);
5280 
5281 	if (ire != NULL) {
5282 		/*
5283 		 * mp initialized above to IRE_DB_REQ_TYPE
5284 		 * appended mblk. Its <upper protocol>'s
5285 		 * job to make sure there is room.
5286 		 */
5287 		if ((mp->b_datap->db_lim - mp->b_rptr) < sizeof (ire_t))
5288 			return (B_FALSE);
5289 
5290 		mp->b_datap->db_type = IRE_DB_TYPE;
5291 		mp->b_wptr = mp->b_rptr + sizeof (ire_t);
5292 		bcopy(ire, mp->b_rptr, sizeof (ire_t));
5293 		ret_ire = (ire_t *)mp->b_rptr;
5294 		/*
5295 		 * Pass the latest setting of the ip_path_mtu_discovery and
5296 		 * copy the ulp info if any.
5297 		 */
5298 		ret_ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ?
5299 		    IPH_DF : 0;
5300 		if (ulp_info != NULL) {
5301 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5302 			    sizeof (iulp_t));
5303 		}
5304 		ret_ire->ire_mp = mp;
5305 	} else {
5306 		/*
5307 		 * No IRE was found. Remove IRE mblk.
5308 		 */
5309 		*mpp = mp->b_cont;
5310 		freeb(mp);
5311 	}
5312 	return (B_TRUE);
5313 }
5314 
5315 /*
5316  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5317  * the final piece where we don't.  Return a pointer to the first mblk in the
5318  * result, and update the pointer to the next mblk to chew on.  If anything
5319  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5320  * NULL pointer.
5321  */
5322 mblk_t *
5323 ip_carve_mp(mblk_t **mpp, ssize_t len)
5324 {
5325 	mblk_t	*mp0;
5326 	mblk_t	*mp1;
5327 	mblk_t	*mp2;
5328 
5329 	if (!len || !mpp || !(mp0 = *mpp))
5330 		return (NULL);
5331 	/* If we aren't going to consume the first mblk, we need a dup. */
5332 	if (mp0->b_wptr - mp0->b_rptr > len) {
5333 		mp1 = dupb(mp0);
5334 		if (mp1) {
5335 			/* Partition the data between the two mblks. */
5336 			mp1->b_wptr = mp1->b_rptr + len;
5337 			mp0->b_rptr = mp1->b_wptr;
5338 			/*
5339 			 * after adjustments if mblk not consumed is now
5340 			 * unaligned, try to align it. If this fails free
5341 			 * all messages and let upper layer recover.
5342 			 */
5343 			if (!OK_32PTR(mp0->b_rptr)) {
5344 				if (!pullupmsg(mp0, -1)) {
5345 					freemsg(mp0);
5346 					freemsg(mp1);
5347 					*mpp = NULL;
5348 					return (NULL);
5349 				}
5350 			}
5351 		}
5352 		return (mp1);
5353 	}
5354 	/* Eat through as many mblks as we need to get len bytes. */
5355 	len -= mp0->b_wptr - mp0->b_rptr;
5356 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5357 		if (mp2->b_wptr - mp2->b_rptr > len) {
5358 			/*
5359 			 * We won't consume the entire last mblk.  Like
5360 			 * above, dup and partition it.
5361 			 */
5362 			mp1->b_cont = dupb(mp2);
5363 			mp1 = mp1->b_cont;
5364 			if (!mp1) {
5365 				/*
5366 				 * Trouble.  Rather than go to a lot of
5367 				 * trouble to clean up, we free the messages.
5368 				 * This won't be any worse than losing it on
5369 				 * the wire.
5370 				 */
5371 				freemsg(mp0);
5372 				freemsg(mp2);
5373 				*mpp = NULL;
5374 				return (NULL);
5375 			}
5376 			mp1->b_wptr = mp1->b_rptr + len;
5377 			mp2->b_rptr = mp1->b_wptr;
5378 			/*
5379 			 * after adjustments if mblk not consumed is now
5380 			 * unaligned, try to align it. If this fails free
5381 			 * all messages and let upper layer recover.
5382 			 */
5383 			if (!OK_32PTR(mp2->b_rptr)) {
5384 				if (!pullupmsg(mp2, -1)) {
5385 					freemsg(mp0);
5386 					freemsg(mp2);
5387 					*mpp = NULL;
5388 					return (NULL);
5389 				}
5390 			}
5391 			*mpp = mp2;
5392 			return (mp0);
5393 		}
5394 		/* Decrement len by the amount we just got. */
5395 		len -= mp2->b_wptr - mp2->b_rptr;
5396 	}
5397 	/*
5398 	 * len should be reduced to zero now.  If not our caller has
5399 	 * screwed up.
5400 	 */
5401 	if (len) {
5402 		/* Shouldn't happen! */
5403 		freemsg(mp0);
5404 		*mpp = NULL;
5405 		return (NULL);
5406 	}
5407 	/*
5408 	 * We consumed up to exactly the end of an mblk.  Detach the part
5409 	 * we are returning from the rest of the chain.
5410 	 */
5411 	mp1->b_cont = NULL;
5412 	*mpp = mp2;
5413 	return (mp0);
5414 }
5415 
5416 /* The ill stream is being unplumbed. Called from ip_close */
5417 int
5418 ip_modclose(ill_t *ill)
5419 {
5420 	boolean_t success;
5421 	ipsq_t	*ipsq;
5422 	ipif_t	*ipif;
5423 	queue_t	*q = ill->ill_rq;
5424 	ip_stack_t	*ipst = ill->ill_ipst;
5425 
5426 	/*
5427 	 * The punlink prior to this may have initiated a capability
5428 	 * negotiation. But ipsq_enter will block until that finishes or
5429 	 * times out.
5430 	 */
5431 	success = ipsq_enter(ill, B_FALSE, NEW_OP);
5432 
5433 	/*
5434 	 * Open/close/push/pop is guaranteed to be single threaded
5435 	 * per stream by STREAMS. FS guarantees that all references
5436 	 * from top are gone before close is called. So there can't
5437 	 * be another close thread that has set CONDEMNED on this ill.
5438 	 * and cause ipsq_enter to return failure.
5439 	 */
5440 	ASSERT(success);
5441 	ipsq = ill->ill_phyint->phyint_ipsq;
5442 
5443 	/*
5444 	 * Mark it condemned. No new reference will be made to this ill.
5445 	 * Lookup functions will return an error. Threads that try to
5446 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5447 	 * that the refcnt will drop down to zero.
5448 	 */
5449 	mutex_enter(&ill->ill_lock);
5450 	ill->ill_state_flags |= ILL_CONDEMNED;
5451 	for (ipif = ill->ill_ipif; ipif != NULL;
5452 	    ipif = ipif->ipif_next) {
5453 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5454 	}
5455 	/*
5456 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5457 	 * returns  error if ILL_CONDEMNED is set
5458 	 */
5459 	cv_broadcast(&ill->ill_cv);
5460 	mutex_exit(&ill->ill_lock);
5461 
5462 	/*
5463 	 * Send all the deferred DLPI messages downstream which came in
5464 	 * during the small window right before ipsq_enter(). We do this
5465 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5466 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5467 	 */
5468 	ill_dlpi_send_deferred(ill);
5469 
5470 	/*
5471 	 * Shut down fragmentation reassembly.
5472 	 * ill_frag_timer won't start a timer again.
5473 	 * Now cancel any existing timer
5474 	 */
5475 	(void) untimeout(ill->ill_frag_timer_id);
5476 	(void) ill_frag_timeout(ill, 0);
5477 
5478 	/*
5479 	 * If MOVE was in progress, clear the
5480 	 * move_in_progress fields also.
5481 	 */
5482 	if (ill->ill_move_in_progress) {
5483 		ILL_CLEAR_MOVE(ill);
5484 	}
5485 
5486 	/*
5487 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5488 	 * this ill. Then wait for the refcnts to drop to zero.
5489 	 * ill_is_freeable checks whether the ill is really quiescent.
5490 	 * Then make sure that threads that are waiting to enter the
5491 	 * ipsq have seen the error returned by ipsq_enter and have
5492 	 * gone away. Then we call ill_delete_tail which does the
5493 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
5494 	 */
5495 	ill_delete(ill);
5496 	mutex_enter(&ill->ill_lock);
5497 	while (!ill_is_freeable(ill))
5498 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5499 	while (ill->ill_waiters)
5500 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5501 
5502 	mutex_exit(&ill->ill_lock);
5503 
5504 	/*
5505 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
5506 	 * it held until the end of the function since the cleanup
5507 	 * below needs to be able to use the ip_stack_t.
5508 	 */
5509 	netstack_hold(ipst->ips_netstack);
5510 
5511 	/* qprocsoff is called in ill_delete_tail */
5512 	ill_delete_tail(ill);
5513 	ASSERT(ill->ill_ipst == NULL);
5514 
5515 	/*
5516 	 * Walk through all upper (conn) streams and qenable
5517 	 * those that have queued data.
5518 	 * close synchronization needs this to
5519 	 * be done to ensure that all upper layers blocked
5520 	 * due to flow control to the closing device
5521 	 * get unblocked.
5522 	 */
5523 	ip1dbg(("ip_wsrv: walking\n"));
5524 	conn_walk_drain(ipst);
5525 
5526 	mutex_enter(&ipst->ips_ip_mi_lock);
5527 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
5528 	mutex_exit(&ipst->ips_ip_mi_lock);
5529 
5530 	/*
5531 	 * credp could be null if the open didn't succeed and ip_modopen
5532 	 * itself calls ip_close.
5533 	 */
5534 	if (ill->ill_credp != NULL)
5535 		crfree(ill->ill_credp);
5536 
5537 	/*
5538 	 * Now we are done with the module close pieces that
5539 	 * need the netstack_t.
5540 	 */
5541 	netstack_rele(ipst->ips_netstack);
5542 
5543 	mi_close_free((IDP)ill);
5544 	q->q_ptr = WR(q)->q_ptr = NULL;
5545 
5546 	ipsq_exit(ipsq);
5547 
5548 	return (0);
5549 }
5550 
5551 /*
5552  * This is called as part of close() for IP, UDP, ICMP, and RTS
5553  * in order to quiesce the conn.
5554  */
5555 void
5556 ip_quiesce_conn(conn_t *connp)
5557 {
5558 	boolean_t	drain_cleanup_reqd = B_FALSE;
5559 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5560 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5561 	ip_stack_t	*ipst;
5562 
5563 	ASSERT(!IPCL_IS_TCP(connp));
5564 	ipst = connp->conn_netstack->netstack_ip;
5565 
5566 	/*
5567 	 * Mark the conn as closing, and this conn must not be
5568 	 * inserted in future into any list. Eg. conn_drain_insert(),
5569 	 * won't insert this conn into the conn_drain_list.
5570 	 * Similarly ill_pending_mp_add() will not add any mp to
5571 	 * the pending mp list, after this conn has started closing.
5572 	 *
5573 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5574 	 * cannot get set henceforth.
5575 	 */
5576 	mutex_enter(&connp->conn_lock);
5577 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5578 	connp->conn_state_flags |= CONN_CLOSING;
5579 	if (connp->conn_idl != NULL)
5580 		drain_cleanup_reqd = B_TRUE;
5581 	if (connp->conn_oper_pending_ill != NULL)
5582 		conn_ioctl_cleanup_reqd = B_TRUE;
5583 	if (connp->conn_dhcpinit_ill != NULL) {
5584 		ASSERT(connp->conn_dhcpinit_ill->ill_dhcpinit != 0);
5585 		atomic_dec_32(&connp->conn_dhcpinit_ill->ill_dhcpinit);
5586 		connp->conn_dhcpinit_ill = NULL;
5587 	}
5588 	if (connp->conn_ilg_inuse != 0)
5589 		ilg_cleanup_reqd = B_TRUE;
5590 	mutex_exit(&connp->conn_lock);
5591 
5592 	if (conn_ioctl_cleanup_reqd)
5593 		conn_ioctl_cleanup(connp);
5594 
5595 	if (is_system_labeled() && connp->conn_anon_port) {
5596 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5597 		    connp->conn_mlp_type, connp->conn_ulp,
5598 		    ntohs(connp->conn_lport), B_FALSE);
5599 		connp->conn_anon_port = 0;
5600 	}
5601 	connp->conn_mlp_type = mlptSingle;
5602 
5603 	/*
5604 	 * Remove this conn from any fanout list it is on.
5605 	 * and then wait for any threads currently operating
5606 	 * on this endpoint to finish
5607 	 */
5608 	ipcl_hash_remove(connp);
5609 
5610 	/*
5611 	 * Remove this conn from the drain list, and do
5612 	 * any other cleanup that may be required.
5613 	 * (Only non-tcp streams may have a non-null conn_idl.
5614 	 * TCP streams are never flow controlled, and
5615 	 * conn_idl will be null)
5616 	 */
5617 	if (drain_cleanup_reqd)
5618 		conn_drain_tail(connp, B_TRUE);
5619 
5620 	if (connp == ipst->ips_ip_g_mrouter)
5621 		(void) ip_mrouter_done(NULL, ipst);
5622 
5623 	if (ilg_cleanup_reqd)
5624 		ilg_delete_all(connp);
5625 
5626 	conn_delete_ire(connp, NULL);
5627 
5628 	/*
5629 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5630 	 * callers from write side can't be there now because close
5631 	 * is in progress. The only other caller is ipcl_walk
5632 	 * which checks for the condemned flag.
5633 	 */
5634 	mutex_enter(&connp->conn_lock);
5635 	connp->conn_state_flags |= CONN_CONDEMNED;
5636 	while (connp->conn_ref != 1)
5637 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5638 	connp->conn_state_flags |= CONN_QUIESCED;
5639 	mutex_exit(&connp->conn_lock);
5640 }
5641 
5642 /* ARGSUSED */
5643 int
5644 ip_close(queue_t *q, int flags)
5645 {
5646 	conn_t		*connp;
5647 
5648 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5649 
5650 	/*
5651 	 * Call the appropriate delete routine depending on whether this is
5652 	 * a module or device.
5653 	 */
5654 	if (WR(q)->q_next != NULL) {
5655 		/* This is a module close */
5656 		return (ip_modclose((ill_t *)q->q_ptr));
5657 	}
5658 
5659 	connp = q->q_ptr;
5660 	ip_quiesce_conn(connp);
5661 
5662 	qprocsoff(q);
5663 
5664 	/*
5665 	 * Now we are truly single threaded on this stream, and can
5666 	 * delete the things hanging off the connp, and finally the connp.
5667 	 * We removed this connp from the fanout list, it cannot be
5668 	 * accessed thru the fanouts, and we already waited for the
5669 	 * conn_ref to drop to 0. We are already in close, so
5670 	 * there cannot be any other thread from the top. qprocsoff
5671 	 * has completed, and service has completed or won't run in
5672 	 * future.
5673 	 */
5674 	ASSERT(connp->conn_ref == 1);
5675 
5676 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
5677 
5678 	connp->conn_ref--;
5679 	ipcl_conn_destroy(connp);
5680 
5681 	q->q_ptr = WR(q)->q_ptr = NULL;
5682 	return (0);
5683 }
5684 
5685 /*
5686  * Wapper around putnext() so that ip_rts_request can merely use
5687  * conn_recv.
5688  */
5689 /*ARGSUSED2*/
5690 static void
5691 ip_conn_input(void *arg1, mblk_t *mp, void *arg2)
5692 {
5693 	conn_t *connp = (conn_t *)arg1;
5694 
5695 	putnext(connp->conn_rq, mp);
5696 }
5697 
5698 /*
5699  * Called when the module is about to be unloaded
5700  */
5701 void
5702 ip_ddi_destroy(void)
5703 {
5704 	tnet_fini();
5705 
5706 	icmp_ddi_g_destroy();
5707 	rts_ddi_g_destroy();
5708 	udp_ddi_g_destroy();
5709 	sctp_ddi_g_destroy();
5710 	tcp_ddi_g_destroy();
5711 	ipsec_policy_g_destroy();
5712 	ipcl_g_destroy();
5713 	ip_net_g_destroy();
5714 	ip_ire_g_fini();
5715 	inet_minor_destroy(ip_minor_arena_sa);
5716 #if defined(_LP64)
5717 	inet_minor_destroy(ip_minor_arena_la);
5718 #endif
5719 
5720 #ifdef DEBUG
5721 	list_destroy(&ip_thread_list);
5722 	rw_destroy(&ip_thread_rwlock);
5723 	tsd_destroy(&ip_thread_data);
5724 #endif
5725 
5726 	netstack_unregister(NS_IP);
5727 }
5728 
5729 /*
5730  * First step in cleanup.
5731  */
5732 /* ARGSUSED */
5733 static void
5734 ip_stack_shutdown(netstackid_t stackid, void *arg)
5735 {
5736 	ip_stack_t *ipst = (ip_stack_t *)arg;
5737 
5738 #ifdef NS_DEBUG
5739 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
5740 #endif
5741 
5742 	/* Get rid of loopback interfaces and their IREs */
5743 	ip_loopback_cleanup(ipst);
5744 
5745 	/*
5746 	 * The *_hook_shutdown()s start the process of notifying any
5747 	 * consumers that things are going away.... nothing is destroyed.
5748 	 */
5749 	ipv4_hook_shutdown(ipst);
5750 	ipv6_hook_shutdown(ipst);
5751 
5752 	mutex_enter(&ipst->ips_capab_taskq_lock);
5753 	ipst->ips_capab_taskq_quit = B_TRUE;
5754 	cv_signal(&ipst->ips_capab_taskq_cv);
5755 	mutex_exit(&ipst->ips_capab_taskq_lock);
5756 }
5757 
5758 /*
5759  * Free the IP stack instance.
5760  */
5761 static void
5762 ip_stack_fini(netstackid_t stackid, void *arg)
5763 {
5764 	ip_stack_t *ipst = (ip_stack_t *)arg;
5765 	int ret;
5766 
5767 	/*
5768 	 * At this point, all of the notifications that the events and
5769 	 * protocols are going away have been run, meaning that we can
5770 	 * now set about starting to clean things up.
5771 	 */
5772 	ipv4_hook_destroy(ipst);
5773 	ipv6_hook_destroy(ipst);
5774 	ip_net_destroy(ipst);
5775 
5776 	mutex_destroy(&ipst->ips_capab_taskq_lock);
5777 	cv_destroy(&ipst->ips_capab_taskq_cv);
5778 	list_destroy(&ipst->ips_capab_taskq_list);
5779 
5780 #ifdef NS_DEBUG
5781 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5782 #endif
5783 	rw_destroy(&ipst->ips_srcid_lock);
5784 
5785 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5786 	ipst->ips_ip_mibkp = NULL;
5787 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5788 	ipst->ips_icmp_mibkp = NULL;
5789 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5790 	ipst->ips_ip_kstat = NULL;
5791 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5792 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5793 	ipst->ips_ip6_kstat = NULL;
5794 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5795 
5796 	nd_free(&ipst->ips_ip_g_nd);
5797 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5798 	ipst->ips_param_arr = NULL;
5799 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5800 	ipst->ips_ndp_arr = NULL;
5801 
5802 	ip_mrouter_stack_destroy(ipst);
5803 
5804 	mutex_destroy(&ipst->ips_ip_mi_lock);
5805 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5806 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5807 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5808 
5809 	ret = untimeout(ipst->ips_igmp_timeout_id);
5810 	if (ret == -1) {
5811 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5812 	} else {
5813 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5814 		ipst->ips_igmp_timeout_id = 0;
5815 	}
5816 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5817 	if (ret == -1) {
5818 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5819 	} else {
5820 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5821 		ipst->ips_igmp_slowtimeout_id = 0;
5822 	}
5823 	ret = untimeout(ipst->ips_mld_timeout_id);
5824 	if (ret == -1) {
5825 		ASSERT(ipst->ips_mld_timeout_id == 0);
5826 	} else {
5827 		ASSERT(ipst->ips_mld_timeout_id != 0);
5828 		ipst->ips_mld_timeout_id = 0;
5829 	}
5830 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5831 	if (ret == -1) {
5832 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5833 	} else {
5834 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5835 		ipst->ips_mld_slowtimeout_id = 0;
5836 	}
5837 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5838 	if (ret == -1) {
5839 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5840 	} else {
5841 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5842 		ipst->ips_ip_ire_expire_id = 0;
5843 	}
5844 
5845 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5846 	mutex_destroy(&ipst->ips_mld_timer_lock);
5847 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5848 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5849 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5850 	rw_destroy(&ipst->ips_ill_g_lock);
5851 
5852 	ipobs_fini(ipst);
5853 	ip_ire_fini(ipst);
5854 	ip6_asp_free(ipst);
5855 	conn_drain_fini(ipst);
5856 	ipcl_destroy(ipst);
5857 
5858 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5859 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5860 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5861 	ipst->ips_ndp4 = NULL;
5862 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5863 	ipst->ips_ndp6 = NULL;
5864 
5865 	if (ipst->ips_loopback_ksp != NULL) {
5866 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5867 		ipst->ips_loopback_ksp = NULL;
5868 	}
5869 
5870 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5871 	ipst->ips_phyint_g_list = NULL;
5872 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5873 	ipst->ips_ill_g_heads = NULL;
5874 
5875 	ldi_ident_release(ipst->ips_ldi_ident);
5876 	kmem_free(ipst, sizeof (*ipst));
5877 }
5878 
5879 /*
5880  * This function is called from the TSD destructor, and is used to debug
5881  * reference count issues in IP. See block comment in <inet/ip_if.h> for
5882  * details.
5883  */
5884 static void
5885 ip_thread_exit(void *phash)
5886 {
5887 	th_hash_t *thh = phash;
5888 
5889 	rw_enter(&ip_thread_rwlock, RW_WRITER);
5890 	list_remove(&ip_thread_list, thh);
5891 	rw_exit(&ip_thread_rwlock);
5892 	mod_hash_destroy_hash(thh->thh_hash);
5893 	kmem_free(thh, sizeof (*thh));
5894 }
5895 
5896 /*
5897  * Called when the IP kernel module is loaded into the kernel
5898  */
5899 void
5900 ip_ddi_init(void)
5901 {
5902 	ip_squeue_flag = ip_squeue_switch(ip_squeue_enter);
5903 
5904 	/*
5905 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5906 	 * initial devices: ip, ip6, tcp, tcp6.
5907 	 */
5908 	/*
5909 	 * If this is a 64-bit kernel, then create two separate arenas -
5910 	 * one for TLIs in the range of INET_MIN_DEV+2 through 2^^18-1, and the
5911 	 * other for socket apps in the range 2^^18 through 2^^32-1.
5912 	 */
5913 	ip_minor_arena_la = NULL;
5914 	ip_minor_arena_sa = NULL;
5915 #if defined(_LP64)
5916 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5917 	    INET_MIN_DEV + 2, MAXMIN32, KM_SLEEP)) == NULL) {
5918 		cmn_err(CE_PANIC,
5919 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5920 	}
5921 	if ((ip_minor_arena_la = inet_minor_create("ip_minor_arena_la",
5922 	    MAXMIN32 + 1, MAXMIN64, KM_SLEEP)) == NULL) {
5923 		cmn_err(CE_PANIC,
5924 		    "ip_ddi_init: ip_minor_arena_la creation failed\n");
5925 	}
5926 #else
5927 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5928 	    INET_MIN_DEV + 2, MAXMIN, KM_SLEEP)) == NULL) {
5929 		cmn_err(CE_PANIC,
5930 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5931 	}
5932 #endif
5933 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5934 
5935 	ipcl_g_init();
5936 	ip_ire_g_init();
5937 	ip_net_g_init();
5938 
5939 #ifdef DEBUG
5940 	tsd_create(&ip_thread_data, ip_thread_exit);
5941 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
5942 	list_create(&ip_thread_list, sizeof (th_hash_t),
5943 	    offsetof(th_hash_t, thh_link));
5944 #endif
5945 
5946 	/*
5947 	 * We want to be informed each time a stack is created or
5948 	 * destroyed in the kernel, so we can maintain the
5949 	 * set of udp_stack_t's.
5950 	 */
5951 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
5952 	    ip_stack_fini);
5953 
5954 	ipsec_policy_g_init();
5955 	tcp_ddi_g_init();
5956 	sctp_ddi_g_init();
5957 
5958 	tnet_init();
5959 
5960 	udp_ddi_g_init();
5961 	rts_ddi_g_init();
5962 	icmp_ddi_g_init();
5963 }
5964 
5965 /*
5966  * Initialize the IP stack instance.
5967  */
5968 static void *
5969 ip_stack_init(netstackid_t stackid, netstack_t *ns)
5970 {
5971 	ip_stack_t	*ipst;
5972 	ipparam_t	*pa;
5973 	ipndp_t		*na;
5974 	major_t		major;
5975 
5976 #ifdef NS_DEBUG
5977 	printf("ip_stack_init(stack %d)\n", stackid);
5978 #endif
5979 
5980 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
5981 	ipst->ips_netstack = ns;
5982 
5983 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
5984 	    KM_SLEEP);
5985 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
5986 	    KM_SLEEP);
5987 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5988 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5989 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5990 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5991 
5992 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5993 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5994 	ipst->ips_igmp_deferred_next = INFINITY;
5995 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5996 	ipst->ips_mld_deferred_next = INFINITY;
5997 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5998 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5999 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
6000 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
6001 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
6002 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
6003 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
6004 
6005 	ipcl_init(ipst);
6006 	ip_ire_init(ipst);
6007 	ip6_asp_init(ipst);
6008 	ipif_init(ipst);
6009 	conn_drain_init(ipst);
6010 	ip_mrouter_stack_init(ipst);
6011 
6012 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
6013 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
6014 
6015 	ipst->ips_ip_multirt_log_interval = 1000;
6016 
6017 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
6018 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
6019 	ipst->ips_ill_index = 1;
6020 
6021 	ipst->ips_saved_ip_g_forward = -1;
6022 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
6023 
6024 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
6025 	ipst->ips_param_arr = pa;
6026 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
6027 
6028 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
6029 	ipst->ips_ndp_arr = na;
6030 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
6031 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
6032 	    (caddr_t)&ipst->ips_ip_g_forward;
6033 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
6034 	    (caddr_t)&ipst->ips_ipv6_forward;
6035 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
6036 	    "ip_cgtp_filter") == 0);
6037 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
6038 	    (caddr_t)&ipst->ips_ip_cgtp_filter;
6039 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_name,
6040 	    "ipmp_hook_emulation") == 0);
6041 	ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_data =
6042 	    (caddr_t)&ipst->ips_ipmp_hook_emulation;
6043 
6044 	(void) ip_param_register(&ipst->ips_ip_g_nd,
6045 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
6046 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
6047 
6048 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
6049 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
6050 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
6051 	ipst->ips_ip6_kstat =
6052 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
6053 
6054 	ipst->ips_ipmp_enable_failback = B_TRUE;
6055 
6056 	ipst->ips_ip_src_id = 1;
6057 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
6058 
6059 	ipobs_init(ipst);
6060 	ip_net_init(ipst, ns);
6061 	ipv4_hook_init(ipst);
6062 	ipv6_hook_init(ipst);
6063 
6064 	/*
6065 	 * Create the taskq dispatcher thread and initialize related stuff.
6066 	 */
6067 	ipst->ips_capab_taskq_thread = thread_create(NULL, 0,
6068 	    ill_taskq_dispatch, ipst, 0, &p0, TS_RUN, minclsyspri);
6069 	mutex_init(&ipst->ips_capab_taskq_lock, NULL, MUTEX_DEFAULT, NULL);
6070 	cv_init(&ipst->ips_capab_taskq_cv, NULL, CV_DEFAULT, NULL);
6071 	list_create(&ipst->ips_capab_taskq_list, sizeof (mblk_t),
6072 	    offsetof(mblk_t, b_next));
6073 
6074 	major = mod_name_to_major(INET_NAME);
6075 	(void) ldi_ident_from_major(major, &ipst->ips_ldi_ident);
6076 	return (ipst);
6077 }
6078 
6079 /*
6080  * Allocate and initialize a DLPI template of the specified length.  (May be
6081  * called as writer.)
6082  */
6083 mblk_t *
6084 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
6085 {
6086 	mblk_t	*mp;
6087 
6088 	mp = allocb(len, BPRI_MED);
6089 	if (!mp)
6090 		return (NULL);
6091 
6092 	/*
6093 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
6094 	 * of which we don't seem to use) are sent with M_PCPROTO, and
6095 	 * that other DLPI are M_PROTO.
6096 	 */
6097 	if (prim == DL_INFO_REQ) {
6098 		mp->b_datap->db_type = M_PCPROTO;
6099 	} else {
6100 		mp->b_datap->db_type = M_PROTO;
6101 	}
6102 
6103 	mp->b_wptr = mp->b_rptr + len;
6104 	bzero(mp->b_rptr, len);
6105 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6106 	return (mp);
6107 }
6108 
6109 /*
6110  * Debug formatting routine.  Returns a character string representation of the
6111  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6112  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6113  *
6114  * Once the ndd table-printing interfaces are removed, this can be changed to
6115  * standard dotted-decimal form.
6116  */
6117 char *
6118 ip_dot_addr(ipaddr_t addr, char *buf)
6119 {
6120 	uint8_t *ap = (uint8_t *)&addr;
6121 
6122 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6123 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6124 	return (buf);
6125 }
6126 
6127 /*
6128  * Write the given MAC address as a printable string in the usual colon-
6129  * separated format.
6130  */
6131 const char *
6132 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6133 {
6134 	char *bp;
6135 
6136 	if (alen == 0 || buflen < 4)
6137 		return ("?");
6138 	bp = buf;
6139 	for (;;) {
6140 		/*
6141 		 * If there are more MAC address bytes available, but we won't
6142 		 * have any room to print them, then add "..." to the string
6143 		 * instead.  See below for the 'magic number' explanation.
6144 		 */
6145 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6146 			(void) strcpy(bp, "...");
6147 			break;
6148 		}
6149 		(void) sprintf(bp, "%02x", *addr++);
6150 		bp += 2;
6151 		if (--alen == 0)
6152 			break;
6153 		*bp++ = ':';
6154 		buflen -= 3;
6155 		/*
6156 		 * At this point, based on the first 'if' statement above,
6157 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6158 		 * buflen >= 4.  The first case leaves room for the final "xx"
6159 		 * number and trailing NUL byte.  The second leaves room for at
6160 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6161 		 * that statement.
6162 		 */
6163 	}
6164 	return (buf);
6165 }
6166 
6167 /*
6168  * Send an ICMP error after patching up the packet appropriately.  Returns
6169  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6170  */
6171 static boolean_t
6172 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6173     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6174     zoneid_t zoneid, ip_stack_t *ipst)
6175 {
6176 	ipha_t *ipha;
6177 	mblk_t *first_mp;
6178 	boolean_t secure;
6179 	unsigned char db_type;
6180 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6181 
6182 	first_mp = mp;
6183 	if (mctl_present) {
6184 		mp = mp->b_cont;
6185 		secure = ipsec_in_is_secure(first_mp);
6186 		ASSERT(mp != NULL);
6187 	} else {
6188 		/*
6189 		 * If this is an ICMP error being reported - which goes
6190 		 * up as M_CTLs, we need to convert them to M_DATA till
6191 		 * we finish checking with global policy because
6192 		 * ipsec_check_global_policy() assumes M_DATA as clear
6193 		 * and M_CTL as secure.
6194 		 */
6195 		db_type = DB_TYPE(mp);
6196 		DB_TYPE(mp) = M_DATA;
6197 		secure = B_FALSE;
6198 	}
6199 	/*
6200 	 * We are generating an icmp error for some inbound packet.
6201 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6202 	 * Before we generate an error, check with global policy
6203 	 * to see whether this is allowed to enter the system. As
6204 	 * there is no "conn", we are checking with global policy.
6205 	 */
6206 	ipha = (ipha_t *)mp->b_rptr;
6207 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6208 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6209 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6210 		if (first_mp == NULL)
6211 			return (B_FALSE);
6212 	}
6213 
6214 	if (!mctl_present)
6215 		DB_TYPE(mp) = db_type;
6216 
6217 	if (flags & IP_FF_SEND_ICMP) {
6218 		if (flags & IP_FF_HDR_COMPLETE) {
6219 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6220 				freemsg(first_mp);
6221 				return (B_TRUE);
6222 			}
6223 		}
6224 		if (flags & IP_FF_CKSUM) {
6225 			/*
6226 			 * Have to correct checksum since
6227 			 * the packet might have been
6228 			 * fragmented and the reassembly code in ip_rput
6229 			 * does not restore the IP checksum.
6230 			 */
6231 			ipha->ipha_hdr_checksum = 0;
6232 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6233 		}
6234 		switch (icmp_type) {
6235 		case ICMP_DEST_UNREACHABLE:
6236 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6237 			    ipst);
6238 			break;
6239 		default:
6240 			freemsg(first_mp);
6241 			break;
6242 		}
6243 	} else {
6244 		freemsg(first_mp);
6245 		return (B_FALSE);
6246 	}
6247 
6248 	return (B_TRUE);
6249 }
6250 
6251 /*
6252  * Used to send an ICMP error message when a packet is received for
6253  * a protocol that is not supported. The mblk passed as argument
6254  * is consumed by this function.
6255  */
6256 void
6257 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6258     ip_stack_t *ipst)
6259 {
6260 	mblk_t *mp;
6261 	ipha_t *ipha;
6262 	ill_t *ill;
6263 	ipsec_in_t *ii;
6264 
6265 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6266 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6267 
6268 	mp = ipsec_mp->b_cont;
6269 	ipsec_mp->b_cont = NULL;
6270 	ipha = (ipha_t *)mp->b_rptr;
6271 	/* Get ill from index in ipsec_in_t. */
6272 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6273 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6274 	    ipst);
6275 	if (ill != NULL) {
6276 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6277 			if (ip_fanout_send_icmp(q, mp, flags,
6278 			    ICMP_DEST_UNREACHABLE,
6279 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6280 				BUMP_MIB(ill->ill_ip_mib,
6281 				    ipIfStatsInUnknownProtos);
6282 			}
6283 		} else {
6284 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6285 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6286 			    0, B_FALSE, zoneid, ipst)) {
6287 				BUMP_MIB(ill->ill_ip_mib,
6288 				    ipIfStatsInUnknownProtos);
6289 			}
6290 		}
6291 		ill_refrele(ill);
6292 	} else { /* re-link for the freemsg() below. */
6293 		ipsec_mp->b_cont = mp;
6294 	}
6295 
6296 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6297 	freemsg(ipsec_mp);
6298 }
6299 
6300 /*
6301  * See if the inbound datagram has had IPsec processing applied to it.
6302  */
6303 boolean_t
6304 ipsec_in_is_secure(mblk_t *ipsec_mp)
6305 {
6306 	ipsec_in_t *ii;
6307 
6308 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6309 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6310 
6311 	if (ii->ipsec_in_loopback) {
6312 		return (ii->ipsec_in_secure);
6313 	} else {
6314 		return (ii->ipsec_in_ah_sa != NULL ||
6315 		    ii->ipsec_in_esp_sa != NULL ||
6316 		    ii->ipsec_in_decaps);
6317 	}
6318 }
6319 
6320 /*
6321  * Handle protocols with which IP is less intimate.  There
6322  * can be more than one stream bound to a particular
6323  * protocol.  When this is the case, normally each one gets a copy
6324  * of any incoming packets.
6325  *
6326  * IPsec NOTE :
6327  *
6328  * Don't allow a secure packet going up a non-secure connection.
6329  * We don't allow this because
6330  *
6331  * 1) Reply might go out in clear which will be dropped at
6332  *    the sending side.
6333  * 2) If the reply goes out in clear it will give the
6334  *    adversary enough information for getting the key in
6335  *    most of the cases.
6336  *
6337  * Moreover getting a secure packet when we expect clear
6338  * implies that SA's were added without checking for
6339  * policy on both ends. This should not happen once ISAKMP
6340  * is used to negotiate SAs as SAs will be added only after
6341  * verifying the policy.
6342  *
6343  * NOTE : If the packet was tunneled and not multicast we only send
6344  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6345  * back to delivering packets to AF_INET6 raw sockets.
6346  *
6347  * IPQoS Notes:
6348  * Once we have determined the client, invoke IPPF processing.
6349  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6350  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6351  * ip_policy will be false.
6352  *
6353  * Zones notes:
6354  * Currently only applications in the global zone can create raw sockets for
6355  * protocols other than ICMP. So unlike the broadcast / multicast case of
6356  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6357  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6358  */
6359 static void
6360 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6361     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6362     zoneid_t zoneid)
6363 {
6364 	queue_t	*rq;
6365 	mblk_t	*mp1, *first_mp1;
6366 	uint_t	protocol = ipha->ipha_protocol;
6367 	ipaddr_t dst;
6368 	boolean_t one_only;
6369 	mblk_t *first_mp = mp;
6370 	boolean_t secure;
6371 	uint32_t ill_index;
6372 	conn_t	*connp, *first_connp, *next_connp;
6373 	connf_t	*connfp;
6374 	boolean_t shared_addr;
6375 	mib2_ipIfStatsEntry_t *mibptr;
6376 	ip_stack_t *ipst = recv_ill->ill_ipst;
6377 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6378 
6379 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6380 	if (mctl_present) {
6381 		mp = first_mp->b_cont;
6382 		secure = ipsec_in_is_secure(first_mp);
6383 		ASSERT(mp != NULL);
6384 	} else {
6385 		secure = B_FALSE;
6386 	}
6387 	dst = ipha->ipha_dst;
6388 	/*
6389 	 * If the packet was tunneled and not multicast we only send to it
6390 	 * the first match.
6391 	 */
6392 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6393 	    !CLASSD(dst));
6394 
6395 	shared_addr = (zoneid == ALL_ZONES);
6396 	if (shared_addr) {
6397 		/*
6398 		 * We don't allow multilevel ports for raw IP, so no need to
6399 		 * check for that here.
6400 		 */
6401 		zoneid = tsol_packet_to_zoneid(mp);
6402 	}
6403 
6404 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6405 	mutex_enter(&connfp->connf_lock);
6406 	connp = connfp->connf_head;
6407 	for (connp = connfp->connf_head; connp != NULL;
6408 	    connp = connp->conn_next) {
6409 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6410 		    zoneid) &&
6411 		    (!is_system_labeled() ||
6412 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6413 		    connp))) {
6414 			break;
6415 		}
6416 	}
6417 
6418 	if (connp == NULL) {
6419 		/*
6420 		 * No one bound to these addresses.  Is
6421 		 * there a client that wants all
6422 		 * unclaimed datagrams?
6423 		 */
6424 		mutex_exit(&connfp->connf_lock);
6425 		/*
6426 		 * Check for IPPROTO_ENCAP...
6427 		 */
6428 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6429 			/*
6430 			 * If an IPsec mblk is here on a multicast
6431 			 * tunnel (using ip_mroute stuff), check policy here,
6432 			 * THEN ship off to ip_mroute_decap().
6433 			 *
6434 			 * BTW,  If I match a configured IP-in-IP
6435 			 * tunnel, this path will not be reached, and
6436 			 * ip_mroute_decap will never be called.
6437 			 */
6438 			first_mp = ipsec_check_global_policy(first_mp, connp,
6439 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6440 			if (first_mp != NULL) {
6441 				if (mctl_present)
6442 					freeb(first_mp);
6443 				ip_mroute_decap(q, mp, ill);
6444 			} /* Else we already freed everything! */
6445 		} else {
6446 			/*
6447 			 * Otherwise send an ICMP protocol unreachable.
6448 			 */
6449 			if (ip_fanout_send_icmp(q, first_mp, flags,
6450 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6451 			    mctl_present, zoneid, ipst)) {
6452 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6453 			}
6454 		}
6455 		return;
6456 	}
6457 
6458 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
6459 
6460 	CONN_INC_REF(connp);
6461 	first_connp = connp;
6462 
6463 	/*
6464 	 * Only send message to one tunnel driver by immediately
6465 	 * terminating the loop.
6466 	 */
6467 	connp = one_only ? NULL : connp->conn_next;
6468 
6469 	for (;;) {
6470 		while (connp != NULL) {
6471 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6472 			    flags, zoneid) &&
6473 			    (!is_system_labeled() ||
6474 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6475 			    shared_addr, connp)))
6476 				break;
6477 			connp = connp->conn_next;
6478 		}
6479 
6480 		/*
6481 		 * Copy the packet.
6482 		 */
6483 		if (connp == NULL ||
6484 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6485 		    ((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6486 			/*
6487 			 * No more interested clients or memory
6488 			 * allocation failed
6489 			 */
6490 			connp = first_connp;
6491 			break;
6492 		}
6493 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
6494 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6495 		CONN_INC_REF(connp);
6496 		mutex_exit(&connfp->connf_lock);
6497 		rq = connp->conn_rq;
6498 
6499 		/*
6500 		 * Check flow control
6501 		 */
6502 		if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
6503 		    (!IPCL_IS_NONSTR(connp) && !canputnext(rq))) {
6504 			if (flags & IP_FF_RAWIP) {
6505 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6506 			} else {
6507 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6508 			}
6509 
6510 			freemsg(first_mp1);
6511 		} else {
6512 			/*
6513 			 * Don't enforce here if we're an actual tunnel -
6514 			 * let "tun" do it instead.
6515 			 */
6516 			if (!IPCL_IS_IPTUN(connp) &&
6517 			    (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6518 			    secure)) {
6519 				first_mp1 = ipsec_check_inbound_policy
6520 				    (first_mp1, connp, ipha, NULL,
6521 				    mctl_present);
6522 			}
6523 			if (first_mp1 != NULL) {
6524 				int in_flags = 0;
6525 				/*
6526 				 * ip_fanout_proto also gets called from
6527 				 * icmp_inbound_error_fanout, in which case
6528 				 * the msg type is M_CTL.  Don't add info
6529 				 * in this case for the time being. In future
6530 				 * when there is a need for knowing the
6531 				 * inbound iface index for ICMP error msgs,
6532 				 * then this can be changed.
6533 				 */
6534 				if (connp->conn_recvif)
6535 					in_flags = IPF_RECVIF;
6536 				/*
6537 				 * The ULP may support IP_RECVPKTINFO for both
6538 				 * IP v4 and v6 so pass the appropriate argument
6539 				 * based on conn IP version.
6540 				 */
6541 				if (connp->conn_ip_recvpktinfo) {
6542 					if (connp->conn_af_isv6) {
6543 						/*
6544 						 * V6 only needs index
6545 						 */
6546 						in_flags |= IPF_RECVIF;
6547 					} else {
6548 						/*
6549 						 * V4 needs index +
6550 						 * matching address.
6551 						 */
6552 						in_flags |= IPF_RECVADDR;
6553 					}
6554 				}
6555 				if ((in_flags != 0) &&
6556 				    (mp->b_datap->db_type != M_CTL)) {
6557 					/*
6558 					 * the actual data will be
6559 					 * contained in b_cont upon
6560 					 * successful return of the
6561 					 * following call else
6562 					 * original mblk is returned
6563 					 */
6564 					ASSERT(recv_ill != NULL);
6565 					mp1 = ip_add_info(mp1, recv_ill,
6566 					    in_flags, IPCL_ZONEID(connp), ipst);
6567 				}
6568 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6569 				if (mctl_present)
6570 					freeb(first_mp1);
6571 				(connp->conn_recv)(connp, mp1, NULL);
6572 			}
6573 		}
6574 		mutex_enter(&connfp->connf_lock);
6575 		/* Follow the next pointer before releasing the conn. */
6576 		next_connp = connp->conn_next;
6577 		CONN_DEC_REF(connp);
6578 		connp = next_connp;
6579 	}
6580 
6581 	/* Last one.  Send it upstream. */
6582 	mutex_exit(&connfp->connf_lock);
6583 
6584 	/*
6585 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6586 	 * will be set to false.
6587 	 */
6588 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6589 		ill_index = ill->ill_phyint->phyint_ifindex;
6590 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6591 		if (mp == NULL) {
6592 			CONN_DEC_REF(connp);
6593 			if (mctl_present) {
6594 				freeb(first_mp);
6595 			}
6596 			return;
6597 		}
6598 	}
6599 
6600 	rq = connp->conn_rq;
6601 	/*
6602 	 * Check flow control
6603 	 */
6604 	if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
6605 	    (!IPCL_IS_NONSTR(connp) && !canputnext(rq))) {
6606 		if (flags & IP_FF_RAWIP) {
6607 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6608 		} else {
6609 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6610 		}
6611 
6612 		freemsg(first_mp);
6613 	} else {
6614 		if (IPCL_IS_IPTUN(connp)) {
6615 			/*
6616 			 * Tunneled packet.  We enforce policy in the tunnel
6617 			 * module itself.
6618 			 *
6619 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6620 			 * a policy check.
6621 			 * FIXME to use conn_recv for tun later.
6622 			 */
6623 			putnext(rq, first_mp);
6624 			CONN_DEC_REF(connp);
6625 			return;
6626 		}
6627 
6628 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6629 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6630 			    ipha, NULL, mctl_present);
6631 		}
6632 
6633 		if (first_mp != NULL) {
6634 			int in_flags = 0;
6635 
6636 			/*
6637 			 * ip_fanout_proto also gets called
6638 			 * from icmp_inbound_error_fanout, in
6639 			 * which case the msg type is M_CTL.
6640 			 * Don't add info in this case for time
6641 			 * being. In future when there is a
6642 			 * need for knowing the inbound iface
6643 			 * index for ICMP error msgs, then this
6644 			 * can be changed
6645 			 */
6646 			if (connp->conn_recvif)
6647 				in_flags = IPF_RECVIF;
6648 			if (connp->conn_ip_recvpktinfo) {
6649 				if (connp->conn_af_isv6) {
6650 					/*
6651 					 * V6 only needs index
6652 					 */
6653 					in_flags |= IPF_RECVIF;
6654 				} else {
6655 					/*
6656 					 * V4 needs index +
6657 					 * matching address.
6658 					 */
6659 					in_flags |= IPF_RECVADDR;
6660 				}
6661 			}
6662 			if ((in_flags != 0) &&
6663 			    (mp->b_datap->db_type != M_CTL)) {
6664 
6665 				/*
6666 				 * the actual data will be contained in
6667 				 * b_cont upon successful return
6668 				 * of the following call else original
6669 				 * mblk is returned
6670 				 */
6671 				ASSERT(recv_ill != NULL);
6672 				mp = ip_add_info(mp, recv_ill,
6673 				    in_flags, IPCL_ZONEID(connp), ipst);
6674 			}
6675 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6676 			(connp->conn_recv)(connp, mp, NULL);
6677 			if (mctl_present)
6678 				freeb(first_mp);
6679 		}
6680 	}
6681 	CONN_DEC_REF(connp);
6682 }
6683 
6684 /*
6685  * Fanout for TCP packets
6686  * The caller puts <fport, lport> in the ports parameter.
6687  *
6688  * IPQoS Notes
6689  * Before sending it to the client, invoke IPPF processing.
6690  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6691  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6692  * ip_policy is false.
6693  */
6694 static void
6695 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6696     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6697 {
6698 	mblk_t  *first_mp;
6699 	boolean_t secure;
6700 	uint32_t ill_index;
6701 	int	ip_hdr_len;
6702 	tcph_t	*tcph;
6703 	boolean_t syn_present = B_FALSE;
6704 	conn_t	*connp;
6705 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6706 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6707 
6708 	ASSERT(recv_ill != NULL);
6709 
6710 	first_mp = mp;
6711 	if (mctl_present) {
6712 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6713 		mp = first_mp->b_cont;
6714 		secure = ipsec_in_is_secure(first_mp);
6715 		ASSERT(mp != NULL);
6716 	} else {
6717 		secure = B_FALSE;
6718 	}
6719 
6720 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6721 
6722 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6723 	    zoneid, ipst)) == NULL) {
6724 		/*
6725 		 * No connected connection or listener. Send a
6726 		 * TH_RST via tcp_xmit_listeners_reset.
6727 		 */
6728 
6729 		/* Initiate IPPf processing, if needed. */
6730 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6731 			uint32_t ill_index;
6732 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6733 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6734 			if (first_mp == NULL)
6735 				return;
6736 		}
6737 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6738 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6739 		    zoneid));
6740 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6741 		    ipst->ips_netstack->netstack_tcp, NULL);
6742 		return;
6743 	}
6744 
6745 	/*
6746 	 * Allocate the SYN for the TCP connection here itself
6747 	 */
6748 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6749 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6750 		if (IPCL_IS_TCP(connp)) {
6751 			squeue_t *sqp;
6752 
6753 			/*
6754 			 * For fused tcp loopback, assign the eager's
6755 			 * squeue to be that of the active connect's.
6756 			 * Note that we don't check for IP_FF_LOOPBACK
6757 			 * here since this routine gets called only
6758 			 * for loopback (unlike the IPv6 counterpart).
6759 			 */
6760 			ASSERT(Q_TO_CONN(q) != NULL);
6761 			if (do_tcp_fusion &&
6762 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6763 			    !secure &&
6764 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy &&
6765 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6766 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6767 				sqp = Q_TO_CONN(q)->conn_sqp;
6768 			} else {
6769 				sqp = IP_SQUEUE_GET(lbolt);
6770 			}
6771 
6772 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6773 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6774 			syn_present = B_TRUE;
6775 		}
6776 	}
6777 
6778 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6779 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6780 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6781 		if ((flags & TH_RST) || (flags & TH_URG)) {
6782 			CONN_DEC_REF(connp);
6783 			freemsg(first_mp);
6784 			return;
6785 		}
6786 		if (flags & TH_ACK) {
6787 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6788 			    ipst->ips_netstack->netstack_tcp, connp);
6789 			CONN_DEC_REF(connp);
6790 			return;
6791 		}
6792 
6793 		CONN_DEC_REF(connp);
6794 		freemsg(first_mp);
6795 		return;
6796 	}
6797 
6798 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6799 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6800 		    NULL, mctl_present);
6801 		if (first_mp == NULL) {
6802 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6803 			CONN_DEC_REF(connp);
6804 			return;
6805 		}
6806 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6807 			ASSERT(syn_present);
6808 			if (mctl_present) {
6809 				ASSERT(first_mp != mp);
6810 				first_mp->b_datap->db_struioflag |=
6811 				    STRUIO_POLICY;
6812 			} else {
6813 				ASSERT(first_mp == mp);
6814 				mp->b_datap->db_struioflag &=
6815 				    ~STRUIO_EAGER;
6816 				mp->b_datap->db_struioflag |=
6817 				    STRUIO_POLICY;
6818 			}
6819 		} else {
6820 			/*
6821 			 * Discard first_mp early since we're dealing with a
6822 			 * fully-connected conn_t and tcp doesn't do policy in
6823 			 * this case.
6824 			 */
6825 			if (mctl_present) {
6826 				freeb(first_mp);
6827 				mctl_present = B_FALSE;
6828 			}
6829 			first_mp = mp;
6830 		}
6831 	}
6832 
6833 	/*
6834 	 * Initiate policy processing here if needed. If we get here from
6835 	 * icmp_inbound_error_fanout, ip_policy is false.
6836 	 */
6837 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6838 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6839 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6840 		if (mp == NULL) {
6841 			CONN_DEC_REF(connp);
6842 			if (mctl_present)
6843 				freeb(first_mp);
6844 			return;
6845 		} else if (mctl_present) {
6846 			ASSERT(first_mp != mp);
6847 			first_mp->b_cont = mp;
6848 		} else {
6849 			first_mp = mp;
6850 		}
6851 	}
6852 
6853 
6854 
6855 	/* Handle socket options. */
6856 	if (!syn_present &&
6857 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6858 		/* Add header */
6859 		ASSERT(recv_ill != NULL);
6860 		/*
6861 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6862 		 * IPF_RECVIF.
6863 		 */
6864 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6865 		    ipst);
6866 		if (mp == NULL) {
6867 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6868 			CONN_DEC_REF(connp);
6869 			if (mctl_present)
6870 				freeb(first_mp);
6871 			return;
6872 		} else if (mctl_present) {
6873 			/*
6874 			 * ip_add_info might return a new mp.
6875 			 */
6876 			ASSERT(first_mp != mp);
6877 			first_mp->b_cont = mp;
6878 		} else {
6879 			first_mp = mp;
6880 		}
6881 	}
6882 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6883 	if (IPCL_IS_TCP(connp)) {
6884 		/* do not drain, certain use cases can blow the stack */
6885 		SQUEUE_ENTER_ONE(connp->conn_sqp, first_mp, connp->conn_recv,
6886 		    connp, ip_squeue_flag, SQTAG_IP_FANOUT_TCP);
6887 	} else {
6888 		/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
6889 		(connp->conn_recv)(connp, first_mp, NULL);
6890 		CONN_DEC_REF(connp);
6891 	}
6892 }
6893 
6894 /*
6895  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
6896  * pass it along to ESP if the SPI is non-zero.  Returns TRUE if the mblk
6897  * is not consumed.
6898  *
6899  * One of four things can happen, all of which affect the passed-in mblk:
6900  *
6901  * 1.) ICMP messages that go through here just get returned TRUE.
6902  *
6903  * 2.) The packet is stock UDP and gets its zero-SPI stripped.  Return TRUE.
6904  *
6905  * 3.) The packet is ESP-in-UDP, gets transformed into an equivalent
6906  *     ESP packet, and is passed along to ESP for consumption.  Return FALSE.
6907  *
6908  * 4.) The packet is an ESP-in-UDP Keepalive.  Drop it and return FALSE.
6909  */
6910 static boolean_t
6911 zero_spi_check(queue_t *q, mblk_t *mp, ire_t *ire, ill_t *recv_ill,
6912     ipsec_stack_t *ipss)
6913 {
6914 	int shift, plen, iph_len;
6915 	ipha_t *ipha;
6916 	udpha_t *udpha;
6917 	uint32_t *spi;
6918 	uint32_t esp_ports;
6919 	uint8_t *orptr;
6920 	boolean_t free_ire;
6921 
6922 	if (DB_TYPE(mp) == M_CTL) {
6923 		/*
6924 		 * ICMP message with UDP inside.  Don't bother stripping, just
6925 		 * send it up.
6926 		 *
6927 		 * NOTE: Any app with UDP_NAT_T_ENDPOINT set is probably going
6928 		 * to ignore errors set by ICMP anyway ('cause they might be
6929 		 * forged), but that's the app's decision, not ours.
6930 		 */
6931 
6932 		/* Bunch of reality checks for DEBUG kernels... */
6933 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION);
6934 		ASSERT(((ipha_t *)mp->b_rptr)->ipha_protocol == IPPROTO_ICMP);
6935 
6936 		return (B_TRUE);
6937 	}
6938 
6939 	ipha = (ipha_t *)mp->b_rptr;
6940 	iph_len = IPH_HDR_LENGTH(ipha);
6941 	plen = ntohs(ipha->ipha_length);
6942 
6943 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
6944 		/*
6945 		 * Most likely a keepalive for the benefit of an intervening
6946 		 * NAT.  These aren't for us, per se, so drop it.
6947 		 *
6948 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
6949 		 * byte packets (keepalives are 1-byte), but we'll drop them
6950 		 * also.
6951 		 */
6952 		ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6953 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
6954 		return (B_FALSE);
6955 	}
6956 
6957 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
6958 		/* might as well pull it all up - it might be ESP. */
6959 		if (!pullupmsg(mp, -1)) {
6960 			ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6961 			    DROPPER(ipss, ipds_esp_nomem),
6962 			    &ipss->ipsec_dropper);
6963 			return (B_FALSE);
6964 		}
6965 
6966 		ipha = (ipha_t *)mp->b_rptr;
6967 	}
6968 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
6969 	if (*spi == 0) {
6970 		/* UDP packet - remove 0-spi. */
6971 		shift = sizeof (uint32_t);
6972 	} else {
6973 		/* ESP-in-UDP packet - reduce to ESP. */
6974 		ipha->ipha_protocol = IPPROTO_ESP;
6975 		shift = sizeof (udpha_t);
6976 	}
6977 
6978 	/* Fix IP header */
6979 	ipha->ipha_length = htons(plen - shift);
6980 	ipha->ipha_hdr_checksum = 0;
6981 
6982 	orptr = mp->b_rptr;
6983 	mp->b_rptr += shift;
6984 
6985 	udpha = (udpha_t *)(orptr + iph_len);
6986 	if (*spi == 0) {
6987 		ASSERT((uint8_t *)ipha == orptr);
6988 		udpha->uha_length = htons(plen - shift - iph_len);
6989 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
6990 		esp_ports = 0;
6991 	} else {
6992 		esp_ports = *((uint32_t *)udpha);
6993 		ASSERT(esp_ports != 0);
6994 	}
6995 	ovbcopy(orptr, orptr + shift, iph_len);
6996 	if (esp_ports != 0) /* Punt up for ESP processing. */ {
6997 		ipha = (ipha_t *)(orptr + shift);
6998 
6999 		free_ire = (ire == NULL);
7000 		if (free_ire) {
7001 			/* Re-acquire ire. */
7002 			ire = ire_cache_lookup(ipha->ipha_dst, ALL_ZONES, NULL,
7003 			    ipss->ipsec_netstack->netstack_ip);
7004 			if (ire == NULL || !(ire->ire_type & IRE_LOCAL)) {
7005 				if (ire != NULL)
7006 					ire_refrele(ire);
7007 				/*
7008 				 * Do a regular freemsg(), as this is an IP
7009 				 * error (no local route) not an IPsec one.
7010 				 */
7011 				freemsg(mp);
7012 			}
7013 		}
7014 
7015 		ip_proto_input(q, mp, ipha, ire, recv_ill, esp_ports);
7016 		if (free_ire)
7017 			ire_refrele(ire);
7018 	}
7019 
7020 	return (esp_ports == 0);
7021 }
7022 
7023 /*
7024  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
7025  * We are responsible for disposing of mp, such as by freemsg() or putnext()
7026  * Caller is responsible for dropping references to the conn, and freeing
7027  * first_mp.
7028  *
7029  * IPQoS Notes
7030  * Before sending it to the client, invoke IPPF processing. Policy processing
7031  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
7032  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
7033  * ip_wput_local, ip_policy is false.
7034  */
7035 static void
7036 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
7037     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
7038     boolean_t ip_policy)
7039 {
7040 	boolean_t	mctl_present = (first_mp != NULL);
7041 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
7042 	uint32_t	ill_index;
7043 	ip_stack_t	*ipst = recv_ill->ill_ipst;
7044 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
7045 
7046 	ASSERT(ill != NULL);
7047 
7048 	if (mctl_present)
7049 		first_mp->b_cont = mp;
7050 	else
7051 		first_mp = mp;
7052 
7053 	if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
7054 	    (!IPCL_IS_NONSTR(connp) && CONN_UDP_FLOWCTLD(connp))) {
7055 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
7056 		freemsg(first_mp);
7057 		return;
7058 	}
7059 
7060 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
7061 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
7062 		    NULL, mctl_present);
7063 		/* Freed by ipsec_check_inbound_policy(). */
7064 		if (first_mp == NULL) {
7065 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7066 			return;
7067 		}
7068 	}
7069 	if (mctl_present)
7070 		freeb(first_mp);
7071 
7072 	/* Let's hope the compilers utter "branch, predict-not-taken..." ;) */
7073 	if (connp->conn_udp->udp_nat_t_endpoint) {
7074 		if (mctl_present) {
7075 			/* mctl_present *shouldn't* happen. */
7076 			ip_drop_packet(mp, B_TRUE, NULL, NULL,
7077 			    DROPPER(ipss, ipds_esp_nat_t_ipsec),
7078 			    &ipss->ipsec_dropper);
7079 			return;
7080 		}
7081 
7082 		if (!zero_spi_check(ill->ill_rq, mp, NULL, recv_ill, ipss))
7083 			return;
7084 	}
7085 
7086 	/* Handle options. */
7087 	if (connp->conn_recvif)
7088 		in_flags = IPF_RECVIF;
7089 	/*
7090 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
7091 	 * passed to ip_add_info is based on IP version of connp.
7092 	 */
7093 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
7094 		if (connp->conn_af_isv6) {
7095 			/*
7096 			 * V6 only needs index
7097 			 */
7098 			in_flags |= IPF_RECVIF;
7099 		} else {
7100 			/*
7101 			 * V4 needs index + matching address.
7102 			 */
7103 			in_flags |= IPF_RECVADDR;
7104 		}
7105 	}
7106 
7107 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
7108 		in_flags |= IPF_RECVSLLA;
7109 
7110 	/*
7111 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7112 	 * freed if the packet is dropped. The caller will do so.
7113 	 */
7114 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7115 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7116 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7117 		if (mp == NULL) {
7118 			return;
7119 		}
7120 	}
7121 	if ((in_flags != 0) &&
7122 	    (mp->b_datap->db_type != M_CTL)) {
7123 		/*
7124 		 * The actual data will be contained in b_cont
7125 		 * upon successful return of the following call
7126 		 * else original mblk is returned
7127 		 */
7128 		ASSERT(recv_ill != NULL);
7129 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7130 		    ipst);
7131 	}
7132 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7133 	/* Send it upstream */
7134 	(connp->conn_recv)(connp, mp, NULL);
7135 }
7136 
7137 /*
7138  * Fanout for UDP packets.
7139  * The caller puts <fport, lport> in the ports parameter.
7140  *
7141  * If SO_REUSEADDR is set all multicast and broadcast packets
7142  * will be delivered to all streams bound to the same port.
7143  *
7144  * Zones notes:
7145  * Multicast and broadcast packets will be distributed to streams in all zones.
7146  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7147  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7148  * packets. To maintain this behavior with multiple zones, the conns are grouped
7149  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7150  * each zone. If unset, all the following conns in the same zone are skipped.
7151  */
7152 static void
7153 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7154     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7155     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7156 {
7157 	uint32_t	dstport, srcport;
7158 	ipaddr_t	dst;
7159 	mblk_t		*first_mp;
7160 	boolean_t	secure;
7161 	in6_addr_t	v6src;
7162 	conn_t		*connp;
7163 	connf_t		*connfp;
7164 	conn_t		*first_connp;
7165 	conn_t		*next_connp;
7166 	mblk_t		*mp1, *first_mp1;
7167 	ipaddr_t	src;
7168 	zoneid_t	last_zoneid;
7169 	boolean_t	reuseaddr;
7170 	boolean_t	shared_addr;
7171 	boolean_t	unlabeled;
7172 	ip_stack_t	*ipst;
7173 
7174 	ASSERT(recv_ill != NULL);
7175 	ipst = recv_ill->ill_ipst;
7176 
7177 	first_mp = mp;
7178 	if (mctl_present) {
7179 		mp = first_mp->b_cont;
7180 		first_mp->b_cont = NULL;
7181 		secure = ipsec_in_is_secure(first_mp);
7182 		ASSERT(mp != NULL);
7183 	} else {
7184 		first_mp = NULL;
7185 		secure = B_FALSE;
7186 	}
7187 
7188 	/* Extract ports in net byte order */
7189 	dstport = htons(ntohl(ports) & 0xFFFF);
7190 	srcport = htons(ntohl(ports) >> 16);
7191 	dst = ipha->ipha_dst;
7192 	src = ipha->ipha_src;
7193 
7194 	unlabeled = B_FALSE;
7195 	if (is_system_labeled())
7196 		/* Cred cannot be null on IPv4 */
7197 		unlabeled = (crgetlabel(DB_CRED(mp))->tsl_flags &
7198 		    TSLF_UNLABELED) != 0;
7199 	shared_addr = (zoneid == ALL_ZONES);
7200 	if (shared_addr) {
7201 		/*
7202 		 * No need to handle exclusive-stack zones since ALL_ZONES
7203 		 * only applies to the shared stack.
7204 		 */
7205 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7206 		/*
7207 		 * If no shared MLP is found, tsol_mlp_findzone returns
7208 		 * ALL_ZONES.  In that case, we assume it's SLP, and
7209 		 * search for the zone based on the packet label.
7210 		 *
7211 		 * If there is such a zone, we prefer to find a
7212 		 * connection in it.  Otherwise, we look for a
7213 		 * MAC-exempt connection in any zone whose label
7214 		 * dominates the default label on the packet.
7215 		 */
7216 		if (zoneid == ALL_ZONES)
7217 			zoneid = tsol_packet_to_zoneid(mp);
7218 		else
7219 			unlabeled = B_FALSE;
7220 	}
7221 
7222 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7223 	mutex_enter(&connfp->connf_lock);
7224 	connp = connfp->connf_head;
7225 	if (!broadcast && !CLASSD(dst)) {
7226 		/*
7227 		 * Not broadcast or multicast. Send to the one (first)
7228 		 * client we find. No need to check conn_wantpacket()
7229 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7230 		 * IPv4 unicast packets.
7231 		 */
7232 		while ((connp != NULL) &&
7233 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7234 		    (!IPCL_ZONE_MATCH(connp, zoneid) &&
7235 		    !(unlabeled && connp->conn_mac_exempt)))) {
7236 			/*
7237 			 * We keep searching since the conn did not match,
7238 			 * or its zone did not match and it is not either
7239 			 * an allzones conn or a mac exempt conn (if the
7240 			 * sender is unlabeled.)
7241 			 */
7242 			connp = connp->conn_next;
7243 		}
7244 
7245 		if (connp == NULL ||
7246 		    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL)
7247 			goto notfound;
7248 
7249 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7250 
7251 		if (is_system_labeled() &&
7252 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7253 		    connp))
7254 			goto notfound;
7255 
7256 		CONN_INC_REF(connp);
7257 		mutex_exit(&connfp->connf_lock);
7258 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7259 		    flags, recv_ill, ip_policy);
7260 		IP_STAT(ipst, ip_udp_fannorm);
7261 		CONN_DEC_REF(connp);
7262 		return;
7263 	}
7264 
7265 	/*
7266 	 * Broadcast and multicast case
7267 	 *
7268 	 * Need to check conn_wantpacket().
7269 	 * If SO_REUSEADDR has been set on the first we send the
7270 	 * packet to all clients that have joined the group and
7271 	 * match the port.
7272 	 */
7273 
7274 	while (connp != NULL) {
7275 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7276 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7277 		    (!is_system_labeled() ||
7278 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7279 		    connp)))
7280 			break;
7281 		connp = connp->conn_next;
7282 	}
7283 
7284 	if (connp == NULL ||
7285 	    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL)
7286 		goto notfound;
7287 
7288 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7289 
7290 	first_connp = connp;
7291 	/*
7292 	 * When SO_REUSEADDR is not set, send the packet only to the first
7293 	 * matching connection in its zone by keeping track of the zoneid.
7294 	 */
7295 	reuseaddr = first_connp->conn_reuseaddr;
7296 	last_zoneid = first_connp->conn_zoneid;
7297 
7298 	CONN_INC_REF(connp);
7299 	connp = connp->conn_next;
7300 	for (;;) {
7301 		while (connp != NULL) {
7302 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7303 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7304 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7305 			    (!is_system_labeled() ||
7306 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7307 			    shared_addr, connp)))
7308 				break;
7309 			connp = connp->conn_next;
7310 		}
7311 		/*
7312 		 * Just copy the data part alone. The mctl part is
7313 		 * needed just for verifying policy and it is never
7314 		 * sent up.
7315 		 */
7316 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7317 		    ((mp1 = copymsg(mp)) == NULL))) {
7318 			/*
7319 			 * No more interested clients or memory
7320 			 * allocation failed
7321 			 */
7322 			connp = first_connp;
7323 			break;
7324 		}
7325 		if (connp->conn_zoneid != last_zoneid) {
7326 			/*
7327 			 * Update the zoneid so that the packet isn't sent to
7328 			 * any more conns in the same zone unless SO_REUSEADDR
7329 			 * is set.
7330 			 */
7331 			reuseaddr = connp->conn_reuseaddr;
7332 			last_zoneid = connp->conn_zoneid;
7333 		}
7334 		if (first_mp != NULL) {
7335 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7336 			    ipsec_info_type == IPSEC_IN);
7337 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7338 			    ipst->ips_netstack);
7339 			if (first_mp1 == NULL) {
7340 				freemsg(mp1);
7341 				connp = first_connp;
7342 				break;
7343 			}
7344 		} else {
7345 			first_mp1 = NULL;
7346 		}
7347 		CONN_INC_REF(connp);
7348 		mutex_exit(&connfp->connf_lock);
7349 		/*
7350 		 * IPQoS notes: We don't send the packet for policy
7351 		 * processing here, will do it for the last one (below).
7352 		 * i.e. we do it per-packet now, but if we do policy
7353 		 * processing per-conn, then we would need to do it
7354 		 * here too.
7355 		 */
7356 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7357 		    ipha, flags, recv_ill, B_FALSE);
7358 		mutex_enter(&connfp->connf_lock);
7359 		/* Follow the next pointer before releasing the conn. */
7360 		next_connp = connp->conn_next;
7361 		IP_STAT(ipst, ip_udp_fanmb);
7362 		CONN_DEC_REF(connp);
7363 		connp = next_connp;
7364 	}
7365 
7366 	/* Last one.  Send it upstream. */
7367 	mutex_exit(&connfp->connf_lock);
7368 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7369 	    recv_ill, ip_policy);
7370 	IP_STAT(ipst, ip_udp_fanmb);
7371 	CONN_DEC_REF(connp);
7372 	return;
7373 
7374 notfound:
7375 
7376 	mutex_exit(&connfp->connf_lock);
7377 	IP_STAT(ipst, ip_udp_fanothers);
7378 	/*
7379 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7380 	 * have already been matched above, since they live in the IPv4
7381 	 * fanout tables. This implies we only need to
7382 	 * check for IPv6 in6addr_any endpoints here.
7383 	 * Thus we compare using ipv6_all_zeros instead of the destination
7384 	 * address, except for the multicast group membership lookup which
7385 	 * uses the IPv4 destination.
7386 	 */
7387 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7388 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7389 	mutex_enter(&connfp->connf_lock);
7390 	connp = connfp->connf_head;
7391 	if (!broadcast && !CLASSD(dst)) {
7392 		while (connp != NULL) {
7393 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7394 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7395 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7396 			    !connp->conn_ipv6_v6only)
7397 				break;
7398 			connp = connp->conn_next;
7399 		}
7400 
7401 		if (connp != NULL && is_system_labeled() &&
7402 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7403 		    connp))
7404 			connp = NULL;
7405 
7406 		if (connp == NULL ||
7407 		    !IPCL_IS_NONSTR(connp) && 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].
7420 			    connf_head != NULL) {
7421 				ip_fanout_proto(q, first_mp, ill, ipha,
7422 				    flags | IP_FF_RAWIP, mctl_present,
7423 				    ip_policy, recv_ill, zoneid);
7424 			} else {
7425 				if (ip_fanout_send_icmp(q, first_mp, flags,
7426 				    ICMP_DEST_UNREACHABLE,
7427 				    ICMP_PORT_UNREACHABLE,
7428 				    mctl_present, zoneid, ipst)) {
7429 					BUMP_MIB(ill->ill_ip_mib,
7430 					    udpIfStatsNoPorts);
7431 				}
7432 			}
7433 			return;
7434 		}
7435 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7436 
7437 		CONN_INC_REF(connp);
7438 		mutex_exit(&connfp->connf_lock);
7439 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7440 		    flags, recv_ill, ip_policy);
7441 		CONN_DEC_REF(connp);
7442 		return;
7443 	}
7444 	/*
7445 	 * IPv4 multicast packet being delivered to an AF_INET6
7446 	 * in6addr_any endpoint.
7447 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7448 	 * and not conn_wantpacket_v6() since any multicast membership is
7449 	 * for an IPv4-mapped multicast address.
7450 	 * The packet is sent to all clients in all zones that have joined the
7451 	 * group and match the port.
7452 	 */
7453 	while (connp != NULL) {
7454 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7455 		    srcport, v6src) &&
7456 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7457 		    (!is_system_labeled() ||
7458 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7459 		    connp)))
7460 			break;
7461 		connp = connp->conn_next;
7462 	}
7463 
7464 	if (connp == NULL ||
7465 	    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL) {
7466 		/*
7467 		 * No one bound to this port.  Is
7468 		 * there a client that wants all
7469 		 * unclaimed datagrams?
7470 		 */
7471 		mutex_exit(&connfp->connf_lock);
7472 
7473 		if (mctl_present)
7474 			first_mp->b_cont = mp;
7475 		else
7476 			first_mp = mp;
7477 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7478 		    NULL) {
7479 			ip_fanout_proto(q, first_mp, ill, ipha,
7480 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7481 			    recv_ill, zoneid);
7482 		} else {
7483 			/*
7484 			 * We used to attempt to send an icmp error here, but
7485 			 * since this is known to be a multicast packet
7486 			 * and we don't send icmp errors in response to
7487 			 * multicast, just drop the packet and give up sooner.
7488 			 */
7489 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7490 			freemsg(first_mp);
7491 		}
7492 		return;
7493 	}
7494 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7495 
7496 	first_connp = connp;
7497 
7498 	CONN_INC_REF(connp);
7499 	connp = connp->conn_next;
7500 	for (;;) {
7501 		while (connp != NULL) {
7502 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7503 			    ipv6_all_zeros, srcport, v6src) &&
7504 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7505 			    (!is_system_labeled() ||
7506 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7507 			    shared_addr, connp)))
7508 				break;
7509 			connp = connp->conn_next;
7510 		}
7511 		/*
7512 		 * Just copy the data part alone. The mctl part is
7513 		 * needed just for verifying policy and it is never
7514 		 * sent up.
7515 		 */
7516 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7517 		    ((mp1 = copymsg(mp)) == NULL))) {
7518 			/*
7519 			 * No more intested clients or memory
7520 			 * allocation failed
7521 			 */
7522 			connp = first_connp;
7523 			break;
7524 		}
7525 		if (first_mp != NULL) {
7526 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7527 			    ipsec_info_type == IPSEC_IN);
7528 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7529 			    ipst->ips_netstack);
7530 			if (first_mp1 == NULL) {
7531 				freemsg(mp1);
7532 				connp = first_connp;
7533 				break;
7534 			}
7535 		} else {
7536 			first_mp1 = NULL;
7537 		}
7538 		CONN_INC_REF(connp);
7539 		mutex_exit(&connfp->connf_lock);
7540 		/*
7541 		 * IPQoS notes: We don't send the packet for policy
7542 		 * processing here, will do it for the last one (below).
7543 		 * i.e. we do it per-packet now, but if we do policy
7544 		 * processing per-conn, then we would need to do it
7545 		 * here too.
7546 		 */
7547 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7548 		    ipha, flags, recv_ill, B_FALSE);
7549 		mutex_enter(&connfp->connf_lock);
7550 		/* Follow the next pointer before releasing the conn. */
7551 		next_connp = connp->conn_next;
7552 		CONN_DEC_REF(connp);
7553 		connp = next_connp;
7554 	}
7555 
7556 	/* Last one.  Send it upstream. */
7557 	mutex_exit(&connfp->connf_lock);
7558 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7559 	    recv_ill, ip_policy);
7560 	CONN_DEC_REF(connp);
7561 }
7562 
7563 /*
7564  * Complete the ip_wput header so that it
7565  * is possible to generate ICMP
7566  * errors.
7567  */
7568 int
7569 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7570 {
7571 	ire_t *ire;
7572 
7573 	if (ipha->ipha_src == INADDR_ANY) {
7574 		ire = ire_lookup_local(zoneid, ipst);
7575 		if (ire == NULL) {
7576 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7577 			return (1);
7578 		}
7579 		ipha->ipha_src = ire->ire_addr;
7580 		ire_refrele(ire);
7581 	}
7582 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7583 	ipha->ipha_hdr_checksum = 0;
7584 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7585 	return (0);
7586 }
7587 
7588 /*
7589  * Nobody should be sending
7590  * packets up this stream
7591  */
7592 static void
7593 ip_lrput(queue_t *q, mblk_t *mp)
7594 {
7595 	mblk_t *mp1;
7596 
7597 	switch (mp->b_datap->db_type) {
7598 	case M_FLUSH:
7599 		/* Turn around */
7600 		if (*mp->b_rptr & FLUSHW) {
7601 			*mp->b_rptr &= ~FLUSHR;
7602 			qreply(q, mp);
7603 			return;
7604 		}
7605 		break;
7606 	}
7607 	/* Could receive messages that passed through ar_rput */
7608 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7609 		mp1->b_prev = mp1->b_next = NULL;
7610 	freemsg(mp);
7611 }
7612 
7613 /* Nobody should be sending packets down this stream */
7614 /* ARGSUSED */
7615 void
7616 ip_lwput(queue_t *q, mblk_t *mp)
7617 {
7618 	freemsg(mp);
7619 }
7620 
7621 /*
7622  * Move the first hop in any source route to ipha_dst and remove that part of
7623  * the source route.  Called by other protocols.  Errors in option formatting
7624  * are ignored - will be handled by ip_wput_options Return the final
7625  * destination (either ipha_dst or the last entry in a source route.)
7626  */
7627 ipaddr_t
7628 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7629 {
7630 	ipoptp_t	opts;
7631 	uchar_t		*opt;
7632 	uint8_t		optval;
7633 	uint8_t		optlen;
7634 	ipaddr_t	dst;
7635 	int		i;
7636 	ire_t		*ire;
7637 	ip_stack_t	*ipst = ns->netstack_ip;
7638 
7639 	ip2dbg(("ip_massage_options\n"));
7640 	dst = ipha->ipha_dst;
7641 	for (optval = ipoptp_first(&opts, ipha);
7642 	    optval != IPOPT_EOL;
7643 	    optval = ipoptp_next(&opts)) {
7644 		opt = opts.ipoptp_cur;
7645 		switch (optval) {
7646 			uint8_t off;
7647 		case IPOPT_SSRR:
7648 		case IPOPT_LSRR:
7649 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7650 				ip1dbg(("ip_massage_options: bad src route\n"));
7651 				break;
7652 			}
7653 			optlen = opts.ipoptp_len;
7654 			off = opt[IPOPT_OFFSET];
7655 			off--;
7656 		redo_srr:
7657 			if (optlen < IP_ADDR_LEN ||
7658 			    off > optlen - IP_ADDR_LEN) {
7659 				/* End of source route */
7660 				ip1dbg(("ip_massage_options: end of SR\n"));
7661 				break;
7662 			}
7663 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7664 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7665 			    ntohl(dst)));
7666 			/*
7667 			 * Check if our address is present more than
7668 			 * once as consecutive hops in source route.
7669 			 * XXX verify per-interface ip_forwarding
7670 			 * for source route?
7671 			 */
7672 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7673 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7674 			if (ire != NULL) {
7675 				ire_refrele(ire);
7676 				off += IP_ADDR_LEN;
7677 				goto redo_srr;
7678 			}
7679 			if (dst == htonl(INADDR_LOOPBACK)) {
7680 				ip1dbg(("ip_massage_options: loopback addr in "
7681 				    "source route!\n"));
7682 				break;
7683 			}
7684 			/*
7685 			 * Update ipha_dst to be the first hop and remove the
7686 			 * first hop from the source route (by overwriting
7687 			 * part of the option with NOP options).
7688 			 */
7689 			ipha->ipha_dst = dst;
7690 			/* Put the last entry in dst */
7691 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7692 			    3;
7693 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7694 
7695 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7696 			    ntohl(dst)));
7697 			/* Move down and overwrite */
7698 			opt[IP_ADDR_LEN] = opt[0];
7699 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7700 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7701 			for (i = 0; i < IP_ADDR_LEN; i++)
7702 				opt[i] = IPOPT_NOP;
7703 			break;
7704 		}
7705 	}
7706 	return (dst);
7707 }
7708 
7709 /*
7710  * Return the network mask
7711  * associated with the specified address.
7712  */
7713 ipaddr_t
7714 ip_net_mask(ipaddr_t addr)
7715 {
7716 	uchar_t	*up = (uchar_t *)&addr;
7717 	ipaddr_t mask = 0;
7718 	uchar_t	*maskp = (uchar_t *)&mask;
7719 
7720 #if defined(__i386) || defined(__amd64)
7721 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7722 #endif
7723 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7724 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7725 #endif
7726 	if (CLASSD(addr)) {
7727 		maskp[0] = 0xF0;
7728 		return (mask);
7729 	}
7730 
7731 	/* We assume Class E default netmask to be 32 */
7732 	if (CLASSE(addr))
7733 		return (0xffffffffU);
7734 
7735 	if (addr == 0)
7736 		return (0);
7737 	maskp[0] = 0xFF;
7738 	if ((up[0] & 0x80) == 0)
7739 		return (mask);
7740 
7741 	maskp[1] = 0xFF;
7742 	if ((up[0] & 0xC0) == 0x80)
7743 		return (mask);
7744 
7745 	maskp[2] = 0xFF;
7746 	if ((up[0] & 0xE0) == 0xC0)
7747 		return (mask);
7748 
7749 	/* Otherwise return no mask */
7750 	return ((ipaddr_t)0);
7751 }
7752 
7753 /*
7754  * Select an ill for the packet by considering load spreading across
7755  * a different ill in the group if dst_ill is part of some group.
7756  */
7757 ill_t *
7758 ip_newroute_get_dst_ill(ill_t *dst_ill)
7759 {
7760 	ill_t *ill;
7761 
7762 	/*
7763 	 * We schedule irrespective of whether the source address is
7764 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7765 	 */
7766 	ill = illgrp_scheduler(dst_ill);
7767 	if (ill == NULL)
7768 		return (NULL);
7769 
7770 	/*
7771 	 * For groups with names ip_sioctl_groupname ensures that all
7772 	 * ills are of same type. For groups without names, ifgrp_insert
7773 	 * ensures this.
7774 	 */
7775 	ASSERT(dst_ill->ill_type == ill->ill_type);
7776 
7777 	return (ill);
7778 }
7779 
7780 /*
7781  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7782  */
7783 ill_t *
7784 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6,
7785     ip_stack_t *ipst)
7786 {
7787 	ill_t *ret_ill;
7788 
7789 	ASSERT(ifindex != 0);
7790 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7791 	    ipst);
7792 	if (ret_ill == NULL ||
7793 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7794 		if (isv6) {
7795 			if (ill != NULL) {
7796 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7797 			} else {
7798 				BUMP_MIB(&ipst->ips_ip6_mib,
7799 				    ipIfStatsOutDiscards);
7800 			}
7801 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7802 			    "bad ifindex %d.\n", ifindex));
7803 		} else {
7804 			if (ill != NULL) {
7805 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7806 			} else {
7807 				BUMP_MIB(&ipst->ips_ip_mib,
7808 				    ipIfStatsOutDiscards);
7809 			}
7810 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7811 			    "bad ifindex %d.\n", ifindex));
7812 		}
7813 		if (ret_ill != NULL)
7814 			ill_refrele(ret_ill);
7815 		freemsg(first_mp);
7816 		return (NULL);
7817 	}
7818 
7819 	return (ret_ill);
7820 }
7821 
7822 /*
7823  * IPv4 -
7824  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7825  * out a packet to a destination address for which we do not have specific
7826  * (or sufficient) routing information.
7827  *
7828  * NOTE : These are the scopes of some of the variables that point at IRE,
7829  *	  which needs to be followed while making any future modifications
7830  *	  to avoid memory leaks.
7831  *
7832  *	- ire and sire are the entries looked up initially by
7833  *	  ire_ftable_lookup.
7834  *	- ipif_ire is used to hold the interface ire associated with
7835  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7836  *	  it before branching out to error paths.
7837  *	- save_ire is initialized before ire_create, so that ire returned
7838  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7839  *	  before breaking out of the switch.
7840  *
7841  *	Thus on failures, we have to REFRELE only ire and sire, if they
7842  *	are not NULL.
7843  */
7844 void
7845 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, conn_t *connp,
7846     zoneid_t zoneid, ip_stack_t *ipst)
7847 {
7848 	areq_t	*areq;
7849 	ipaddr_t gw = 0;
7850 	ire_t	*ire = NULL;
7851 	mblk_t	*res_mp;
7852 	ipaddr_t *addrp;
7853 	ipaddr_t nexthop_addr;
7854 	ipif_t  *src_ipif = NULL;
7855 	ill_t	*dst_ill = NULL;
7856 	ipha_t  *ipha;
7857 	ire_t	*sire = NULL;
7858 	mblk_t	*first_mp;
7859 	ire_t	*save_ire;
7860 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7861 	ushort_t ire_marks = 0;
7862 	boolean_t mctl_present;
7863 	ipsec_out_t *io;
7864 	mblk_t	*saved_mp;
7865 	ire_t	*first_sire = NULL;
7866 	mblk_t	*copy_mp = NULL;
7867 	mblk_t	*xmit_mp = NULL;
7868 	ipaddr_t save_dst;
7869 	uint32_t multirt_flags =
7870 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7871 	boolean_t multirt_is_resolvable;
7872 	boolean_t multirt_resolve_next;
7873 	boolean_t unspec_src;
7874 	boolean_t do_attach_ill = B_FALSE;
7875 	boolean_t ip_nexthop = B_FALSE;
7876 	tsol_ire_gw_secattr_t *attrp = NULL;
7877 	tsol_gcgrp_t *gcgrp = NULL;
7878 	tsol_gcgrp_addr_t ga;
7879 
7880 	if (ip_debug > 2) {
7881 		/* ip1dbg */
7882 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7883 	}
7884 
7885 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7886 	if (mctl_present) {
7887 		io = (ipsec_out_t *)first_mp->b_rptr;
7888 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7889 		ASSERT(zoneid == io->ipsec_out_zoneid);
7890 		ASSERT(zoneid != ALL_ZONES);
7891 	}
7892 
7893 	ipha = (ipha_t *)mp->b_rptr;
7894 
7895 	/* All multicast lookups come through ip_newroute_ipif() */
7896 	if (CLASSD(dst)) {
7897 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7898 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7899 		freemsg(first_mp);
7900 		return;
7901 	}
7902 
7903 	if (mctl_present && io->ipsec_out_attach_if) {
7904 		/* ip_grab_attach_ill returns a held ill */
7905 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7906 		    io->ipsec_out_ill_index, B_FALSE, ipst);
7907 
7908 		/* Failure case frees things for us. */
7909 		if (attach_ill == NULL)
7910 			return;
7911 
7912 		/*
7913 		 * Check if we need an ire that will not be
7914 		 * looked up by anybody else i.e. HIDDEN.
7915 		 */
7916 		if (ill_is_probeonly(attach_ill))
7917 			ire_marks = IRE_MARK_HIDDEN;
7918 	}
7919 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7920 		ip_nexthop = B_TRUE;
7921 		nexthop_addr = io->ipsec_out_nexthop_addr;
7922 	}
7923 	/*
7924 	 * If this IRE is created for forwarding or it is not for
7925 	 * traffic for congestion controlled protocols, mark it as temporary.
7926 	 */
7927 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7928 		ire_marks |= IRE_MARK_TEMPORARY;
7929 
7930 	/*
7931 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7932 	 * chain until it gets the most specific information available.
7933 	 * For example, we know that there is no IRE_CACHE for this dest,
7934 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7935 	 * ire_ftable_lookup will look up the gateway, etc.
7936 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7937 	 * to the destination, of equal netmask length in the forward table,
7938 	 * will be recursively explored. If no information is available
7939 	 * for the final gateway of that route, we force the returned ire
7940 	 * to be equal to sire using MATCH_IRE_PARENT.
7941 	 * At least, in this case we have a starting point (in the buckets)
7942 	 * to look for other routes to the destination in the forward table.
7943 	 * This is actually used only for multirouting, where a list
7944 	 * of routes has to be processed in sequence.
7945 	 *
7946 	 * In the process of coming up with the most specific information,
7947 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7948 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7949 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7950 	 * Two caveats when handling incomplete ire's in ip_newroute:
7951 	 * - we should be careful when accessing its ire_nce (specifically
7952 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7953 	 * - not all legacy code path callers are prepared to handle
7954 	 *   incomplete ire's, so we should not create/add incomplete
7955 	 *   ire_cache entries here. (See discussion about temporary solution
7956 	 *   further below).
7957 	 *
7958 	 * In order to minimize packet dropping, and to preserve existing
7959 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7960 	 * gateway, and instead use the IF_RESOLVER ire to send out
7961 	 * another request to ARP (this is achieved by passing the
7962 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
7963 	 * arp response comes back in ip_wput_nondata, we will create
7964 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
7965 	 *
7966 	 * Note that this is a temporary solution; the correct solution is
7967 	 * to create an incomplete  per-dst ire_cache entry, and send the
7968 	 * packet out when the gw's nce is resolved. In order to achieve this,
7969 	 * all packet processing must have been completed prior to calling
7970 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
7971 	 * to be modified to accomodate this solution.
7972 	 */
7973 	if (ip_nexthop) {
7974 		/*
7975 		 * The first time we come here, we look for an IRE_INTERFACE
7976 		 * entry for the specified nexthop, set the dst to be the
7977 		 * nexthop address and create an IRE_CACHE entry for the
7978 		 * nexthop. The next time around, we are able to find an
7979 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7980 		 * nexthop address and create an IRE_CACHE entry for the
7981 		 * destination address via the specified nexthop.
7982 		 */
7983 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7984 		    MBLK_GETLABEL(mp), ipst);
7985 		if (ire != NULL) {
7986 			gw = nexthop_addr;
7987 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7988 		} else {
7989 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7990 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7991 			    MBLK_GETLABEL(mp),
7992 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
7993 			    ipst);
7994 			if (ire != NULL) {
7995 				dst = nexthop_addr;
7996 			}
7997 		}
7998 	} else if (attach_ill == NULL) {
7999 		ire = ire_ftable_lookup(dst, 0, 0, 0,
8000 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
8001 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
8002 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
8003 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
8004 		    ipst);
8005 	} else {
8006 		/*
8007 		 * attach_ill is set only for communicating with
8008 		 * on-link hosts. So, don't look for DEFAULT.
8009 		 */
8010 		ipif_t	*attach_ipif;
8011 
8012 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
8013 		if (attach_ipif == NULL) {
8014 			ill_refrele(attach_ill);
8015 			goto icmp_err_ret;
8016 		}
8017 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
8018 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
8019 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
8020 		    MATCH_IRE_SECATTR, ipst);
8021 		ipif_refrele(attach_ipif);
8022 	}
8023 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
8024 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
8025 
8026 	/*
8027 	 * This loop is run only once in most cases.
8028 	 * We loop to resolve further routes only when the destination
8029 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8030 	 */
8031 	do {
8032 		/* Clear the previous iteration's values */
8033 		if (src_ipif != NULL) {
8034 			ipif_refrele(src_ipif);
8035 			src_ipif = NULL;
8036 		}
8037 		if (dst_ill != NULL) {
8038 			ill_refrele(dst_ill);
8039 			dst_ill = NULL;
8040 		}
8041 
8042 		multirt_resolve_next = B_FALSE;
8043 		/*
8044 		 * We check if packets have to be multirouted.
8045 		 * In this case, given the current <ire, sire> couple,
8046 		 * we look for the next suitable <ire, sire>.
8047 		 * This check is done in ire_multirt_lookup(),
8048 		 * which applies various criteria to find the next route
8049 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
8050 		 * unchanged if it detects it has not been tried yet.
8051 		 */
8052 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8053 			ip3dbg(("ip_newroute: starting next_resolution "
8054 			    "with first_mp %p, tag %d\n",
8055 			    (void *)first_mp,
8056 			    MULTIRT_DEBUG_TAGGED(first_mp)));
8057 
8058 			ASSERT(sire != NULL);
8059 			multirt_is_resolvable =
8060 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
8061 			    MBLK_GETLABEL(mp), ipst);
8062 
8063 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
8064 			    "ire %p, sire %p\n",
8065 			    multirt_is_resolvable,
8066 			    (void *)ire, (void *)sire));
8067 
8068 			if (!multirt_is_resolvable) {
8069 				/*
8070 				 * No more multirt route to resolve; give up
8071 				 * (all routes resolved or no more
8072 				 * resolvable routes).
8073 				 */
8074 				if (ire != NULL) {
8075 					ire_refrele(ire);
8076 					ire = NULL;
8077 				}
8078 			} else {
8079 				ASSERT(sire != NULL);
8080 				ASSERT(ire != NULL);
8081 				/*
8082 				 * We simply use first_sire as a flag that
8083 				 * indicates if a resolvable multirt route
8084 				 * has already been found.
8085 				 * If it is not the case, we may have to send
8086 				 * an ICMP error to report that the
8087 				 * destination is unreachable.
8088 				 * We do not IRE_REFHOLD first_sire.
8089 				 */
8090 				if (first_sire == NULL) {
8091 					first_sire = sire;
8092 				}
8093 			}
8094 		}
8095 		if (ire == NULL) {
8096 			if (ip_debug > 3) {
8097 				/* ip2dbg */
8098 				pr_addr_dbg("ip_newroute: "
8099 				    "can't resolve %s\n", AF_INET, &dst);
8100 			}
8101 			ip3dbg(("ip_newroute: "
8102 			    "ire %p, sire %p, first_sire %p\n",
8103 			    (void *)ire, (void *)sire, (void *)first_sire));
8104 
8105 			if (sire != NULL) {
8106 				ire_refrele(sire);
8107 				sire = NULL;
8108 			}
8109 
8110 			if (first_sire != NULL) {
8111 				/*
8112 				 * At least one multirt route has been found
8113 				 * in the same call to ip_newroute();
8114 				 * there is no need to report an ICMP error.
8115 				 * first_sire was not IRE_REFHOLDed.
8116 				 */
8117 				MULTIRT_DEBUG_UNTAG(first_mp);
8118 				freemsg(first_mp);
8119 				return;
8120 			}
8121 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8122 			    RTA_DST, ipst);
8123 			if (attach_ill != NULL)
8124 				ill_refrele(attach_ill);
8125 			goto icmp_err_ret;
8126 		}
8127 
8128 		/*
8129 		 * Verify that the returned IRE does not have either
8130 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8131 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8132 		 */
8133 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8134 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8135 			if (attach_ill != NULL)
8136 				ill_refrele(attach_ill);
8137 			goto icmp_err_ret;
8138 		}
8139 		/*
8140 		 * Increment the ire_ob_pkt_count field for ire if it is an
8141 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8142 		 * increment the same for the parent IRE, sire, if it is some
8143 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, and HOST)
8144 		 */
8145 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8146 			UPDATE_OB_PKT_COUNT(ire);
8147 			ire->ire_last_used_time = lbolt;
8148 		}
8149 
8150 		if (sire != NULL) {
8151 			gw = sire->ire_gateway_addr;
8152 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8153 			    IRE_INTERFACE)) == 0);
8154 			UPDATE_OB_PKT_COUNT(sire);
8155 			sire->ire_last_used_time = lbolt;
8156 		}
8157 		/*
8158 		 * We have a route to reach the destination.
8159 		 *
8160 		 * 1) If the interface is part of ill group, try to get a new
8161 		 *    ill taking load spreading into account.
8162 		 *
8163 		 * 2) After selecting the ill, get a source address that
8164 		 *    might create good inbound load spreading.
8165 		 *    ipif_select_source does this for us.
8166 		 *
8167 		 * If the application specified the ill (ifindex), we still
8168 		 * load spread. Only if the packets needs to go out
8169 		 * specifically on a given ill e.g. binding to
8170 		 * IPIF_NOFAILOVER address, then we don't try to use a
8171 		 * different ill for load spreading.
8172 		 */
8173 		if (attach_ill == NULL) {
8174 			/*
8175 			 * Don't perform outbound load spreading in the
8176 			 * case of an RTF_MULTIRT route, as we actually
8177 			 * typically want to replicate outgoing packets
8178 			 * through particular interfaces.
8179 			 */
8180 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8181 				dst_ill = ire->ire_ipif->ipif_ill;
8182 				/* for uniformity */
8183 				ill_refhold(dst_ill);
8184 			} else {
8185 				/*
8186 				 * If we are here trying to create an IRE_CACHE
8187 				 * for an offlink destination and have the
8188 				 * IRE_CACHE for the next hop and the latter is
8189 				 * using virtual IP source address selection i.e
8190 				 * it's ire->ire_ipif is pointing to a virtual
8191 				 * network interface (vni) then
8192 				 * ip_newroute_get_dst_ll() will return the vni
8193 				 * interface as the dst_ill. Since the vni is
8194 				 * virtual i.e not associated with any physical
8195 				 * interface, it cannot be the dst_ill, hence
8196 				 * in such a case call ip_newroute_get_dst_ll()
8197 				 * with the stq_ill instead of the ire_ipif ILL.
8198 				 * The function returns a refheld ill.
8199 				 */
8200 				if ((ire->ire_type == IRE_CACHE) &&
8201 				    IS_VNI(ire->ire_ipif->ipif_ill))
8202 					dst_ill = ip_newroute_get_dst_ill(
8203 					    ire->ire_stq->q_ptr);
8204 				else
8205 					dst_ill = ip_newroute_get_dst_ill(
8206 					    ire->ire_ipif->ipif_ill);
8207 			}
8208 			if (dst_ill == NULL) {
8209 				if (ip_debug > 2) {
8210 					pr_addr_dbg("ip_newroute: "
8211 					    "no dst ill for dst"
8212 					    " %s\n", AF_INET, &dst);
8213 				}
8214 				goto icmp_err_ret;
8215 			}
8216 		} else {
8217 			dst_ill = ire->ire_ipif->ipif_ill;
8218 			/* for uniformity */
8219 			ill_refhold(dst_ill);
8220 			/*
8221 			 * We should have found a route matching ill as we
8222 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
8223 			 * Rather than asserting, when there is a mismatch,
8224 			 * we just drop the packet.
8225 			 */
8226 			if (dst_ill != attach_ill) {
8227 				ip0dbg(("ip_newroute: Packet dropped as "
8228 				    "IPIF_NOFAILOVER ill is %s, "
8229 				    "ire->ire_ipif->ipif_ill is %s\n",
8230 				    attach_ill->ill_name,
8231 				    dst_ill->ill_name));
8232 				ill_refrele(attach_ill);
8233 				goto icmp_err_ret;
8234 			}
8235 		}
8236 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
8237 		if (attach_ill != NULL) {
8238 			ill_refrele(attach_ill);
8239 			attach_ill = NULL;
8240 			do_attach_ill = B_TRUE;
8241 		}
8242 		ASSERT(dst_ill != NULL);
8243 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8244 
8245 		/*
8246 		 * Pick the best source address from dst_ill.
8247 		 *
8248 		 * 1) If it is part of a multipathing group, we would
8249 		 *    like to spread the inbound packets across different
8250 		 *    interfaces. ipif_select_source picks a random source
8251 		 *    across the different ills in the group.
8252 		 *
8253 		 * 2) If it is not part of a multipathing group, we try
8254 		 *    to pick the source address from the destination
8255 		 *    route. Clustering assumes that when we have multiple
8256 		 *    prefixes hosted on an interface, the prefix of the
8257 		 *    source address matches the prefix of the destination
8258 		 *    route. We do this only if the address is not
8259 		 *    DEPRECATED.
8260 		 *
8261 		 * 3) If the conn is in a different zone than the ire, we
8262 		 *    need to pick a source address from the right zone.
8263 		 *
8264 		 * NOTE : If we hit case (1) above, the prefix of the source
8265 		 *	  address picked may not match the prefix of the
8266 		 *	  destination routes prefix as ipif_select_source
8267 		 *	  does not look at "dst" while picking a source
8268 		 *	  address.
8269 		 *	  If we want the same behavior as (2), we will need
8270 		 *	  to change the behavior of ipif_select_source.
8271 		 */
8272 		ASSERT(src_ipif == NULL);
8273 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8274 			/*
8275 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8276 			 * Check that the ipif matching the requested source
8277 			 * address still exists.
8278 			 */
8279 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8280 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8281 		}
8282 
8283 		unspec_src = (connp != NULL && connp->conn_unspec_src);
8284 
8285 		if (src_ipif == NULL &&
8286 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
8287 			ire_marks |= IRE_MARK_USESRC_CHECK;
8288 			if ((dst_ill->ill_group != NULL) ||
8289 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8290 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8291 			    ire->ire_zoneid != ALL_ZONES) ||
8292 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8293 				/*
8294 				 * If the destination is reachable via a
8295 				 * given gateway, the selected source address
8296 				 * should be in the same subnet as the gateway.
8297 				 * Otherwise, the destination is not reachable.
8298 				 *
8299 				 * If there are no interfaces on the same subnet
8300 				 * as the destination, ipif_select_source gives
8301 				 * first non-deprecated interface which might be
8302 				 * on a different subnet than the gateway.
8303 				 * This is not desirable. Hence pass the dst_ire
8304 				 * source address to ipif_select_source.
8305 				 * It is sure that the destination is reachable
8306 				 * with the dst_ire source address subnet.
8307 				 * So passing dst_ire source address to
8308 				 * ipif_select_source will make sure that the
8309 				 * selected source will be on the same subnet
8310 				 * as dst_ire source address.
8311 				 */
8312 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8313 				src_ipif = ipif_select_source(dst_ill, saddr,
8314 				    zoneid);
8315 				if (src_ipif == NULL) {
8316 					if (ip_debug > 2) {
8317 						pr_addr_dbg("ip_newroute: "
8318 						    "no src for dst %s ",
8319 						    AF_INET, &dst);
8320 						printf("through interface %s\n",
8321 						    dst_ill->ill_name);
8322 					}
8323 					goto icmp_err_ret;
8324 				}
8325 			} else {
8326 				src_ipif = ire->ire_ipif;
8327 				ASSERT(src_ipif != NULL);
8328 				/* hold src_ipif for uniformity */
8329 				ipif_refhold(src_ipif);
8330 			}
8331 		}
8332 
8333 		/*
8334 		 * Assign a source address while we have the conn.
8335 		 * We can't have ip_wput_ire pick a source address when the
8336 		 * packet returns from arp since we need to look at
8337 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8338 		 * going through arp.
8339 		 *
8340 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8341 		 *	  it uses ip6i to store this information.
8342 		 */
8343 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
8344 			ipha->ipha_src = src_ipif->ipif_src_addr;
8345 
8346 		if (ip_debug > 3) {
8347 			/* ip2dbg */
8348 			pr_addr_dbg("ip_newroute: first hop %s\n",
8349 			    AF_INET, &gw);
8350 		}
8351 		ip2dbg(("\tire type %s (%d)\n",
8352 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8353 
8354 		/*
8355 		 * The TTL of multirouted packets is bounded by the
8356 		 * ip_multirt_ttl ndd variable.
8357 		 */
8358 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8359 			/* Force TTL of multirouted packets */
8360 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8361 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8362 				ip2dbg(("ip_newroute: forcing multirt TTL "
8363 				    "to %d (was %d), dst 0x%08x\n",
8364 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8365 				    ntohl(sire->ire_addr)));
8366 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8367 			}
8368 		}
8369 		/*
8370 		 * At this point in ip_newroute(), ire is either the
8371 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8372 		 * destination or an IRE_INTERFACE type that should be used
8373 		 * to resolve an on-subnet destination or an on-subnet
8374 		 * next-hop gateway.
8375 		 *
8376 		 * In the IRE_CACHE case, we have the following :
8377 		 *
8378 		 * 1) src_ipif - used for getting a source address.
8379 		 *
8380 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8381 		 *    means packets using this IRE_CACHE will go out on
8382 		 *    dst_ill.
8383 		 *
8384 		 * 3) The IRE sire will point to the prefix that is the
8385 		 *    longest  matching route for the destination. These
8386 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8387 		 *
8388 		 *    The newly created IRE_CACHE entry for the off-subnet
8389 		 *    destination is tied to both the prefix route and the
8390 		 *    interface route used to resolve the next-hop gateway
8391 		 *    via the ire_phandle and ire_ihandle fields,
8392 		 *    respectively.
8393 		 *
8394 		 * In the IRE_INTERFACE case, we have the following :
8395 		 *
8396 		 * 1) src_ipif - used for getting a source address.
8397 		 *
8398 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8399 		 *    means packets using the IRE_CACHE that we will build
8400 		 *    here will go out on dst_ill.
8401 		 *
8402 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8403 		 *    to be created will only be tied to the IRE_INTERFACE
8404 		 *    that was derived from the ire_ihandle field.
8405 		 *
8406 		 *    If sire is non-NULL, it means the destination is
8407 		 *    off-link and we will first create the IRE_CACHE for the
8408 		 *    gateway. Next time through ip_newroute, we will create
8409 		 *    the IRE_CACHE for the final destination as described
8410 		 *    above.
8411 		 *
8412 		 * In both cases, after the current resolution has been
8413 		 * completed (or possibly initialised, in the IRE_INTERFACE
8414 		 * case), the loop may be re-entered to attempt the resolution
8415 		 * of another RTF_MULTIRT route.
8416 		 *
8417 		 * When an IRE_CACHE entry for the off-subnet destination is
8418 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8419 		 * for further processing in emission loops.
8420 		 */
8421 		save_ire = ire;
8422 		switch (ire->ire_type) {
8423 		case IRE_CACHE: {
8424 			ire_t	*ipif_ire;
8425 
8426 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8427 			if (gw == 0)
8428 				gw = ire->ire_gateway_addr;
8429 			/*
8430 			 * We need 3 ire's to create a new cache ire for an
8431 			 * off-link destination from the cache ire of the
8432 			 * gateway.
8433 			 *
8434 			 *	1. The prefix ire 'sire' (Note that this does
8435 			 *	   not apply to the conn_nexthop_set case)
8436 			 *	2. The cache ire of the gateway 'ire'
8437 			 *	3. The interface ire 'ipif_ire'
8438 			 *
8439 			 * We have (1) and (2). We lookup (3) below.
8440 			 *
8441 			 * If there is no interface route to the gateway,
8442 			 * it is a race condition, where we found the cache
8443 			 * but the interface route has been deleted.
8444 			 */
8445 			if (ip_nexthop) {
8446 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8447 			} else {
8448 				ipif_ire =
8449 				    ire_ihandle_lookup_offlink(ire, sire);
8450 			}
8451 			if (ipif_ire == NULL) {
8452 				ip1dbg(("ip_newroute: "
8453 				    "ire_ihandle_lookup_offlink failed\n"));
8454 				goto icmp_err_ret;
8455 			}
8456 
8457 			/*
8458 			 * Check cached gateway IRE for any security
8459 			 * attributes; if found, associate the gateway
8460 			 * credentials group to the destination IRE.
8461 			 */
8462 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8463 				mutex_enter(&attrp->igsa_lock);
8464 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8465 					GCGRP_REFHOLD(gcgrp);
8466 				mutex_exit(&attrp->igsa_lock);
8467 			}
8468 
8469 			/*
8470 			 * XXX For the source of the resolver mp,
8471 			 * we are using the same DL_UNITDATA_REQ
8472 			 * (from save_ire->ire_nce->nce_res_mp)
8473 			 * though the save_ire is not pointing at the same ill.
8474 			 * This is incorrect. We need to send it up to the
8475 			 * resolver to get the right res_mp. For ethernets
8476 			 * this may be okay (ill_type == DL_ETHER).
8477 			 */
8478 
8479 			ire = ire_create(
8480 			    (uchar_t *)&dst,		/* dest address */
8481 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8482 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8483 			    (uchar_t *)&gw,		/* gateway address */
8484 			    &save_ire->ire_max_frag,
8485 			    save_ire->ire_nce,		/* src nce */
8486 			    dst_ill->ill_rq,		/* recv-from queue */
8487 			    dst_ill->ill_wq,		/* send-to queue */
8488 			    IRE_CACHE,			/* IRE type */
8489 			    src_ipif,
8490 			    (sire != NULL) ?
8491 			    sire->ire_mask : 0, 	/* Parent mask */
8492 			    (sire != NULL) ?
8493 			    sire->ire_phandle : 0,	/* Parent handle */
8494 			    ipif_ire->ire_ihandle,	/* Interface handle */
8495 			    (sire != NULL) ? (sire->ire_flags &
8496 			    (RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8497 			    (sire != NULL) ?
8498 			    &(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8499 			    NULL,
8500 			    gcgrp,
8501 			    ipst);
8502 
8503 			if (ire == NULL) {
8504 				if (gcgrp != NULL) {
8505 					GCGRP_REFRELE(gcgrp);
8506 					gcgrp = NULL;
8507 				}
8508 				ire_refrele(ipif_ire);
8509 				ire_refrele(save_ire);
8510 				break;
8511 			}
8512 
8513 			/* reference now held by IRE */
8514 			gcgrp = NULL;
8515 
8516 			ire->ire_marks |= ire_marks;
8517 
8518 			/*
8519 			 * Prevent sire and ipif_ire from getting deleted.
8520 			 * The newly created ire is tied to both of them via
8521 			 * the phandle and ihandle respectively.
8522 			 */
8523 			if (sire != NULL) {
8524 				IRB_REFHOLD(sire->ire_bucket);
8525 				/* Has it been removed already ? */
8526 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8527 					IRB_REFRELE(sire->ire_bucket);
8528 					ire_refrele(ipif_ire);
8529 					ire_refrele(save_ire);
8530 					break;
8531 				}
8532 			}
8533 
8534 			IRB_REFHOLD(ipif_ire->ire_bucket);
8535 			/* Has it been removed already ? */
8536 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8537 				IRB_REFRELE(ipif_ire->ire_bucket);
8538 				if (sire != NULL)
8539 					IRB_REFRELE(sire->ire_bucket);
8540 				ire_refrele(ipif_ire);
8541 				ire_refrele(save_ire);
8542 				break;
8543 			}
8544 
8545 			xmit_mp = first_mp;
8546 			/*
8547 			 * In the case of multirouting, a copy
8548 			 * of the packet is done before its sending.
8549 			 * The copy is used to attempt another
8550 			 * route resolution, in a next loop.
8551 			 */
8552 			if (ire->ire_flags & RTF_MULTIRT) {
8553 				copy_mp = copymsg(first_mp);
8554 				if (copy_mp != NULL) {
8555 					xmit_mp = copy_mp;
8556 					MULTIRT_DEBUG_TAG(first_mp);
8557 				}
8558 			}
8559 			ire_add_then_send(q, ire, xmit_mp);
8560 			ire_refrele(save_ire);
8561 
8562 			/* Assert that sire is not deleted yet. */
8563 			if (sire != NULL) {
8564 				ASSERT(sire->ire_ptpn != NULL);
8565 				IRB_REFRELE(sire->ire_bucket);
8566 			}
8567 
8568 			/* Assert that ipif_ire is not deleted yet. */
8569 			ASSERT(ipif_ire->ire_ptpn != NULL);
8570 			IRB_REFRELE(ipif_ire->ire_bucket);
8571 			ire_refrele(ipif_ire);
8572 
8573 			/*
8574 			 * If copy_mp is not NULL, multirouting was
8575 			 * requested. We loop to initiate a next
8576 			 * route resolution attempt, starting from sire.
8577 			 */
8578 			if (copy_mp != NULL) {
8579 				/*
8580 				 * Search for the next unresolved
8581 				 * multirt route.
8582 				 */
8583 				copy_mp = NULL;
8584 				ipif_ire = NULL;
8585 				ire = NULL;
8586 				multirt_resolve_next = B_TRUE;
8587 				continue;
8588 			}
8589 			if (sire != NULL)
8590 				ire_refrele(sire);
8591 			ipif_refrele(src_ipif);
8592 			ill_refrele(dst_ill);
8593 			return;
8594 		}
8595 		case IRE_IF_NORESOLVER: {
8596 			if (dst_ill->ill_phys_addr_length != IP_ADDR_LEN &&
8597 			    dst_ill->ill_resolver_mp == NULL) {
8598 				ip1dbg(("ip_newroute: dst_ill %p "
8599 				    "for IRE_IF_NORESOLVER ire %p has "
8600 				    "no ill_resolver_mp\n",
8601 				    (void *)dst_ill, (void *)ire));
8602 				break;
8603 			}
8604 
8605 			/*
8606 			 * TSol note: We are creating the ire cache for the
8607 			 * destination 'dst'. If 'dst' is offlink, going
8608 			 * through the first hop 'gw', the security attributes
8609 			 * of 'dst' must be set to point to the gateway
8610 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8611 			 * is possible that 'dst' is a potential gateway that is
8612 			 * referenced by some route that has some security
8613 			 * attributes. Thus in the former case, we need to do a
8614 			 * gcgrp_lookup of 'gw' while in the latter case we
8615 			 * need to do gcgrp_lookup of 'dst' itself.
8616 			 */
8617 			ga.ga_af = AF_INET;
8618 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8619 			    &ga.ga_addr);
8620 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8621 
8622 			ire = ire_create(
8623 			    (uchar_t *)&dst,		/* dest address */
8624 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8625 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8626 			    (uchar_t *)&gw,		/* gateway address */
8627 			    &save_ire->ire_max_frag,
8628 			    NULL,			/* no src nce */
8629 			    dst_ill->ill_rq,		/* recv-from queue */
8630 			    dst_ill->ill_wq,		/* send-to queue */
8631 			    IRE_CACHE,
8632 			    src_ipif,
8633 			    save_ire->ire_mask,		/* Parent mask */
8634 			    (sire != NULL) ?		/* Parent handle */
8635 			    sire->ire_phandle : 0,
8636 			    save_ire->ire_ihandle,	/* Interface handle */
8637 			    (sire != NULL) ? sire->ire_flags &
8638 			    (RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8639 			    &(save_ire->ire_uinfo),
8640 			    NULL,
8641 			    gcgrp,
8642 			    ipst);
8643 
8644 			if (ire == NULL) {
8645 				if (gcgrp != NULL) {
8646 					GCGRP_REFRELE(gcgrp);
8647 					gcgrp = NULL;
8648 				}
8649 				ire_refrele(save_ire);
8650 				break;
8651 			}
8652 
8653 			/* reference now held by IRE */
8654 			gcgrp = NULL;
8655 
8656 			ire->ire_marks |= ire_marks;
8657 
8658 			/* Prevent save_ire from getting deleted */
8659 			IRB_REFHOLD(save_ire->ire_bucket);
8660 			/* Has it been removed already ? */
8661 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8662 				IRB_REFRELE(save_ire->ire_bucket);
8663 				ire_refrele(save_ire);
8664 				break;
8665 			}
8666 
8667 			/*
8668 			 * In the case of multirouting, a copy
8669 			 * of the packet is made before it is sent.
8670 			 * The copy is used in the next
8671 			 * loop to attempt another resolution.
8672 			 */
8673 			xmit_mp = first_mp;
8674 			if ((sire != NULL) &&
8675 			    (sire->ire_flags & RTF_MULTIRT)) {
8676 				copy_mp = copymsg(first_mp);
8677 				if (copy_mp != NULL) {
8678 					xmit_mp = copy_mp;
8679 					MULTIRT_DEBUG_TAG(first_mp);
8680 				}
8681 			}
8682 			ire_add_then_send(q, ire, xmit_mp);
8683 
8684 			/* Assert that it is not deleted yet. */
8685 			ASSERT(save_ire->ire_ptpn != NULL);
8686 			IRB_REFRELE(save_ire->ire_bucket);
8687 			ire_refrele(save_ire);
8688 
8689 			if (copy_mp != NULL) {
8690 				/*
8691 				 * If we found a (no)resolver, we ignore any
8692 				 * trailing top priority IRE_CACHE in further
8693 				 * loops. This ensures that we do not omit any
8694 				 * (no)resolver.
8695 				 * This IRE_CACHE, if any, will be processed
8696 				 * by another thread entering ip_newroute().
8697 				 * IRE_CACHE entries, if any, will be processed
8698 				 * by another thread entering ip_newroute(),
8699 				 * (upon resolver response, for instance).
8700 				 * This aims to force parallel multirt
8701 				 * resolutions as soon as a packet must be sent.
8702 				 * In the best case, after the tx of only one
8703 				 * packet, all reachable routes are resolved.
8704 				 * Otherwise, the resolution of all RTF_MULTIRT
8705 				 * routes would require several emissions.
8706 				 */
8707 				multirt_flags &= ~MULTIRT_CACHEGW;
8708 
8709 				/*
8710 				 * Search for the next unresolved multirt
8711 				 * route.
8712 				 */
8713 				copy_mp = NULL;
8714 				save_ire = NULL;
8715 				ire = NULL;
8716 				multirt_resolve_next = B_TRUE;
8717 				continue;
8718 			}
8719 
8720 			/*
8721 			 * Don't need sire anymore
8722 			 */
8723 			if (sire != NULL)
8724 				ire_refrele(sire);
8725 
8726 			ipif_refrele(src_ipif);
8727 			ill_refrele(dst_ill);
8728 			return;
8729 		}
8730 		case IRE_IF_RESOLVER:
8731 			/*
8732 			 * We can't build an IRE_CACHE yet, but at least we
8733 			 * found a resolver that can help.
8734 			 */
8735 			res_mp = dst_ill->ill_resolver_mp;
8736 			if (!OK_RESOLVER_MP(res_mp))
8737 				break;
8738 
8739 			/*
8740 			 * To be at this point in the code with a non-zero gw
8741 			 * means that dst is reachable through a gateway that
8742 			 * we have never resolved.  By changing dst to the gw
8743 			 * addr we resolve the gateway first.
8744 			 * When ire_add_then_send() tries to put the IP dg
8745 			 * to dst, it will reenter ip_newroute() at which
8746 			 * time we will find the IRE_CACHE for the gw and
8747 			 * create another IRE_CACHE in case IRE_CACHE above.
8748 			 */
8749 			if (gw != INADDR_ANY) {
8750 				/*
8751 				 * The source ipif that was determined above was
8752 				 * relative to the destination address, not the
8753 				 * gateway's. If src_ipif was not taken out of
8754 				 * the IRE_IF_RESOLVER entry, we'll need to call
8755 				 * ipif_select_source() again.
8756 				 */
8757 				if (src_ipif != ire->ire_ipif) {
8758 					ipif_refrele(src_ipif);
8759 					src_ipif = ipif_select_source(dst_ill,
8760 					    gw, zoneid);
8761 					if (src_ipif == NULL) {
8762 						if (ip_debug > 2) {
8763 							pr_addr_dbg(
8764 							    "ip_newroute: no "
8765 							    "src for gw %s ",
8766 							    AF_INET, &gw);
8767 							printf("through "
8768 							    "interface %s\n",
8769 							    dst_ill->ill_name);
8770 						}
8771 						goto icmp_err_ret;
8772 					}
8773 				}
8774 				save_dst = dst;
8775 				dst = gw;
8776 				gw = INADDR_ANY;
8777 			}
8778 
8779 			/*
8780 			 * We obtain a partial IRE_CACHE which we will pass
8781 			 * along with the resolver query.  When the response
8782 			 * comes back it will be there ready for us to add.
8783 			 * The ire_max_frag is atomically set under the
8784 			 * irebucket lock in ire_add_v[46].
8785 			 */
8786 
8787 			ire = ire_create_mp(
8788 			    (uchar_t *)&dst,		/* dest address */
8789 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8790 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8791 			    (uchar_t *)&gw,		/* gateway address */
8792 			    NULL,			/* ire_max_frag */
8793 			    NULL,			/* no src nce */
8794 			    dst_ill->ill_rq,		/* recv-from queue */
8795 			    dst_ill->ill_wq,		/* send-to queue */
8796 			    IRE_CACHE,
8797 			    src_ipif,			/* Interface ipif */
8798 			    save_ire->ire_mask,		/* Parent mask */
8799 			    0,
8800 			    save_ire->ire_ihandle,	/* Interface handle */
8801 			    0,				/* flags if any */
8802 			    &(save_ire->ire_uinfo),
8803 			    NULL,
8804 			    NULL,
8805 			    ipst);
8806 
8807 			if (ire == NULL) {
8808 				ire_refrele(save_ire);
8809 				break;
8810 			}
8811 
8812 			if ((sire != NULL) &&
8813 			    (sire->ire_flags & RTF_MULTIRT)) {
8814 				copy_mp = copymsg(first_mp);
8815 				if (copy_mp != NULL)
8816 					MULTIRT_DEBUG_TAG(copy_mp);
8817 			}
8818 
8819 			ire->ire_marks |= ire_marks;
8820 
8821 			/*
8822 			 * Construct message chain for the resolver
8823 			 * of the form:
8824 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8825 			 * Packet could contain a IPSEC_OUT mp.
8826 			 *
8827 			 * NOTE : ire will be added later when the response
8828 			 * comes back from ARP. If the response does not
8829 			 * come back, ARP frees the packet. For this reason,
8830 			 * we can't REFHOLD the bucket of save_ire to prevent
8831 			 * deletions. We may not be able to REFRELE the bucket
8832 			 * if the response never comes back. Thus, before
8833 			 * adding the ire, ire_add_v4 will make sure that the
8834 			 * interface route does not get deleted. This is the
8835 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8836 			 * where we can always prevent deletions because of
8837 			 * the synchronous nature of adding IRES i.e
8838 			 * ire_add_then_send is called after creating the IRE.
8839 			 */
8840 			ASSERT(ire->ire_mp != NULL);
8841 			ire->ire_mp->b_cont = first_mp;
8842 			/* Have saved_mp handy, for cleanup if canput fails */
8843 			saved_mp = mp;
8844 			mp = copyb(res_mp);
8845 			if (mp == NULL) {
8846 				/* Prepare for cleanup */
8847 				mp = saved_mp; /* pkt */
8848 				ire_delete(ire); /* ire_mp */
8849 				ire = NULL;
8850 				ire_refrele(save_ire);
8851 				if (copy_mp != NULL) {
8852 					MULTIRT_DEBUG_UNTAG(copy_mp);
8853 					freemsg(copy_mp);
8854 					copy_mp = NULL;
8855 				}
8856 				break;
8857 			}
8858 			linkb(mp, ire->ire_mp);
8859 
8860 			/*
8861 			 * Fill in the source and dest addrs for the resolver.
8862 			 * NOTE: this depends on memory layouts imposed by
8863 			 * ill_init().
8864 			 */
8865 			areq = (areq_t *)mp->b_rptr;
8866 			addrp = (ipaddr_t *)((char *)areq +
8867 			    areq->areq_sender_addr_offset);
8868 			if (do_attach_ill) {
8869 				/*
8870 				 * This is bind to no failover case.
8871 				 * arp packet also must go out on attach_ill.
8872 				 */
8873 				ASSERT(ipha->ipha_src != NULL);
8874 				*addrp = ipha->ipha_src;
8875 			} else {
8876 				*addrp = save_ire->ire_src_addr;
8877 			}
8878 
8879 			ire_refrele(save_ire);
8880 			addrp = (ipaddr_t *)((char *)areq +
8881 			    areq->areq_target_addr_offset);
8882 			*addrp = dst;
8883 			/* Up to the resolver. */
8884 			if (canputnext(dst_ill->ill_rq) &&
8885 			    !(dst_ill->ill_arp_closing)) {
8886 				putnext(dst_ill->ill_rq, mp);
8887 				ire = NULL;
8888 				if (copy_mp != NULL) {
8889 					/*
8890 					 * If we found a resolver, we ignore
8891 					 * any trailing top priority IRE_CACHE
8892 					 * in the further loops. This ensures
8893 					 * that we do not omit any resolver.
8894 					 * IRE_CACHE entries, if any, will be
8895 					 * processed next time we enter
8896 					 * ip_newroute().
8897 					 */
8898 					multirt_flags &= ~MULTIRT_CACHEGW;
8899 					/*
8900 					 * Search for the next unresolved
8901 					 * multirt route.
8902 					 */
8903 					first_mp = copy_mp;
8904 					copy_mp = NULL;
8905 					/* Prepare the next resolution loop. */
8906 					mp = first_mp;
8907 					EXTRACT_PKT_MP(mp, first_mp,
8908 					    mctl_present);
8909 					if (mctl_present)
8910 						io = (ipsec_out_t *)
8911 						    first_mp->b_rptr;
8912 					ipha = (ipha_t *)mp->b_rptr;
8913 
8914 					ASSERT(sire != NULL);
8915 
8916 					dst = save_dst;
8917 					multirt_resolve_next = B_TRUE;
8918 					continue;
8919 				}
8920 
8921 				if (sire != NULL)
8922 					ire_refrele(sire);
8923 
8924 				/*
8925 				 * The response will come back in ip_wput
8926 				 * with db_type IRE_DB_TYPE.
8927 				 */
8928 				ipif_refrele(src_ipif);
8929 				ill_refrele(dst_ill);
8930 				return;
8931 			} else {
8932 				/* Prepare for cleanup */
8933 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8934 				    mp);
8935 				mp->b_cont = NULL;
8936 				freeb(mp); /* areq */
8937 				/*
8938 				 * this is an ire that is not added to the
8939 				 * cache. ire_freemblk will handle the release
8940 				 * of any resources associated with the ire.
8941 				 */
8942 				ire_delete(ire); /* ire_mp */
8943 				mp = saved_mp; /* pkt */
8944 				ire = NULL;
8945 				if (copy_mp != NULL) {
8946 					MULTIRT_DEBUG_UNTAG(copy_mp);
8947 					freemsg(copy_mp);
8948 					copy_mp = NULL;
8949 				}
8950 				break;
8951 			}
8952 		default:
8953 			break;
8954 		}
8955 	} while (multirt_resolve_next);
8956 
8957 	ip1dbg(("ip_newroute: dropped\n"));
8958 	/* Did this packet originate externally? */
8959 	if (mp->b_prev) {
8960 		mp->b_next = NULL;
8961 		mp->b_prev = NULL;
8962 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
8963 	} else {
8964 		if (dst_ill != NULL) {
8965 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
8966 		} else {
8967 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
8968 		}
8969 	}
8970 	ASSERT(copy_mp == NULL);
8971 	MULTIRT_DEBUG_UNTAG(first_mp);
8972 	freemsg(first_mp);
8973 	if (ire != NULL)
8974 		ire_refrele(ire);
8975 	if (sire != NULL)
8976 		ire_refrele(sire);
8977 	if (src_ipif != NULL)
8978 		ipif_refrele(src_ipif);
8979 	if (dst_ill != NULL)
8980 		ill_refrele(dst_ill);
8981 	return;
8982 
8983 icmp_err_ret:
8984 	ip1dbg(("ip_newroute: no route\n"));
8985 	if (src_ipif != NULL)
8986 		ipif_refrele(src_ipif);
8987 	if (dst_ill != NULL)
8988 		ill_refrele(dst_ill);
8989 	if (sire != NULL)
8990 		ire_refrele(sire);
8991 	/* Did this packet originate externally? */
8992 	if (mp->b_prev) {
8993 		mp->b_next = NULL;
8994 		mp->b_prev = NULL;
8995 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
8996 		q = WR(q);
8997 	} else {
8998 		/*
8999 		 * There is no outgoing ill, so just increment the
9000 		 * system MIB.
9001 		 */
9002 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
9003 		/*
9004 		 * Since ip_wput() isn't close to finished, we fill
9005 		 * in enough of the header for credible error reporting.
9006 		 */
9007 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
9008 			/* Failed */
9009 			MULTIRT_DEBUG_UNTAG(first_mp);
9010 			freemsg(first_mp);
9011 			if (ire != NULL)
9012 				ire_refrele(ire);
9013 			return;
9014 		}
9015 	}
9016 
9017 	/*
9018 	 * At this point we will have ire only if RTF_BLACKHOLE
9019 	 * or RTF_REJECT flags are set on the IRE. It will not
9020 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9021 	 */
9022 	if (ire != NULL) {
9023 		if (ire->ire_flags & RTF_BLACKHOLE) {
9024 			ire_refrele(ire);
9025 			MULTIRT_DEBUG_UNTAG(first_mp);
9026 			freemsg(first_mp);
9027 			return;
9028 		}
9029 		ire_refrele(ire);
9030 	}
9031 	if (ip_source_routed(ipha, ipst)) {
9032 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
9033 		    zoneid, ipst);
9034 		return;
9035 	}
9036 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9037 }
9038 
9039 ip_opt_info_t zero_info;
9040 
9041 /*
9042  * IPv4 -
9043  * ip_newroute_ipif is called by ip_wput_multicast and
9044  * ip_rput_forward_multicast whenever we need to send
9045  * out a packet to a destination address for which we do not have specific
9046  * routing information. It is used when the packet will be sent out
9047  * on a specific interface. It is also called by ip_wput() when IP_BOUND_IF
9048  * socket option is set or icmp error message wants to go out on a particular
9049  * interface for a unicast packet.
9050  *
9051  * In most cases, the destination address is resolved thanks to the ipif
9052  * intrinsic resolver. However, there are some cases where the call to
9053  * ip_newroute_ipif must take into account the potential presence of
9054  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
9055  * that uses the interface. This is specified through flags,
9056  * which can be a combination of:
9057  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
9058  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
9059  *   and flags. Additionally, the packet source address has to be set to
9060  *   the specified address. The caller is thus expected to set this flag
9061  *   if the packet has no specific source address yet.
9062  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
9063  *   flag, the resulting ire will inherit the flag. All unresolved routes
9064  *   to the destination must be explored in the same call to
9065  *   ip_newroute_ipif().
9066  */
9067 static void
9068 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
9069     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
9070 {
9071 	areq_t	*areq;
9072 	ire_t	*ire = NULL;
9073 	mblk_t	*res_mp;
9074 	ipaddr_t *addrp;
9075 	mblk_t *first_mp;
9076 	ire_t	*save_ire = NULL;
9077 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
9078 	ipif_t	*src_ipif = NULL;
9079 	ushort_t ire_marks = 0;
9080 	ill_t	*dst_ill = NULL;
9081 	boolean_t mctl_present;
9082 	ipsec_out_t *io;
9083 	ipha_t *ipha;
9084 	int	ihandle = 0;
9085 	mblk_t	*saved_mp;
9086 	ire_t   *fire = NULL;
9087 	mblk_t  *copy_mp = NULL;
9088 	boolean_t multirt_resolve_next;
9089 	boolean_t unspec_src;
9090 	ipaddr_t ipha_dst;
9091 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
9092 
9093 	/*
9094 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
9095 	 * here for uniformity
9096 	 */
9097 	ipif_refhold(ipif);
9098 
9099 	/*
9100 	 * This loop is run only once in most cases.
9101 	 * We loop to resolve further routes only when the destination
9102 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
9103 	 */
9104 	do {
9105 		if (dst_ill != NULL) {
9106 			ill_refrele(dst_ill);
9107 			dst_ill = NULL;
9108 		}
9109 		if (src_ipif != NULL) {
9110 			ipif_refrele(src_ipif);
9111 			src_ipif = NULL;
9112 		}
9113 		multirt_resolve_next = B_FALSE;
9114 
9115 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9116 		    ipif->ipif_ill->ill_name));
9117 
9118 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
9119 		if (mctl_present)
9120 			io = (ipsec_out_t *)first_mp->b_rptr;
9121 
9122 		ipha = (ipha_t *)mp->b_rptr;
9123 
9124 		/*
9125 		 * Save the packet destination address, we may need it after
9126 		 * the packet has been consumed.
9127 		 */
9128 		ipha_dst = ipha->ipha_dst;
9129 
9130 		/*
9131 		 * If the interface is a pt-pt interface we look for an
9132 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9133 		 * local_address and the pt-pt destination address. Otherwise
9134 		 * we just match the local address.
9135 		 * NOTE: dst could be different than ipha->ipha_dst in case
9136 		 * of sending igmp multicast packets over a point-to-point
9137 		 * connection.
9138 		 * Thus we must be careful enough to check ipha_dst to be a
9139 		 * multicast address, otherwise it will take xmit_if path for
9140 		 * multicast packets resulting into kernel stack overflow by
9141 		 * repeated calls to ip_newroute_ipif from ire_send().
9142 		 */
9143 		if (CLASSD(ipha_dst) &&
9144 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9145 			goto err_ret;
9146 		}
9147 
9148 		/*
9149 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9150 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9151 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9152 		 * propagate its flags to the new ire.
9153 		 */
9154 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9155 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9156 			ip2dbg(("ip_newroute_ipif: "
9157 			    "ipif_lookup_multi_ire("
9158 			    "ipif %p, dst %08x) = fire %p\n",
9159 			    (void *)ipif, ntohl(dst), (void *)fire));
9160 		}
9161 
9162 		if (mctl_present && io->ipsec_out_attach_if) {
9163 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
9164 			    io->ipsec_out_ill_index, B_FALSE, ipst);
9165 
9166 			/* Failure case frees things for us. */
9167 			if (attach_ill == NULL) {
9168 				ipif_refrele(ipif);
9169 				if (fire != NULL)
9170 					ire_refrele(fire);
9171 				return;
9172 			}
9173 
9174 			/*
9175 			 * Check if we need an ire that will not be
9176 			 * looked up by anybody else i.e. HIDDEN.
9177 			 */
9178 			if (ill_is_probeonly(attach_ill)) {
9179 				ire_marks = IRE_MARK_HIDDEN;
9180 			}
9181 			/*
9182 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
9183 			 * case.
9184 			 */
9185 			dst_ill = ipif->ipif_ill;
9186 			/* attach_ill has been refheld by ip_grab_attach_ill */
9187 			ASSERT(dst_ill == attach_ill);
9188 		} else {
9189 			/*
9190 			 * If the interface belongs to an interface group,
9191 			 * make sure the next possible interface in the group
9192 			 * is used.  This encourages load spreading among
9193 			 * peers in an interface group.
9194 			 * Note: load spreading is disabled for RTF_MULTIRT
9195 			 * routes.
9196 			 */
9197 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9198 			    (fire->ire_flags & RTF_MULTIRT)) {
9199 				/*
9200 				 * Don't perform outbound load spreading
9201 				 * in the case of an RTF_MULTIRT issued route,
9202 				 * we actually typically want to replicate
9203 				 * outgoing packets through particular
9204 				 * interfaces.
9205 				 */
9206 				dst_ill = ipif->ipif_ill;
9207 				ill_refhold(dst_ill);
9208 			} else {
9209 				dst_ill = ip_newroute_get_dst_ill(
9210 				    ipif->ipif_ill);
9211 			}
9212 			if (dst_ill == NULL) {
9213 				if (ip_debug > 2) {
9214 					pr_addr_dbg("ip_newroute_ipif: "
9215 					    "no dst ill for dst %s\n",
9216 					    AF_INET, &dst);
9217 				}
9218 				goto err_ret;
9219 			}
9220 		}
9221 
9222 		/*
9223 		 * Pick a source address preferring non-deprecated ones.
9224 		 * Unlike ip_newroute, we don't do any source address
9225 		 * selection here since for multicast it really does not help
9226 		 * in inbound load spreading as in the unicast case.
9227 		 */
9228 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9229 		    (fire->ire_flags & RTF_SETSRC)) {
9230 			/*
9231 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9232 			 * on that interface. This ire has RTF_SETSRC flag, so
9233 			 * the source address of the packet must be changed.
9234 			 * Check that the ipif matching the requested source
9235 			 * address still exists.
9236 			 */
9237 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9238 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9239 		}
9240 
9241 		unspec_src = (connp != NULL && connp->conn_unspec_src);
9242 
9243 		if (((!ipif->ipif_isv6 && ipif->ipif_lcl_addr == INADDR_ANY) ||
9244 		    (ipif->ipif_flags & (IPIF_DEPRECATED|IPIF_UP)) != IPIF_UP ||
9245 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9246 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9247 		    (src_ipif == NULL) &&
9248 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
9249 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9250 			if (src_ipif == NULL) {
9251 				if (ip_debug > 2) {
9252 					/* ip1dbg */
9253 					pr_addr_dbg("ip_newroute_ipif: "
9254 					    "no src for dst %s",
9255 					    AF_INET, &dst);
9256 				}
9257 				ip1dbg((" through interface %s\n",
9258 				    dst_ill->ill_name));
9259 				goto err_ret;
9260 			}
9261 			ipif_refrele(ipif);
9262 			ipif = src_ipif;
9263 			ipif_refhold(ipif);
9264 		}
9265 		if (src_ipif == NULL) {
9266 			src_ipif = ipif;
9267 			ipif_refhold(src_ipif);
9268 		}
9269 
9270 		/*
9271 		 * Assign a source address while we have the conn.
9272 		 * We can't have ip_wput_ire pick a source address when the
9273 		 * packet returns from arp since conn_unspec_src might be set
9274 		 * and we lose the conn when going through arp.
9275 		 */
9276 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
9277 			ipha->ipha_src = src_ipif->ipif_src_addr;
9278 
9279 		/*
9280 		 * In the case of IP_BOUND_IF and IP_PKTINFO, it is possible
9281 		 * that the outgoing interface does not have an interface ire.
9282 		 */
9283 		if (CLASSD(ipha_dst) && (connp == NULL ||
9284 		    connp->conn_outgoing_ill == NULL) &&
9285 		    infop->ip_opt_ill_index == 0) {
9286 			/* ipif_to_ire returns an held ire */
9287 			ire = ipif_to_ire(ipif);
9288 			if (ire == NULL)
9289 				goto err_ret;
9290 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9291 				goto err_ret;
9292 			/*
9293 			 * ihandle is needed when the ire is added to
9294 			 * cache table.
9295 			 */
9296 			save_ire = ire;
9297 			ihandle = save_ire->ire_ihandle;
9298 
9299 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9300 			    "flags %04x\n",
9301 			    (void *)ire, (void *)ipif, flags));
9302 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9303 			    (fire->ire_flags & RTF_MULTIRT)) {
9304 				/*
9305 				 * As requested by flags, an IRE_OFFSUBNET was
9306 				 * looked up on that interface. This ire has
9307 				 * RTF_MULTIRT flag, so the resolution loop will
9308 				 * be re-entered to resolve additional routes on
9309 				 * other interfaces. For that purpose, a copy of
9310 				 * the packet is performed at this point.
9311 				 */
9312 				fire->ire_last_used_time = lbolt;
9313 				copy_mp = copymsg(first_mp);
9314 				if (copy_mp) {
9315 					MULTIRT_DEBUG_TAG(copy_mp);
9316 				}
9317 			}
9318 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9319 			    (fire->ire_flags & RTF_SETSRC)) {
9320 				/*
9321 				 * As requested by flags, an IRE_OFFSUBET was
9322 				 * looked up on that interface. This ire has
9323 				 * RTF_SETSRC flag, so the source address of the
9324 				 * packet must be changed.
9325 				 */
9326 				ipha->ipha_src = fire->ire_src_addr;
9327 			}
9328 		} else {
9329 			ASSERT((connp == NULL) ||
9330 			    (connp->conn_outgoing_ill != NULL) ||
9331 			    (connp->conn_dontroute) ||
9332 			    infop->ip_opt_ill_index != 0);
9333 			/*
9334 			 * The only ways we can come here are:
9335 			 * 1) IP_BOUND_IF socket option is set
9336 			 * 2) SO_DONTROUTE socket option is set
9337 			 * 3) IP_PKTINFO option is passed in as ancillary data.
9338 			 * In all cases, the new ire will not be added
9339 			 * into cache table.
9340 			 */
9341 			ire_marks |= IRE_MARK_NOADD;
9342 		}
9343 
9344 		switch (ipif->ipif_net_type) {
9345 		case IRE_IF_NORESOLVER: {
9346 			/* We have what we need to build an IRE_CACHE. */
9347 
9348 			if ((dst_ill->ill_phys_addr_length != IP_ADDR_LEN) &&
9349 			    (dst_ill->ill_resolver_mp == NULL)) {
9350 				ip1dbg(("ip_newroute_ipif: dst_ill %p "
9351 				    "for IRE_IF_NORESOLVER ire %p has "
9352 				    "no ill_resolver_mp\n",
9353 				    (void *)dst_ill, (void *)ire));
9354 				break;
9355 			}
9356 
9357 			/*
9358 			 * The new ire inherits the IRE_OFFSUBNET flags
9359 			 * and source address, if this was requested.
9360 			 */
9361 			ire = ire_create(
9362 			    (uchar_t *)&dst,		/* dest address */
9363 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9364 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9365 			    NULL,			/* gateway address */
9366 			    &ipif->ipif_mtu,
9367 			    NULL,			/* no src nce */
9368 			    dst_ill->ill_rq,		/* recv-from queue */
9369 			    dst_ill->ill_wq,		/* send-to queue */
9370 			    IRE_CACHE,
9371 			    src_ipif,
9372 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9373 			    (fire != NULL) ?		/* Parent handle */
9374 			    fire->ire_phandle : 0,
9375 			    ihandle,			/* Interface handle */
9376 			    (fire != NULL) ?
9377 			    (fire->ire_flags &
9378 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9379 			    (save_ire == NULL ? &ire_uinfo_null :
9380 			    &save_ire->ire_uinfo),
9381 			    NULL,
9382 			    NULL,
9383 			    ipst);
9384 
9385 			if (ire == NULL) {
9386 				if (save_ire != NULL)
9387 					ire_refrele(save_ire);
9388 				break;
9389 			}
9390 
9391 			ire->ire_marks |= ire_marks;
9392 
9393 			/*
9394 			 * If IRE_MARK_NOADD is set then we need to convert
9395 			 * the max_fragp to a useable value now. This is
9396 			 * normally done in ire_add_v[46]. We also need to
9397 			 * associate the ire with an nce (normally would be
9398 			 * done in ip_wput_nondata()).
9399 			 *
9400 			 * Note that IRE_MARK_NOADD packets created here
9401 			 * do not have a non-null ire_mp pointer. The null
9402 			 * value of ire_bucket indicates that they were
9403 			 * never added.
9404 			 */
9405 			if (ire->ire_marks & IRE_MARK_NOADD) {
9406 				uint_t  max_frag;
9407 
9408 				max_frag = *ire->ire_max_fragp;
9409 				ire->ire_max_fragp = NULL;
9410 				ire->ire_max_frag = max_frag;
9411 
9412 				if ((ire->ire_nce = ndp_lookup_v4(
9413 				    ire_to_ill(ire),
9414 				    (ire->ire_gateway_addr != INADDR_ANY ?
9415 				    &ire->ire_gateway_addr : &ire->ire_addr),
9416 				    B_FALSE)) == NULL) {
9417 					if (save_ire != NULL)
9418 						ire_refrele(save_ire);
9419 					break;
9420 				}
9421 				ASSERT(ire->ire_nce->nce_state ==
9422 				    ND_REACHABLE);
9423 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9424 			}
9425 
9426 			/* Prevent save_ire from getting deleted */
9427 			if (save_ire != NULL) {
9428 				IRB_REFHOLD(save_ire->ire_bucket);
9429 				/* Has it been removed already ? */
9430 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9431 					IRB_REFRELE(save_ire->ire_bucket);
9432 					ire_refrele(save_ire);
9433 					break;
9434 				}
9435 			}
9436 
9437 			ire_add_then_send(q, ire, first_mp);
9438 
9439 			/* Assert that save_ire is not deleted yet. */
9440 			if (save_ire != NULL) {
9441 				ASSERT(save_ire->ire_ptpn != NULL);
9442 				IRB_REFRELE(save_ire->ire_bucket);
9443 				ire_refrele(save_ire);
9444 				save_ire = NULL;
9445 			}
9446 			if (fire != NULL) {
9447 				ire_refrele(fire);
9448 				fire = NULL;
9449 			}
9450 
9451 			/*
9452 			 * the resolution loop is re-entered if this
9453 			 * was requested through flags and if we
9454 			 * actually are in a multirouting case.
9455 			 */
9456 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9457 				boolean_t need_resolve =
9458 				    ire_multirt_need_resolve(ipha_dst,
9459 				    MBLK_GETLABEL(copy_mp), ipst);
9460 				if (!need_resolve) {
9461 					MULTIRT_DEBUG_UNTAG(copy_mp);
9462 					freemsg(copy_mp);
9463 					copy_mp = NULL;
9464 				} else {
9465 					/*
9466 					 * ipif_lookup_group() calls
9467 					 * ire_lookup_multi() that uses
9468 					 * ire_ftable_lookup() to find
9469 					 * an IRE_INTERFACE for the group.
9470 					 * In the multirt case,
9471 					 * ire_lookup_multi() then invokes
9472 					 * ire_multirt_lookup() to find
9473 					 * the next resolvable ire.
9474 					 * As a result, we obtain an new
9475 					 * interface, derived from the
9476 					 * next ire.
9477 					 */
9478 					ipif_refrele(ipif);
9479 					ipif = ipif_lookup_group(ipha_dst,
9480 					    zoneid, ipst);
9481 					ip2dbg(("ip_newroute_ipif: "
9482 					    "multirt dst %08x, ipif %p\n",
9483 					    htonl(dst), (void *)ipif));
9484 					if (ipif != NULL) {
9485 						mp = copy_mp;
9486 						copy_mp = NULL;
9487 						multirt_resolve_next = B_TRUE;
9488 						continue;
9489 					} else {
9490 						freemsg(copy_mp);
9491 					}
9492 				}
9493 			}
9494 			if (ipif != NULL)
9495 				ipif_refrele(ipif);
9496 			ill_refrele(dst_ill);
9497 			ipif_refrele(src_ipif);
9498 			return;
9499 		}
9500 		case IRE_IF_RESOLVER:
9501 			/*
9502 			 * We can't build an IRE_CACHE yet, but at least
9503 			 * we found a resolver that can help.
9504 			 */
9505 			res_mp = dst_ill->ill_resolver_mp;
9506 			if (!OK_RESOLVER_MP(res_mp))
9507 				break;
9508 
9509 			/*
9510 			 * We obtain a partial IRE_CACHE which we will pass
9511 			 * along with the resolver query.  When the response
9512 			 * comes back it will be there ready for us to add.
9513 			 * The new ire inherits the IRE_OFFSUBNET flags
9514 			 * and source address, if this was requested.
9515 			 * The ire_max_frag is atomically set under the
9516 			 * irebucket lock in ire_add_v[46]. Only in the
9517 			 * case of IRE_MARK_NOADD, we set it here itself.
9518 			 */
9519 			ire = ire_create_mp(
9520 			    (uchar_t *)&dst,		/* dest address */
9521 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9522 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9523 			    NULL,			/* gateway address */
9524 			    (ire_marks & IRE_MARK_NOADD) ?
9525 			    ipif->ipif_mtu : 0,		/* max_frag */
9526 			    NULL,			/* no src nce */
9527 			    dst_ill->ill_rq,		/* recv-from queue */
9528 			    dst_ill->ill_wq,		/* send-to queue */
9529 			    IRE_CACHE,
9530 			    src_ipif,
9531 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9532 			    (fire != NULL) ?		/* Parent handle */
9533 			    fire->ire_phandle : 0,
9534 			    ihandle,			/* Interface handle */
9535 			    (fire != NULL) ?		/* flags if any */
9536 			    (fire->ire_flags &
9537 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9538 			    (save_ire == NULL ? &ire_uinfo_null :
9539 			    &save_ire->ire_uinfo),
9540 			    NULL,
9541 			    NULL,
9542 			    ipst);
9543 
9544 			if (save_ire != NULL) {
9545 				ire_refrele(save_ire);
9546 				save_ire = NULL;
9547 			}
9548 			if (ire == NULL)
9549 				break;
9550 
9551 			ire->ire_marks |= ire_marks;
9552 			/*
9553 			 * Construct message chain for the resolver of the
9554 			 * form:
9555 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9556 			 *
9557 			 * NOTE : ire will be added later when the response
9558 			 * comes back from ARP. If the response does not
9559 			 * come back, ARP frees the packet. For this reason,
9560 			 * we can't REFHOLD the bucket of save_ire to prevent
9561 			 * deletions. We may not be able to REFRELE the
9562 			 * bucket if the response never comes back.
9563 			 * Thus, before adding the ire, ire_add_v4 will make
9564 			 * sure that the interface route does not get deleted.
9565 			 * This is the only case unlike ip_newroute_v6,
9566 			 * ip_newroute_ipif_v6 where we can always prevent
9567 			 * deletions because ire_add_then_send is called after
9568 			 * creating the IRE.
9569 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9570 			 * does not add this IRE into the IRE CACHE.
9571 			 */
9572 			ASSERT(ire->ire_mp != NULL);
9573 			ire->ire_mp->b_cont = first_mp;
9574 			/* Have saved_mp handy, for cleanup if canput fails */
9575 			saved_mp = mp;
9576 			mp = copyb(res_mp);
9577 			if (mp == NULL) {
9578 				/* Prepare for cleanup */
9579 				mp = saved_mp; /* pkt */
9580 				ire_delete(ire); /* ire_mp */
9581 				ire = NULL;
9582 				if (copy_mp != NULL) {
9583 					MULTIRT_DEBUG_UNTAG(copy_mp);
9584 					freemsg(copy_mp);
9585 					copy_mp = NULL;
9586 				}
9587 				break;
9588 			}
9589 			linkb(mp, ire->ire_mp);
9590 
9591 			/*
9592 			 * Fill in the source and dest addrs for the resolver.
9593 			 * NOTE: this depends on memory layouts imposed by
9594 			 * ill_init().
9595 			 */
9596 			areq = (areq_t *)mp->b_rptr;
9597 			addrp = (ipaddr_t *)((char *)areq +
9598 			    areq->areq_sender_addr_offset);
9599 			*addrp = ire->ire_src_addr;
9600 			addrp = (ipaddr_t *)((char *)areq +
9601 			    areq->areq_target_addr_offset);
9602 			*addrp = dst;
9603 			/* Up to the resolver. */
9604 			if (canputnext(dst_ill->ill_rq) &&
9605 			    !(dst_ill->ill_arp_closing)) {
9606 				putnext(dst_ill->ill_rq, mp);
9607 				/*
9608 				 * The response will come back in ip_wput
9609 				 * with db_type IRE_DB_TYPE.
9610 				 */
9611 			} else {
9612 				mp->b_cont = NULL;
9613 				freeb(mp); /* areq */
9614 				ire_delete(ire); /* ire_mp */
9615 				saved_mp->b_next = NULL;
9616 				saved_mp->b_prev = NULL;
9617 				freemsg(first_mp); /* pkt */
9618 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9619 			}
9620 
9621 			if (fire != NULL) {
9622 				ire_refrele(fire);
9623 				fire = NULL;
9624 			}
9625 
9626 
9627 			/*
9628 			 * The resolution loop is re-entered if this was
9629 			 * requested through flags and we actually are
9630 			 * in a multirouting case.
9631 			 */
9632 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9633 				boolean_t need_resolve =
9634 				    ire_multirt_need_resolve(ipha_dst,
9635 				    MBLK_GETLABEL(copy_mp), ipst);
9636 				if (!need_resolve) {
9637 					MULTIRT_DEBUG_UNTAG(copy_mp);
9638 					freemsg(copy_mp);
9639 					copy_mp = NULL;
9640 				} else {
9641 					/*
9642 					 * ipif_lookup_group() calls
9643 					 * ire_lookup_multi() that uses
9644 					 * ire_ftable_lookup() to find
9645 					 * an IRE_INTERFACE for the group.
9646 					 * In the multirt case,
9647 					 * ire_lookup_multi() then invokes
9648 					 * ire_multirt_lookup() to find
9649 					 * the next resolvable ire.
9650 					 * As a result, we obtain an new
9651 					 * interface, derived from the
9652 					 * next ire.
9653 					 */
9654 					ipif_refrele(ipif);
9655 					ipif = ipif_lookup_group(ipha_dst,
9656 					    zoneid, ipst);
9657 					if (ipif != NULL) {
9658 						mp = copy_mp;
9659 						copy_mp = NULL;
9660 						multirt_resolve_next = B_TRUE;
9661 						continue;
9662 					} else {
9663 						freemsg(copy_mp);
9664 					}
9665 				}
9666 			}
9667 			if (ipif != NULL)
9668 				ipif_refrele(ipif);
9669 			ill_refrele(dst_ill);
9670 			ipif_refrele(src_ipif);
9671 			return;
9672 		default:
9673 			break;
9674 		}
9675 	} while (multirt_resolve_next);
9676 
9677 err_ret:
9678 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9679 	if (fire != NULL)
9680 		ire_refrele(fire);
9681 	ipif_refrele(ipif);
9682 	/* Did this packet originate externally? */
9683 	if (dst_ill != NULL)
9684 		ill_refrele(dst_ill);
9685 	if (src_ipif != NULL)
9686 		ipif_refrele(src_ipif);
9687 	if (mp->b_prev || mp->b_next) {
9688 		mp->b_next = NULL;
9689 		mp->b_prev = NULL;
9690 	} else {
9691 		/*
9692 		 * Since ip_wput() isn't close to finished, we fill
9693 		 * in enough of the header for credible error reporting.
9694 		 */
9695 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9696 			/* Failed */
9697 			freemsg(first_mp);
9698 			if (ire != NULL)
9699 				ire_refrele(ire);
9700 			return;
9701 		}
9702 	}
9703 	/*
9704 	 * At this point we will have ire only if RTF_BLACKHOLE
9705 	 * or RTF_REJECT flags are set on the IRE. It will not
9706 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9707 	 */
9708 	if (ire != NULL) {
9709 		if (ire->ire_flags & RTF_BLACKHOLE) {
9710 			ire_refrele(ire);
9711 			freemsg(first_mp);
9712 			return;
9713 		}
9714 		ire_refrele(ire);
9715 	}
9716 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9717 }
9718 
9719 /* Name/Value Table Lookup Routine */
9720 char *
9721 ip_nv_lookup(nv_t *nv, int value)
9722 {
9723 	if (!nv)
9724 		return (NULL);
9725 	for (; nv->nv_name; nv++) {
9726 		if (nv->nv_value == value)
9727 			return (nv->nv_name);
9728 	}
9729 	return ("unknown");
9730 }
9731 
9732 /*
9733  * This is a module open, i.e. this is a control stream for access
9734  * to a DLPI device.  We allocate an ill_t as the instance data in
9735  * this case.
9736  */
9737 int
9738 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9739 {
9740 	ill_t	*ill;
9741 	int	err;
9742 	zoneid_t zoneid;
9743 	netstack_t *ns;
9744 	ip_stack_t *ipst;
9745 
9746 	/*
9747 	 * Prevent unprivileged processes from pushing IP so that
9748 	 * they can't send raw IP.
9749 	 */
9750 	if (secpolicy_net_rawaccess(credp) != 0)
9751 		return (EPERM);
9752 
9753 	ns = netstack_find_by_cred(credp);
9754 	ASSERT(ns != NULL);
9755 	ipst = ns->netstack_ip;
9756 	ASSERT(ipst != NULL);
9757 
9758 	/*
9759 	 * For exclusive stacks we set the zoneid to zero
9760 	 * to make IP operate as if in the global zone.
9761 	 */
9762 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9763 		zoneid = GLOBAL_ZONEID;
9764 	else
9765 		zoneid = crgetzoneid(credp);
9766 
9767 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9768 	q->q_ptr = WR(q)->q_ptr = ill;
9769 	ill->ill_ipst = ipst;
9770 	ill->ill_zoneid = zoneid;
9771 
9772 	/*
9773 	 * ill_init initializes the ill fields and then sends down
9774 	 * down a DL_INFO_REQ after calling qprocson.
9775 	 */
9776 	err = ill_init(q, ill);
9777 	if (err != 0) {
9778 		mi_free(ill);
9779 		netstack_rele(ipst->ips_netstack);
9780 		q->q_ptr = NULL;
9781 		WR(q)->q_ptr = NULL;
9782 		return (err);
9783 	}
9784 
9785 	/* ill_init initializes the ipsq marking this thread as writer */
9786 	ipsq_exit(ill->ill_phyint->phyint_ipsq);
9787 	/* Wait for the DL_INFO_ACK */
9788 	mutex_enter(&ill->ill_lock);
9789 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9790 		/*
9791 		 * Return value of 0 indicates a pending signal.
9792 		 */
9793 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9794 		if (err == 0) {
9795 			mutex_exit(&ill->ill_lock);
9796 			(void) ip_close(q, 0);
9797 			return (EINTR);
9798 		}
9799 	}
9800 	mutex_exit(&ill->ill_lock);
9801 
9802 	/*
9803 	 * ip_rput_other could have set an error  in ill_error on
9804 	 * receipt of M_ERROR.
9805 	 */
9806 
9807 	err = ill->ill_error;
9808 	if (err != 0) {
9809 		(void) ip_close(q, 0);
9810 		return (err);
9811 	}
9812 
9813 	ill->ill_credp = credp;
9814 	crhold(credp);
9815 
9816 	mutex_enter(&ipst->ips_ip_mi_lock);
9817 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
9818 	    credp);
9819 	mutex_exit(&ipst->ips_ip_mi_lock);
9820 	if (err) {
9821 		(void) ip_close(q, 0);
9822 		return (err);
9823 	}
9824 	return (0);
9825 }
9826 
9827 /* For /dev/ip aka AF_INET open */
9828 int
9829 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9830 {
9831 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
9832 }
9833 
9834 /* For /dev/ip6 aka AF_INET6 open */
9835 int
9836 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9837 {
9838 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
9839 }
9840 
9841 /* IP open routine. */
9842 int
9843 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9844     boolean_t isv6)
9845 {
9846 	conn_t 		*connp;
9847 	major_t		maj;
9848 	zoneid_t	zoneid;
9849 	netstack_t	*ns;
9850 	ip_stack_t	*ipst;
9851 
9852 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9853 
9854 	/* Allow reopen. */
9855 	if (q->q_ptr != NULL)
9856 		return (0);
9857 
9858 	if (sflag & MODOPEN) {
9859 		/* This is a module open */
9860 		return (ip_modopen(q, devp, flag, sflag, credp));
9861 	}
9862 
9863 	if ((flag & ~(FKLYR)) == IP_HELPER_STR) {
9864 		/*
9865 		 * Non streams based socket looking for a stream
9866 		 * to access IP
9867 		 */
9868 		return (ip_helper_stream_setup(q, devp, flag, sflag,
9869 		    credp, isv6));
9870 	}
9871 
9872 	ns = netstack_find_by_cred(credp);
9873 	ASSERT(ns != NULL);
9874 	ipst = ns->netstack_ip;
9875 	ASSERT(ipst != NULL);
9876 
9877 	/*
9878 	 * For exclusive stacks we set the zoneid to zero
9879 	 * to make IP operate as if in the global zone.
9880 	 */
9881 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9882 		zoneid = GLOBAL_ZONEID;
9883 	else
9884 		zoneid = crgetzoneid(credp);
9885 
9886 	/*
9887 	 * We are opening as a device. This is an IP client stream, and we
9888 	 * allocate an conn_t as the instance data.
9889 	 */
9890 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
9891 
9892 	/*
9893 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
9894 	 * done by netstack_find_by_cred()
9895 	 */
9896 	netstack_rele(ipst->ips_netstack);
9897 
9898 	connp->conn_zoneid = zoneid;
9899 	connp->conn_sqp = NULL;
9900 	connp->conn_initial_sqp = NULL;
9901 	connp->conn_final_sqp = NULL;
9902 
9903 	connp->conn_upq = q;
9904 	q->q_ptr = WR(q)->q_ptr = connp;
9905 
9906 	if (flag & SO_SOCKSTR)
9907 		connp->conn_flags |= IPCL_SOCKET;
9908 
9909 	/* Minor tells us which /dev entry was opened */
9910 	if (isv6) {
9911 		connp->conn_flags |= IPCL_ISV6;
9912 		connp->conn_af_isv6 = B_TRUE;
9913 		ip_setpktversion(connp, isv6, B_FALSE, ipst);
9914 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9915 	} else {
9916 		connp->conn_af_isv6 = B_FALSE;
9917 		connp->conn_pkt_isv6 = B_FALSE;
9918 	}
9919 
9920 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9921 	    ((connp->conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9922 		connp->conn_minor_arena = ip_minor_arena_la;
9923 	} else {
9924 		/*
9925 		 * Either minor numbers in the large arena were exhausted
9926 		 * or a non socket application is doing the open.
9927 		 * Try to allocate from the small arena.
9928 		 */
9929 		if ((connp->conn_dev =
9930 		    inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9931 			/* CONN_DEC_REF takes care of netstack_rele() */
9932 			q->q_ptr = WR(q)->q_ptr = NULL;
9933 			CONN_DEC_REF(connp);
9934 			return (EBUSY);
9935 		}
9936 		connp->conn_minor_arena = ip_minor_arena_sa;
9937 	}
9938 
9939 	maj = getemajor(*devp);
9940 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9941 
9942 	/*
9943 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9944 	 */
9945 	connp->conn_cred = credp;
9946 
9947 	/*
9948 	 * Handle IP_RTS_REQUEST and other ioctls which use conn_recv
9949 	 */
9950 	connp->conn_recv = ip_conn_input;
9951 
9952 	crhold(connp->conn_cred);
9953 
9954 	/*
9955 	 * If the caller has the process-wide flag set, then default to MAC
9956 	 * exempt mode.  This allows read-down to unlabeled hosts.
9957 	 */
9958 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9959 		connp->conn_mac_exempt = B_TRUE;
9960 
9961 	connp->conn_rq = q;
9962 	connp->conn_wq = WR(q);
9963 
9964 	/* Non-zero default values */
9965 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9966 
9967 	/*
9968 	 * Make the conn globally visible to walkers
9969 	 */
9970 	ASSERT(connp->conn_ref == 1);
9971 	mutex_enter(&connp->conn_lock);
9972 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9973 	mutex_exit(&connp->conn_lock);
9974 
9975 	qprocson(q);
9976 
9977 	return (0);
9978 }
9979 
9980 /*
9981  * Change the output format (IPv4 vs. IPv6) for a conn_t.
9982  * Note that there is no race since either ip_output function works - it
9983  * is just an optimization to enter the best ip_output routine directly.
9984  */
9985 void
9986 ip_setpktversion(conn_t *connp, boolean_t isv6, boolean_t bump_mib,
9987     ip_stack_t *ipst)
9988 {
9989 	if (isv6)  {
9990 		if (bump_mib) {
9991 			BUMP_MIB(&ipst->ips_ip6_mib,
9992 			    ipIfStatsOutSwitchIPVersion);
9993 		}
9994 		connp->conn_send = ip_output_v6;
9995 		connp->conn_pkt_isv6 = B_TRUE;
9996 	} else {
9997 		if (bump_mib) {
9998 			BUMP_MIB(&ipst->ips_ip_mib,
9999 			    ipIfStatsOutSwitchIPVersion);
10000 		}
10001 		connp->conn_send = ip_output;
10002 		connp->conn_pkt_isv6 = B_FALSE;
10003 	}
10004 
10005 }
10006 
10007 /*
10008  * See if IPsec needs loading because of the options in mp.
10009  */
10010 static boolean_t
10011 ipsec_opt_present(mblk_t *mp)
10012 {
10013 	uint8_t *optcp, *next_optcp, *opt_endcp;
10014 	struct opthdr *opt;
10015 	struct T_opthdr *topt;
10016 	int opthdr_len;
10017 	t_uscalar_t optname, optlevel;
10018 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
10019 	ipsec_req_t *ipsr;
10020 
10021 	/*
10022 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
10023 	 * return TRUE.
10024 	 */
10025 
10026 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
10027 	opt_endcp = optcp + tor->OPT_length;
10028 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
10029 		opthdr_len = sizeof (struct T_opthdr);
10030 	} else {		/* O_OPTMGMT_REQ */
10031 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
10032 		opthdr_len = sizeof (struct opthdr);
10033 	}
10034 	for (; optcp < opt_endcp; optcp = next_optcp) {
10035 		if (optcp + opthdr_len > opt_endcp)
10036 			return (B_FALSE);	/* Not enough option header. */
10037 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
10038 			topt = (struct T_opthdr *)optcp;
10039 			optlevel = topt->level;
10040 			optname = topt->name;
10041 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
10042 		} else {
10043 			opt = (struct opthdr *)optcp;
10044 			optlevel = opt->level;
10045 			optname = opt->name;
10046 			next_optcp = optcp + opthdr_len +
10047 			    _TPI_ALIGN_OPT(opt->len);
10048 		}
10049 		if ((next_optcp < optcp) || /* wraparound pointer space */
10050 		    ((next_optcp >= opt_endcp) && /* last option bad len */
10051 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
10052 			return (B_FALSE); /* bad option buffer */
10053 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
10054 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
10055 			/*
10056 			 * Check to see if it's an all-bypass or all-zeroes
10057 			 * IPsec request.  Don't bother loading IPsec if
10058 			 * the socket doesn't want to use it.  (A good example
10059 			 * is a bypass request.)
10060 			 *
10061 			 * Basically, if any of the non-NEVER bits are set,
10062 			 * load IPsec.
10063 			 */
10064 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
10065 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
10066 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
10067 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
10068 			    != 0)
10069 				return (B_TRUE);
10070 		}
10071 	}
10072 	return (B_FALSE);
10073 }
10074 
10075 /*
10076  * If conn is is waiting for ipsec to finish loading, kick it.
10077  */
10078 /* ARGSUSED */
10079 static void
10080 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
10081 {
10082 	t_scalar_t	optreq_prim;
10083 	mblk_t		*mp;
10084 	cred_t		*cr;
10085 	int		err = 0;
10086 
10087 	/*
10088 	 * This function is called, after ipsec loading is complete.
10089 	 * Since IP checks exclusively and atomically (i.e it prevents
10090 	 * ipsec load from completing until ip_optcom_req completes)
10091 	 * whether ipsec load is complete, there cannot be a race with IP
10092 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
10093 	 */
10094 	mutex_enter(&connp->conn_lock);
10095 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
10096 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
10097 		mp = connp->conn_ipsec_opt_mp;
10098 		connp->conn_ipsec_opt_mp = NULL;
10099 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
10100 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
10101 		mutex_exit(&connp->conn_lock);
10102 
10103 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
10104 
10105 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
10106 		if (optreq_prim == T_OPTMGMT_REQ) {
10107 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10108 			    &ip_opt_obj, B_FALSE);
10109 		} else {
10110 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
10111 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10112 			    &ip_opt_obj, B_FALSE);
10113 		}
10114 		if (err != EINPROGRESS)
10115 			CONN_OPER_PENDING_DONE(connp);
10116 		return;
10117 	}
10118 	mutex_exit(&connp->conn_lock);
10119 }
10120 
10121 /*
10122  * Called from the ipsec_loader thread, outside any perimeter, to tell
10123  * ip qenable any of the queues waiting for the ipsec loader to
10124  * complete.
10125  */
10126 void
10127 ip_ipsec_load_complete(ipsec_stack_t *ipss)
10128 {
10129 	netstack_t *ns = ipss->ipsec_netstack;
10130 
10131 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
10132 }
10133 
10134 /*
10135  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10136  * determines the grp on which it has to become exclusive, queues the mp
10137  * and sq draining restarts the optmgmt
10138  */
10139 static boolean_t
10140 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10141 {
10142 	conn_t *connp = Q_TO_CONN(q);
10143 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
10144 
10145 	/*
10146 	 * Take IPsec requests and treat them special.
10147 	 */
10148 	if (ipsec_opt_present(mp)) {
10149 		/* First check if IPsec is loaded. */
10150 		mutex_enter(&ipss->ipsec_loader_lock);
10151 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
10152 			mutex_exit(&ipss->ipsec_loader_lock);
10153 			return (B_FALSE);
10154 		}
10155 		mutex_enter(&connp->conn_lock);
10156 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10157 
10158 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10159 		connp->conn_ipsec_opt_mp = mp;
10160 		mutex_exit(&connp->conn_lock);
10161 		mutex_exit(&ipss->ipsec_loader_lock);
10162 
10163 		ipsec_loader_loadnow(ipss);
10164 		return (B_TRUE);
10165 	}
10166 	return (B_FALSE);
10167 }
10168 
10169 /*
10170  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10171  * all of them are copied to the conn_t. If the req is "zero", the policy is
10172  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10173  * fields.
10174  * We keep only the latest setting of the policy and thus policy setting
10175  * is not incremental/cumulative.
10176  *
10177  * Requests to set policies with multiple alternative actions will
10178  * go through a different API.
10179  */
10180 int
10181 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10182 {
10183 	uint_t ah_req = 0;
10184 	uint_t esp_req = 0;
10185 	uint_t se_req = 0;
10186 	ipsec_selkey_t sel;
10187 	ipsec_act_t *actp = NULL;
10188 	uint_t nact;
10189 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
10190 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
10191 	ipsec_policy_root_t *pr;
10192 	ipsec_policy_head_t *ph;
10193 	int fam;
10194 	boolean_t is_pol_reset;
10195 	int error = 0;
10196 	netstack_t	*ns = connp->conn_netstack;
10197 	ip_stack_t	*ipst = ns->netstack_ip;
10198 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10199 
10200 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10201 
10202 	/*
10203 	 * The IP_SEC_OPT option does not allow variable length parameters,
10204 	 * hence a request cannot be NULL.
10205 	 */
10206 	if (req == NULL)
10207 		return (EINVAL);
10208 
10209 	ah_req = req->ipsr_ah_req;
10210 	esp_req = req->ipsr_esp_req;
10211 	se_req = req->ipsr_self_encap_req;
10212 
10213 	/* Don't allow setting self-encap without one or more of AH/ESP. */
10214 	if (se_req != 0 && esp_req == 0 && ah_req == 0)
10215 		return (EINVAL);
10216 
10217 	/*
10218 	 * Are we dealing with a request to reset the policy (i.e.
10219 	 * zero requests).
10220 	 */
10221 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10222 	    (esp_req & REQ_MASK) == 0 &&
10223 	    (se_req & REQ_MASK) == 0);
10224 
10225 	if (!is_pol_reset) {
10226 		/*
10227 		 * If we couldn't load IPsec, fail with "protocol
10228 		 * not supported".
10229 		 * IPsec may not have been loaded for a request with zero
10230 		 * policies, so we don't fail in this case.
10231 		 */
10232 		mutex_enter(&ipss->ipsec_loader_lock);
10233 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10234 			mutex_exit(&ipss->ipsec_loader_lock);
10235 			return (EPROTONOSUPPORT);
10236 		}
10237 		mutex_exit(&ipss->ipsec_loader_lock);
10238 
10239 		/*
10240 		 * Test for valid requests. Invalid algorithms
10241 		 * need to be tested by IPsec code because new
10242 		 * algorithms can be added dynamically.
10243 		 */
10244 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10245 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10246 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10247 			return (EINVAL);
10248 		}
10249 
10250 		/*
10251 		 * Only privileged users can issue these
10252 		 * requests.
10253 		 */
10254 		if (((ah_req & IPSEC_PREF_NEVER) ||
10255 		    (esp_req & IPSEC_PREF_NEVER) ||
10256 		    (se_req & IPSEC_PREF_NEVER)) &&
10257 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10258 			return (EPERM);
10259 		}
10260 
10261 		/*
10262 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10263 		 * are mutually exclusive.
10264 		 */
10265 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10266 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10267 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10268 			/* Both of them are set */
10269 			return (EINVAL);
10270 		}
10271 	}
10272 
10273 	mutex_enter(&connp->conn_lock);
10274 
10275 	/*
10276 	 * If we have already cached policies in ip_bind_connected*(), don't
10277 	 * let them change now. We cache policies for connections
10278 	 * whose src,dst [addr, port] is known.
10279 	 */
10280 	if (connp->conn_policy_cached) {
10281 		mutex_exit(&connp->conn_lock);
10282 		return (EINVAL);
10283 	}
10284 
10285 	/*
10286 	 * We have a zero policies, reset the connection policy if already
10287 	 * set. This will cause the connection to inherit the
10288 	 * global policy, if any.
10289 	 */
10290 	if (is_pol_reset) {
10291 		if (connp->conn_policy != NULL) {
10292 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10293 			connp->conn_policy = NULL;
10294 		}
10295 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10296 		connp->conn_in_enforce_policy = B_FALSE;
10297 		connp->conn_out_enforce_policy = B_FALSE;
10298 		mutex_exit(&connp->conn_lock);
10299 		return (0);
10300 	}
10301 
10302 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10303 	    ipst->ips_netstack);
10304 	if (ph == NULL)
10305 		goto enomem;
10306 
10307 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10308 	if (actp == NULL)
10309 		goto enomem;
10310 
10311 	/*
10312 	 * Always allocate IPv4 policy entries, since they can also
10313 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10314 	 */
10315 	bzero(&sel, sizeof (sel));
10316 	sel.ipsl_valid = IPSL_IPV4;
10317 
10318 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10319 	    ipst->ips_netstack);
10320 	if (pin4 == NULL)
10321 		goto enomem;
10322 
10323 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10324 	    ipst->ips_netstack);
10325 	if (pout4 == NULL)
10326 		goto enomem;
10327 
10328 	if (connp->conn_af_isv6) {
10329 		/*
10330 		 * We're looking at a v6 socket, also allocate the
10331 		 * v6-specific entries...
10332 		 */
10333 		sel.ipsl_valid = IPSL_IPV6;
10334 		pin6 = ipsec_policy_create(&sel, actp, nact,
10335 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10336 		if (pin6 == NULL)
10337 			goto enomem;
10338 
10339 		pout6 = ipsec_policy_create(&sel, actp, nact,
10340 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10341 		if (pout6 == NULL)
10342 			goto enomem;
10343 
10344 		/*
10345 		 * .. and file them away in the right place.
10346 		 */
10347 		fam = IPSEC_AF_V6;
10348 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10349 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10350 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10351 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10352 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10353 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10354 	}
10355 
10356 	ipsec_actvec_free(actp, nact);
10357 
10358 	/*
10359 	 * File the v4 policies.
10360 	 */
10361 	fam = IPSEC_AF_V4;
10362 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10363 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10364 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10365 
10366 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10367 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10368 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10369 
10370 	/*
10371 	 * If the requests need security, set enforce_policy.
10372 	 * If the requests are IPSEC_PREF_NEVER, one should
10373 	 * still set conn_out_enforce_policy so that an ipsec_out
10374 	 * gets attached in ip_wput. This is needed so that
10375 	 * for connections that we don't cache policy in ip_bind,
10376 	 * if global policy matches in ip_wput_attach_policy, we
10377 	 * don't wrongly inherit global policy. Similarly, we need
10378 	 * to set conn_in_enforce_policy also so that we don't verify
10379 	 * policy wrongly.
10380 	 */
10381 	if ((ah_req & REQ_MASK) != 0 ||
10382 	    (esp_req & REQ_MASK) != 0 ||
10383 	    (se_req & REQ_MASK) != 0) {
10384 		connp->conn_in_enforce_policy = B_TRUE;
10385 		connp->conn_out_enforce_policy = B_TRUE;
10386 		connp->conn_flags |= IPCL_CHECK_POLICY;
10387 	}
10388 
10389 	mutex_exit(&connp->conn_lock);
10390 	return (error);
10391 #undef REQ_MASK
10392 
10393 	/*
10394 	 * Common memory-allocation-failure exit path.
10395 	 */
10396 enomem:
10397 	mutex_exit(&connp->conn_lock);
10398 	if (actp != NULL)
10399 		ipsec_actvec_free(actp, nact);
10400 	if (pin4 != NULL)
10401 		IPPOL_REFRELE(pin4, ipst->ips_netstack);
10402 	if (pout4 != NULL)
10403 		IPPOL_REFRELE(pout4, ipst->ips_netstack);
10404 	if (pin6 != NULL)
10405 		IPPOL_REFRELE(pin6, ipst->ips_netstack);
10406 	if (pout6 != NULL)
10407 		IPPOL_REFRELE(pout6, ipst->ips_netstack);
10408 	return (ENOMEM);
10409 }
10410 
10411 /*
10412  * Only for options that pass in an IP addr. Currently only V4 options
10413  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10414  * So this function assumes level is IPPROTO_IP
10415  */
10416 int
10417 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10418     mblk_t *first_mp)
10419 {
10420 	ipif_t *ipif = NULL;
10421 	int error;
10422 	ill_t *ill;
10423 	int zoneid;
10424 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10425 
10426 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10427 
10428 	if (addr != INADDR_ANY || checkonly) {
10429 		ASSERT(connp != NULL);
10430 		zoneid = IPCL_ZONEID(connp);
10431 		if (option == IP_NEXTHOP) {
10432 			ipif = ipif_lookup_onlink_addr(addr,
10433 			    connp->conn_zoneid, ipst);
10434 		} else {
10435 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10436 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10437 			    &error, ipst);
10438 		}
10439 		if (ipif == NULL) {
10440 			if (error == EINPROGRESS)
10441 				return (error);
10442 			if ((option == IP_MULTICAST_IF) ||
10443 			    (option == IP_NEXTHOP))
10444 				return (EHOSTUNREACH);
10445 			else
10446 				return (EINVAL);
10447 		} else if (checkonly) {
10448 			if (option == IP_MULTICAST_IF) {
10449 				ill = ipif->ipif_ill;
10450 				/* not supported by the virtual network iface */
10451 				if (IS_VNI(ill)) {
10452 					ipif_refrele(ipif);
10453 					return (EINVAL);
10454 				}
10455 			}
10456 			ipif_refrele(ipif);
10457 			return (0);
10458 		}
10459 		ill = ipif->ipif_ill;
10460 		mutex_enter(&connp->conn_lock);
10461 		mutex_enter(&ill->ill_lock);
10462 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10463 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10464 			mutex_exit(&ill->ill_lock);
10465 			mutex_exit(&connp->conn_lock);
10466 			ipif_refrele(ipif);
10467 			return (option == IP_MULTICAST_IF ?
10468 			    EHOSTUNREACH : EINVAL);
10469 		}
10470 	} else {
10471 		mutex_enter(&connp->conn_lock);
10472 	}
10473 
10474 	/* None of the options below are supported on the VNI */
10475 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10476 		mutex_exit(&ill->ill_lock);
10477 		mutex_exit(&connp->conn_lock);
10478 		ipif_refrele(ipif);
10479 		return (EINVAL);
10480 	}
10481 
10482 	switch (option) {
10483 	case IP_DONTFAILOVER_IF:
10484 		/*
10485 		 * This option is used by in.mpathd to ensure
10486 		 * that IPMP probe packets only go out on the
10487 		 * test interfaces. in.mpathd sets this option
10488 		 * on the non-failover interfaces.
10489 		 * For backward compatibility, this option
10490 		 * implicitly sets IP_MULTICAST_IF, as used
10491 		 * be done in bind(), so that ip_wput gets
10492 		 * this ipif to send mcast packets.
10493 		 */
10494 		if (ipif != NULL) {
10495 			ASSERT(addr != INADDR_ANY);
10496 			connp->conn_nofailover_ill = ipif->ipif_ill;
10497 			connp->conn_multicast_ipif = ipif;
10498 		} else {
10499 			ASSERT(addr == INADDR_ANY);
10500 			connp->conn_nofailover_ill = NULL;
10501 			connp->conn_multicast_ipif = NULL;
10502 		}
10503 		break;
10504 
10505 	case IP_MULTICAST_IF:
10506 		connp->conn_multicast_ipif = ipif;
10507 		break;
10508 	case IP_NEXTHOP:
10509 		connp->conn_nexthop_v4 = addr;
10510 		connp->conn_nexthop_set = B_TRUE;
10511 		break;
10512 	}
10513 
10514 	if (ipif != NULL) {
10515 		mutex_exit(&ill->ill_lock);
10516 		mutex_exit(&connp->conn_lock);
10517 		ipif_refrele(ipif);
10518 		return (0);
10519 	}
10520 	mutex_exit(&connp->conn_lock);
10521 	/* We succeded in cleared the option */
10522 	return (0);
10523 }
10524 
10525 /*
10526  * For options that pass in an ifindex specifying the ill. V6 options always
10527  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10528  */
10529 int
10530 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10531     int level, int option, mblk_t *first_mp)
10532 {
10533 	ill_t *ill = NULL;
10534 	int error = 0;
10535 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10536 
10537 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10538 	if (ifindex != 0) {
10539 		ASSERT(connp != NULL);
10540 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10541 		    first_mp, ip_restart_optmgmt, &error, ipst);
10542 		if (ill != NULL) {
10543 			if (checkonly) {
10544 				/* not supported by the virtual network iface */
10545 				if (IS_VNI(ill)) {
10546 					ill_refrele(ill);
10547 					return (EINVAL);
10548 				}
10549 				ill_refrele(ill);
10550 				return (0);
10551 			}
10552 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
10553 			    0, NULL)) {
10554 				ill_refrele(ill);
10555 				ill = NULL;
10556 				mutex_enter(&connp->conn_lock);
10557 				goto setit;
10558 			}
10559 			mutex_enter(&connp->conn_lock);
10560 			mutex_enter(&ill->ill_lock);
10561 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10562 				mutex_exit(&ill->ill_lock);
10563 				mutex_exit(&connp->conn_lock);
10564 				ill_refrele(ill);
10565 				ill = NULL;
10566 				mutex_enter(&connp->conn_lock);
10567 			}
10568 			goto setit;
10569 		} else if (error == EINPROGRESS) {
10570 			return (error);
10571 		} else {
10572 			error = 0;
10573 		}
10574 	}
10575 	mutex_enter(&connp->conn_lock);
10576 setit:
10577 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10578 
10579 	/*
10580 	 * The options below assume that the ILL (if any) transmits and/or
10581 	 * receives traffic. Neither of which is true for the virtual network
10582 	 * interface, so fail setting these on a VNI.
10583 	 */
10584 	if (IS_VNI(ill)) {
10585 		ASSERT(ill != NULL);
10586 		mutex_exit(&ill->ill_lock);
10587 		mutex_exit(&connp->conn_lock);
10588 		ill_refrele(ill);
10589 		return (EINVAL);
10590 	}
10591 
10592 	if (level == IPPROTO_IP) {
10593 		switch (option) {
10594 		case IP_BOUND_IF:
10595 			connp->conn_incoming_ill = ill;
10596 			connp->conn_outgoing_ill = ill;
10597 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10598 			    0 : ifindex;
10599 			break;
10600 
10601 		case IP_MULTICAST_IF:
10602 			/*
10603 			 * This option is an internal special. The socket
10604 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10605 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10606 			 * specifies an ifindex and we try first on V6 ill's.
10607 			 * If we don't find one, we they try using on v4 ill's
10608 			 * intenally and we come here.
10609 			 */
10610 			if (!checkonly && ill != NULL) {
10611 				ipif_t	*ipif;
10612 				ipif = ill->ill_ipif;
10613 
10614 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10615 					mutex_exit(&ill->ill_lock);
10616 					mutex_exit(&connp->conn_lock);
10617 					ill_refrele(ill);
10618 					ill = NULL;
10619 					mutex_enter(&connp->conn_lock);
10620 				} else {
10621 					connp->conn_multicast_ipif = ipif;
10622 				}
10623 			}
10624 			break;
10625 
10626 		case IP_DHCPINIT_IF:
10627 			if (connp->conn_dhcpinit_ill != NULL) {
10628 				/*
10629 				 * We've locked the conn so conn_cleanup_ill()
10630 				 * cannot clear conn_dhcpinit_ill -- so it's
10631 				 * safe to access the ill.
10632 				 */
10633 				ill_t *oill = connp->conn_dhcpinit_ill;
10634 
10635 				ASSERT(oill->ill_dhcpinit != 0);
10636 				atomic_dec_32(&oill->ill_dhcpinit);
10637 				connp->conn_dhcpinit_ill = NULL;
10638 			}
10639 
10640 			if (ill != NULL) {
10641 				connp->conn_dhcpinit_ill = ill;
10642 				atomic_inc_32(&ill->ill_dhcpinit);
10643 			}
10644 			break;
10645 		}
10646 	} else {
10647 		switch (option) {
10648 		case IPV6_BOUND_IF:
10649 			connp->conn_incoming_ill = ill;
10650 			connp->conn_outgoing_ill = ill;
10651 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10652 			    0 : ifindex;
10653 			break;
10654 
10655 		case IPV6_BOUND_PIF:
10656 			/*
10657 			 * Limit all transmit to this ill.
10658 			 * Unlike IPV6_BOUND_IF, using this option
10659 			 * prevents load spreading and failover from
10660 			 * happening when the interface is part of the
10661 			 * group. That's why we don't need to remember
10662 			 * the ifindex in orig_bound_ifindex as in
10663 			 * IPV6_BOUND_IF.
10664 			 */
10665 			connp->conn_outgoing_pill = ill;
10666 			break;
10667 
10668 		case IPV6_DONTFAILOVER_IF:
10669 			/*
10670 			 * This option is used by in.mpathd to ensure
10671 			 * that IPMP probe packets only go out on the
10672 			 * test interfaces. in.mpathd sets this option
10673 			 * on the non-failover interfaces.
10674 			 */
10675 			connp->conn_nofailover_ill = ill;
10676 			/*
10677 			 * For backward compatibility, this option
10678 			 * implicitly sets ip_multicast_ill as used in
10679 			 * IPV6_MULTICAST_IF so that ip_wput gets
10680 			 * this ill to send mcast packets.
10681 			 */
10682 			connp->conn_multicast_ill = ill;
10683 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
10684 			    0 : ifindex;
10685 			break;
10686 
10687 		case IPV6_MULTICAST_IF:
10688 			/*
10689 			 * Set conn_multicast_ill to be the IPv6 ill.
10690 			 * Set conn_multicast_ipif to be an IPv4 ipif
10691 			 * for ifindex to make IPv4 mapped addresses
10692 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10693 			 * Even if no IPv6 ill exists for the ifindex
10694 			 * we need to check for an IPv4 ifindex in order
10695 			 * for this to work with mapped addresses. In that
10696 			 * case only set conn_multicast_ipif.
10697 			 */
10698 			if (!checkonly) {
10699 				if (ifindex == 0) {
10700 					connp->conn_multicast_ill = NULL;
10701 					connp->conn_orig_multicast_ifindex = 0;
10702 					connp->conn_multicast_ipif = NULL;
10703 				} else if (ill != NULL) {
10704 					connp->conn_multicast_ill = ill;
10705 					connp->conn_orig_multicast_ifindex =
10706 					    ifindex;
10707 				}
10708 			}
10709 			break;
10710 		}
10711 	}
10712 
10713 	if (ill != NULL) {
10714 		mutex_exit(&ill->ill_lock);
10715 		mutex_exit(&connp->conn_lock);
10716 		ill_refrele(ill);
10717 		return (0);
10718 	}
10719 	mutex_exit(&connp->conn_lock);
10720 	/*
10721 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10722 	 * locate the ill and could not set the option (ifindex != 0)
10723 	 */
10724 	return (ifindex == 0 ? 0 : EINVAL);
10725 }
10726 
10727 /* This routine sets socket options. */
10728 /* ARGSUSED */
10729 int
10730 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10731     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10732     void *dummy, cred_t *cr, mblk_t *first_mp)
10733 {
10734 	int		*i1 = (int *)invalp;
10735 	conn_t		*connp = Q_TO_CONN(q);
10736 	int		error = 0;
10737 	boolean_t	checkonly;
10738 	ire_t		*ire;
10739 	boolean_t	found;
10740 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10741 
10742 	switch (optset_context) {
10743 
10744 	case SETFN_OPTCOM_CHECKONLY:
10745 		checkonly = B_TRUE;
10746 		/*
10747 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10748 		 * inlen != 0 implies value supplied and
10749 		 * 	we have to "pretend" to set it.
10750 		 * inlen == 0 implies that there is no
10751 		 * 	value part in T_CHECK request and just validation
10752 		 * done elsewhere should be enough, we just return here.
10753 		 */
10754 		if (inlen == 0) {
10755 			*outlenp = 0;
10756 			return (0);
10757 		}
10758 		break;
10759 	case SETFN_OPTCOM_NEGOTIATE:
10760 	case SETFN_UD_NEGOTIATE:
10761 	case SETFN_CONN_NEGOTIATE:
10762 		checkonly = B_FALSE;
10763 		break;
10764 	default:
10765 		/*
10766 		 * We should never get here
10767 		 */
10768 		*outlenp = 0;
10769 		return (EINVAL);
10770 	}
10771 
10772 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10773 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10774 
10775 	/*
10776 	 * For fixed length options, no sanity check
10777 	 * of passed in length is done. It is assumed *_optcom_req()
10778 	 * routines do the right thing.
10779 	 */
10780 
10781 	switch (level) {
10782 	case SOL_SOCKET:
10783 		/*
10784 		 * conn_lock protects the bitfields, and is used to
10785 		 * set the fields atomically.
10786 		 */
10787 		switch (name) {
10788 		case SO_BROADCAST:
10789 			if (!checkonly) {
10790 				/* TODO: use value someplace? */
10791 				mutex_enter(&connp->conn_lock);
10792 				connp->conn_broadcast = *i1 ? 1 : 0;
10793 				mutex_exit(&connp->conn_lock);
10794 			}
10795 			break;	/* goto sizeof (int) option return */
10796 		case SO_USELOOPBACK:
10797 			if (!checkonly) {
10798 				/* TODO: use value someplace? */
10799 				mutex_enter(&connp->conn_lock);
10800 				connp->conn_loopback = *i1 ? 1 : 0;
10801 				mutex_exit(&connp->conn_lock);
10802 			}
10803 			break;	/* goto sizeof (int) option return */
10804 		case SO_DONTROUTE:
10805 			if (!checkonly) {
10806 				mutex_enter(&connp->conn_lock);
10807 				connp->conn_dontroute = *i1 ? 1 : 0;
10808 				mutex_exit(&connp->conn_lock);
10809 			}
10810 			break;	/* goto sizeof (int) option return */
10811 		case SO_REUSEADDR:
10812 			if (!checkonly) {
10813 				mutex_enter(&connp->conn_lock);
10814 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10815 				mutex_exit(&connp->conn_lock);
10816 			}
10817 			break;	/* goto sizeof (int) option return */
10818 		case SO_PROTOTYPE:
10819 			if (!checkonly) {
10820 				mutex_enter(&connp->conn_lock);
10821 				connp->conn_proto = *i1;
10822 				mutex_exit(&connp->conn_lock);
10823 			}
10824 			break;	/* goto sizeof (int) option return */
10825 		case SO_ALLZONES:
10826 			if (!checkonly) {
10827 				mutex_enter(&connp->conn_lock);
10828 				if (IPCL_IS_BOUND(connp)) {
10829 					mutex_exit(&connp->conn_lock);
10830 					return (EINVAL);
10831 				}
10832 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10833 				mutex_exit(&connp->conn_lock);
10834 			}
10835 			break;	/* goto sizeof (int) option return */
10836 		case SO_ANON_MLP:
10837 			if (!checkonly) {
10838 				mutex_enter(&connp->conn_lock);
10839 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10840 				mutex_exit(&connp->conn_lock);
10841 			}
10842 			break;	/* goto sizeof (int) option return */
10843 		case SO_MAC_EXEMPT:
10844 			if (secpolicy_net_mac_aware(cr) != 0 ||
10845 			    IPCL_IS_BOUND(connp))
10846 				return (EACCES);
10847 			if (!checkonly) {
10848 				mutex_enter(&connp->conn_lock);
10849 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10850 				mutex_exit(&connp->conn_lock);
10851 			}
10852 			break;	/* goto sizeof (int) option return */
10853 		default:
10854 			/*
10855 			 * "soft" error (negative)
10856 			 * option not handled at this level
10857 			 * Note: Do not modify *outlenp
10858 			 */
10859 			return (-EINVAL);
10860 		}
10861 		break;
10862 	case IPPROTO_IP:
10863 		switch (name) {
10864 		case IP_NEXTHOP:
10865 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
10866 				return (EPERM);
10867 			/* FALLTHRU */
10868 		case IP_MULTICAST_IF:
10869 		case IP_DONTFAILOVER_IF: {
10870 			ipaddr_t addr = *i1;
10871 
10872 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10873 			    first_mp);
10874 			if (error != 0)
10875 				return (error);
10876 			break;	/* goto sizeof (int) option return */
10877 		}
10878 
10879 		case IP_MULTICAST_TTL:
10880 			/* Recorded in transport above IP */
10881 			*outvalp = *invalp;
10882 			*outlenp = sizeof (uchar_t);
10883 			return (0);
10884 		case IP_MULTICAST_LOOP:
10885 			if (!checkonly) {
10886 				mutex_enter(&connp->conn_lock);
10887 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10888 				mutex_exit(&connp->conn_lock);
10889 			}
10890 			*outvalp = *invalp;
10891 			*outlenp = sizeof (uchar_t);
10892 			return (0);
10893 		case IP_ADD_MEMBERSHIP:
10894 		case MCAST_JOIN_GROUP:
10895 		case IP_DROP_MEMBERSHIP:
10896 		case MCAST_LEAVE_GROUP: {
10897 			struct ip_mreq *mreqp;
10898 			struct group_req *greqp;
10899 			ire_t *ire;
10900 			boolean_t done = B_FALSE;
10901 			ipaddr_t group, ifaddr;
10902 			struct sockaddr_in *sin;
10903 			uint32_t *ifindexp;
10904 			boolean_t mcast_opt = B_TRUE;
10905 			mcast_record_t fmode;
10906 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10907 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10908 
10909 			switch (name) {
10910 			case IP_ADD_MEMBERSHIP:
10911 				mcast_opt = B_FALSE;
10912 				/* FALLTHRU */
10913 			case MCAST_JOIN_GROUP:
10914 				fmode = MODE_IS_EXCLUDE;
10915 				optfn = ip_opt_add_group;
10916 				break;
10917 
10918 			case IP_DROP_MEMBERSHIP:
10919 				mcast_opt = B_FALSE;
10920 				/* FALLTHRU */
10921 			case MCAST_LEAVE_GROUP:
10922 				fmode = MODE_IS_INCLUDE;
10923 				optfn = ip_opt_delete_group;
10924 				break;
10925 			}
10926 
10927 			if (mcast_opt) {
10928 				greqp = (struct group_req *)i1;
10929 				sin = (struct sockaddr_in *)&greqp->gr_group;
10930 				if (sin->sin_family != AF_INET) {
10931 					*outlenp = 0;
10932 					return (ENOPROTOOPT);
10933 				}
10934 				group = (ipaddr_t)sin->sin_addr.s_addr;
10935 				ifaddr = INADDR_ANY;
10936 				ifindexp = &greqp->gr_interface;
10937 			} else {
10938 				mreqp = (struct ip_mreq *)i1;
10939 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10940 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10941 				ifindexp = NULL;
10942 			}
10943 
10944 			/*
10945 			 * In the multirouting case, we need to replicate
10946 			 * the request on all interfaces that will take part
10947 			 * in replication.  We do so because multirouting is
10948 			 * reflective, thus we will probably receive multi-
10949 			 * casts on those interfaces.
10950 			 * The ip_multirt_apply_membership() succeeds if the
10951 			 * operation succeeds on at least one interface.
10952 			 */
10953 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10954 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10955 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10956 			if (ire != NULL) {
10957 				if (ire->ire_flags & RTF_MULTIRT) {
10958 					error = ip_multirt_apply_membership(
10959 					    optfn, ire, connp, checkonly, group,
10960 					    fmode, INADDR_ANY, first_mp);
10961 					done = B_TRUE;
10962 				}
10963 				ire_refrele(ire);
10964 			}
10965 			if (!done) {
10966 				error = optfn(connp, checkonly, group, ifaddr,
10967 				    ifindexp, fmode, INADDR_ANY, first_mp);
10968 			}
10969 			if (error) {
10970 				/*
10971 				 * EINPROGRESS is a soft error, needs retry
10972 				 * so don't make *outlenp zero.
10973 				 */
10974 				if (error != EINPROGRESS)
10975 					*outlenp = 0;
10976 				return (error);
10977 			}
10978 			/* OK return - copy input buffer into output buffer */
10979 			if (invalp != outvalp) {
10980 				/* don't trust bcopy for identical src/dst */
10981 				bcopy(invalp, outvalp, inlen);
10982 			}
10983 			*outlenp = inlen;
10984 			return (0);
10985 		}
10986 		case IP_BLOCK_SOURCE:
10987 		case IP_UNBLOCK_SOURCE:
10988 		case IP_ADD_SOURCE_MEMBERSHIP:
10989 		case IP_DROP_SOURCE_MEMBERSHIP:
10990 		case MCAST_BLOCK_SOURCE:
10991 		case MCAST_UNBLOCK_SOURCE:
10992 		case MCAST_JOIN_SOURCE_GROUP:
10993 		case MCAST_LEAVE_SOURCE_GROUP: {
10994 			struct ip_mreq_source *imreqp;
10995 			struct group_source_req *gsreqp;
10996 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10997 			uint32_t ifindex = 0;
10998 			mcast_record_t fmode;
10999 			struct sockaddr_in *sin;
11000 			ire_t *ire;
11001 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
11002 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
11003 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
11004 
11005 			switch (name) {
11006 			case IP_BLOCK_SOURCE:
11007 				mcast_opt = B_FALSE;
11008 				/* FALLTHRU */
11009 			case MCAST_BLOCK_SOURCE:
11010 				fmode = MODE_IS_EXCLUDE;
11011 				optfn = ip_opt_add_group;
11012 				break;
11013 
11014 			case IP_UNBLOCK_SOURCE:
11015 				mcast_opt = B_FALSE;
11016 				/* FALLTHRU */
11017 			case MCAST_UNBLOCK_SOURCE:
11018 				fmode = MODE_IS_EXCLUDE;
11019 				optfn = ip_opt_delete_group;
11020 				break;
11021 
11022 			case IP_ADD_SOURCE_MEMBERSHIP:
11023 				mcast_opt = B_FALSE;
11024 				/* FALLTHRU */
11025 			case MCAST_JOIN_SOURCE_GROUP:
11026 				fmode = MODE_IS_INCLUDE;
11027 				optfn = ip_opt_add_group;
11028 				break;
11029 
11030 			case IP_DROP_SOURCE_MEMBERSHIP:
11031 				mcast_opt = B_FALSE;
11032 				/* FALLTHRU */
11033 			case MCAST_LEAVE_SOURCE_GROUP:
11034 				fmode = MODE_IS_INCLUDE;
11035 				optfn = ip_opt_delete_group;
11036 				break;
11037 			}
11038 
11039 			if (mcast_opt) {
11040 				gsreqp = (struct group_source_req *)i1;
11041 				if (gsreqp->gsr_group.ss_family != AF_INET) {
11042 					*outlenp = 0;
11043 					return (ENOPROTOOPT);
11044 				}
11045 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
11046 				grp = (ipaddr_t)sin->sin_addr.s_addr;
11047 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
11048 				src = (ipaddr_t)sin->sin_addr.s_addr;
11049 				ifindex = gsreqp->gsr_interface;
11050 			} else {
11051 				imreqp = (struct ip_mreq_source *)i1;
11052 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
11053 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
11054 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
11055 			}
11056 
11057 			/*
11058 			 * In the multirouting case, we need to replicate
11059 			 * the request as noted in the mcast cases above.
11060 			 */
11061 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
11062 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11063 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11064 			if (ire != NULL) {
11065 				if (ire->ire_flags & RTF_MULTIRT) {
11066 					error = ip_multirt_apply_membership(
11067 					    optfn, ire, connp, checkonly, grp,
11068 					    fmode, src, first_mp);
11069 					done = B_TRUE;
11070 				}
11071 				ire_refrele(ire);
11072 			}
11073 			if (!done) {
11074 				error = optfn(connp, checkonly, grp, ifaddr,
11075 				    &ifindex, fmode, src, first_mp);
11076 			}
11077 			if (error != 0) {
11078 				/*
11079 				 * EINPROGRESS is a soft error, needs retry
11080 				 * so don't make *outlenp zero.
11081 				 */
11082 				if (error != EINPROGRESS)
11083 					*outlenp = 0;
11084 				return (error);
11085 			}
11086 			/* OK return - copy input buffer into output buffer */
11087 			if (invalp != outvalp) {
11088 				bcopy(invalp, outvalp, inlen);
11089 			}
11090 			*outlenp = inlen;
11091 			return (0);
11092 		}
11093 		case IP_SEC_OPT:
11094 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11095 			if (error != 0) {
11096 				*outlenp = 0;
11097 				return (error);
11098 			}
11099 			break;
11100 		case IP_HDRINCL:
11101 		case IP_OPTIONS:
11102 		case T_IP_OPTIONS:
11103 		case IP_TOS:
11104 		case T_IP_TOS:
11105 		case IP_TTL:
11106 		case IP_RECVDSTADDR:
11107 		case IP_RECVOPTS:
11108 			/* OK return - copy input buffer into output buffer */
11109 			if (invalp != outvalp) {
11110 				/* don't trust bcopy for identical src/dst */
11111 				bcopy(invalp, outvalp, inlen);
11112 			}
11113 			*outlenp = inlen;
11114 			return (0);
11115 		case IP_RECVIF:
11116 			/* Retrieve the inbound interface index */
11117 			if (!checkonly) {
11118 				mutex_enter(&connp->conn_lock);
11119 				connp->conn_recvif = *i1 ? 1 : 0;
11120 				mutex_exit(&connp->conn_lock);
11121 			}
11122 			break;	/* goto sizeof (int) option return */
11123 		case IP_RECVPKTINFO:
11124 			if (!checkonly) {
11125 				mutex_enter(&connp->conn_lock);
11126 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11127 				mutex_exit(&connp->conn_lock);
11128 			}
11129 			break;	/* goto sizeof (int) option return */
11130 		case IP_RECVSLLA:
11131 			/* Retrieve the source link layer address */
11132 			if (!checkonly) {
11133 				mutex_enter(&connp->conn_lock);
11134 				connp->conn_recvslla = *i1 ? 1 : 0;
11135 				mutex_exit(&connp->conn_lock);
11136 			}
11137 			break;	/* goto sizeof (int) option return */
11138 		case MRT_INIT:
11139 		case MRT_DONE:
11140 		case MRT_ADD_VIF:
11141 		case MRT_DEL_VIF:
11142 		case MRT_ADD_MFC:
11143 		case MRT_DEL_MFC:
11144 		case MRT_ASSERT:
11145 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
11146 				*outlenp = 0;
11147 				return (error);
11148 			}
11149 			error = ip_mrouter_set((int)name, q, checkonly,
11150 			    (uchar_t *)invalp, inlen, first_mp);
11151 			if (error) {
11152 				*outlenp = 0;
11153 				return (error);
11154 			}
11155 			/* OK return - copy input buffer into output buffer */
11156 			if (invalp != outvalp) {
11157 				/* don't trust bcopy for identical src/dst */
11158 				bcopy(invalp, outvalp, inlen);
11159 			}
11160 			*outlenp = inlen;
11161 			return (0);
11162 		case IP_BOUND_IF:
11163 		case IP_DHCPINIT_IF:
11164 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11165 			    level, name, first_mp);
11166 			if (error != 0)
11167 				return (error);
11168 			break; 		/* goto sizeof (int) option return */
11169 
11170 		case IP_UNSPEC_SRC:
11171 			/* Allow sending with a zero source address */
11172 			if (!checkonly) {
11173 				mutex_enter(&connp->conn_lock);
11174 				connp->conn_unspec_src = *i1 ? 1 : 0;
11175 				mutex_exit(&connp->conn_lock);
11176 			}
11177 			break;	/* goto sizeof (int) option return */
11178 		default:
11179 			/*
11180 			 * "soft" error (negative)
11181 			 * option not handled at this level
11182 			 * Note: Do not modify *outlenp
11183 			 */
11184 			return (-EINVAL);
11185 		}
11186 		break;
11187 	case IPPROTO_IPV6:
11188 		switch (name) {
11189 		case IPV6_BOUND_IF:
11190 		case IPV6_BOUND_PIF:
11191 		case IPV6_DONTFAILOVER_IF:
11192 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11193 			    level, name, first_mp);
11194 			if (error != 0)
11195 				return (error);
11196 			break; 		/* goto sizeof (int) option return */
11197 
11198 		case IPV6_MULTICAST_IF:
11199 			/*
11200 			 * The only possible errors are EINPROGRESS and
11201 			 * EINVAL. EINPROGRESS will be restarted and is not
11202 			 * a hard error. We call this option on both V4 and V6
11203 			 * If both return EINVAL, then this call returns
11204 			 * EINVAL. If at least one of them succeeds we
11205 			 * return success.
11206 			 */
11207 			found = B_FALSE;
11208 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11209 			    level, name, first_mp);
11210 			if (error == EINPROGRESS)
11211 				return (error);
11212 			if (error == 0)
11213 				found = B_TRUE;
11214 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11215 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11216 			if (error == 0)
11217 				found = B_TRUE;
11218 			if (!found)
11219 				return (error);
11220 			break; 		/* goto sizeof (int) option return */
11221 
11222 		case IPV6_MULTICAST_HOPS:
11223 			/* Recorded in transport above IP */
11224 			break;	/* goto sizeof (int) option return */
11225 		case IPV6_MULTICAST_LOOP:
11226 			if (!checkonly) {
11227 				mutex_enter(&connp->conn_lock);
11228 				connp->conn_multicast_loop = *i1;
11229 				mutex_exit(&connp->conn_lock);
11230 			}
11231 			break;	/* goto sizeof (int) option return */
11232 		case IPV6_JOIN_GROUP:
11233 		case MCAST_JOIN_GROUP:
11234 		case IPV6_LEAVE_GROUP:
11235 		case MCAST_LEAVE_GROUP: {
11236 			struct ipv6_mreq *ip_mreqp;
11237 			struct group_req *greqp;
11238 			ire_t *ire;
11239 			boolean_t done = B_FALSE;
11240 			in6_addr_t groupv6;
11241 			uint32_t ifindex;
11242 			boolean_t mcast_opt = B_TRUE;
11243 			mcast_record_t fmode;
11244 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11245 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11246 
11247 			switch (name) {
11248 			case IPV6_JOIN_GROUP:
11249 				mcast_opt = B_FALSE;
11250 				/* FALLTHRU */
11251 			case MCAST_JOIN_GROUP:
11252 				fmode = MODE_IS_EXCLUDE;
11253 				optfn = ip_opt_add_group_v6;
11254 				break;
11255 
11256 			case IPV6_LEAVE_GROUP:
11257 				mcast_opt = B_FALSE;
11258 				/* FALLTHRU */
11259 			case MCAST_LEAVE_GROUP:
11260 				fmode = MODE_IS_INCLUDE;
11261 				optfn = ip_opt_delete_group_v6;
11262 				break;
11263 			}
11264 
11265 			if (mcast_opt) {
11266 				struct sockaddr_in *sin;
11267 				struct sockaddr_in6 *sin6;
11268 				greqp = (struct group_req *)i1;
11269 				if (greqp->gr_group.ss_family == AF_INET) {
11270 					sin = (struct sockaddr_in *)
11271 					    &(greqp->gr_group);
11272 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11273 					    &groupv6);
11274 				} else {
11275 					sin6 = (struct sockaddr_in6 *)
11276 					    &(greqp->gr_group);
11277 					groupv6 = sin6->sin6_addr;
11278 				}
11279 				ifindex = greqp->gr_interface;
11280 			} else {
11281 				ip_mreqp = (struct ipv6_mreq *)i1;
11282 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11283 				ifindex = ip_mreqp->ipv6mr_interface;
11284 			}
11285 			/*
11286 			 * In the multirouting case, we need to replicate
11287 			 * the request on all interfaces that will take part
11288 			 * in replication.  We do so because multirouting is
11289 			 * reflective, thus we will probably receive multi-
11290 			 * casts on those interfaces.
11291 			 * The ip_multirt_apply_membership_v6() succeeds if
11292 			 * the operation succeeds on at least one interface.
11293 			 */
11294 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11295 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11296 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11297 			if (ire != NULL) {
11298 				if (ire->ire_flags & RTF_MULTIRT) {
11299 					error = ip_multirt_apply_membership_v6(
11300 					    optfn, ire, connp, checkonly,
11301 					    &groupv6, fmode, &ipv6_all_zeros,
11302 					    first_mp);
11303 					done = B_TRUE;
11304 				}
11305 				ire_refrele(ire);
11306 			}
11307 			if (!done) {
11308 				error = optfn(connp, checkonly, &groupv6,
11309 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11310 			}
11311 			if (error) {
11312 				/*
11313 				 * EINPROGRESS is a soft error, needs retry
11314 				 * so don't make *outlenp zero.
11315 				 */
11316 				if (error != EINPROGRESS)
11317 					*outlenp = 0;
11318 				return (error);
11319 			}
11320 			/* OK return - copy input buffer into output buffer */
11321 			if (invalp != outvalp) {
11322 				/* don't trust bcopy for identical src/dst */
11323 				bcopy(invalp, outvalp, inlen);
11324 			}
11325 			*outlenp = inlen;
11326 			return (0);
11327 		}
11328 		case MCAST_BLOCK_SOURCE:
11329 		case MCAST_UNBLOCK_SOURCE:
11330 		case MCAST_JOIN_SOURCE_GROUP:
11331 		case MCAST_LEAVE_SOURCE_GROUP: {
11332 			struct group_source_req *gsreqp;
11333 			in6_addr_t v6grp, v6src;
11334 			uint32_t ifindex;
11335 			mcast_record_t fmode;
11336 			ire_t *ire;
11337 			boolean_t done = B_FALSE;
11338 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11339 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11340 
11341 			switch (name) {
11342 			case MCAST_BLOCK_SOURCE:
11343 				fmode = MODE_IS_EXCLUDE;
11344 				optfn = ip_opt_add_group_v6;
11345 				break;
11346 			case MCAST_UNBLOCK_SOURCE:
11347 				fmode = MODE_IS_EXCLUDE;
11348 				optfn = ip_opt_delete_group_v6;
11349 				break;
11350 			case MCAST_JOIN_SOURCE_GROUP:
11351 				fmode = MODE_IS_INCLUDE;
11352 				optfn = ip_opt_add_group_v6;
11353 				break;
11354 			case MCAST_LEAVE_SOURCE_GROUP:
11355 				fmode = MODE_IS_INCLUDE;
11356 				optfn = ip_opt_delete_group_v6;
11357 				break;
11358 			}
11359 
11360 			gsreqp = (struct group_source_req *)i1;
11361 			ifindex = gsreqp->gsr_interface;
11362 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11363 				struct sockaddr_in *s;
11364 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11365 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11366 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11367 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11368 			} else {
11369 				struct sockaddr_in6 *s6;
11370 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11371 				v6grp = s6->sin6_addr;
11372 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11373 				v6src = s6->sin6_addr;
11374 			}
11375 
11376 			/*
11377 			 * In the multirouting case, we need to replicate
11378 			 * the request as noted in the mcast cases above.
11379 			 */
11380 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11381 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11382 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11383 			if (ire != NULL) {
11384 				if (ire->ire_flags & RTF_MULTIRT) {
11385 					error = ip_multirt_apply_membership_v6(
11386 					    optfn, ire, connp, checkonly,
11387 					    &v6grp, fmode, &v6src, first_mp);
11388 					done = B_TRUE;
11389 				}
11390 				ire_refrele(ire);
11391 			}
11392 			if (!done) {
11393 				error = optfn(connp, checkonly, &v6grp,
11394 				    ifindex, fmode, &v6src, first_mp);
11395 			}
11396 			if (error != 0) {
11397 				/*
11398 				 * EINPROGRESS is a soft error, needs retry
11399 				 * so don't make *outlenp zero.
11400 				 */
11401 				if (error != EINPROGRESS)
11402 					*outlenp = 0;
11403 				return (error);
11404 			}
11405 			/* OK return - copy input buffer into output buffer */
11406 			if (invalp != outvalp) {
11407 				bcopy(invalp, outvalp, inlen);
11408 			}
11409 			*outlenp = inlen;
11410 			return (0);
11411 		}
11412 		case IPV6_UNICAST_HOPS:
11413 			/* Recorded in transport above IP */
11414 			break;	/* goto sizeof (int) option return */
11415 		case IPV6_UNSPEC_SRC:
11416 			/* Allow sending with a zero source address */
11417 			if (!checkonly) {
11418 				mutex_enter(&connp->conn_lock);
11419 				connp->conn_unspec_src = *i1 ? 1 : 0;
11420 				mutex_exit(&connp->conn_lock);
11421 			}
11422 			break;	/* goto sizeof (int) option return */
11423 		case IPV6_RECVPKTINFO:
11424 			if (!checkonly) {
11425 				mutex_enter(&connp->conn_lock);
11426 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11427 				mutex_exit(&connp->conn_lock);
11428 			}
11429 			break;	/* goto sizeof (int) option return */
11430 		case IPV6_RECVTCLASS:
11431 			if (!checkonly) {
11432 				if (*i1 < 0 || *i1 > 1) {
11433 					return (EINVAL);
11434 				}
11435 				mutex_enter(&connp->conn_lock);
11436 				connp->conn_ipv6_recvtclass = *i1;
11437 				mutex_exit(&connp->conn_lock);
11438 			}
11439 			break;
11440 		case IPV6_RECVPATHMTU:
11441 			if (!checkonly) {
11442 				if (*i1 < 0 || *i1 > 1) {
11443 					return (EINVAL);
11444 				}
11445 				mutex_enter(&connp->conn_lock);
11446 				connp->conn_ipv6_recvpathmtu = *i1;
11447 				mutex_exit(&connp->conn_lock);
11448 			}
11449 			break;
11450 		case IPV6_RECVHOPLIMIT:
11451 			if (!checkonly) {
11452 				mutex_enter(&connp->conn_lock);
11453 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11454 				mutex_exit(&connp->conn_lock);
11455 			}
11456 			break;	/* goto sizeof (int) option return */
11457 		case IPV6_RECVHOPOPTS:
11458 			if (!checkonly) {
11459 				mutex_enter(&connp->conn_lock);
11460 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11461 				mutex_exit(&connp->conn_lock);
11462 			}
11463 			break;	/* goto sizeof (int) option return */
11464 		case IPV6_RECVDSTOPTS:
11465 			if (!checkonly) {
11466 				mutex_enter(&connp->conn_lock);
11467 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11468 				mutex_exit(&connp->conn_lock);
11469 			}
11470 			break;	/* goto sizeof (int) option return */
11471 		case IPV6_RECVRTHDR:
11472 			if (!checkonly) {
11473 				mutex_enter(&connp->conn_lock);
11474 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11475 				mutex_exit(&connp->conn_lock);
11476 			}
11477 			break;	/* goto sizeof (int) option return */
11478 		case IPV6_RECVRTHDRDSTOPTS:
11479 			if (!checkonly) {
11480 				mutex_enter(&connp->conn_lock);
11481 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11482 				mutex_exit(&connp->conn_lock);
11483 			}
11484 			break;	/* goto sizeof (int) option return */
11485 		case IPV6_PKTINFO:
11486 			if (inlen == 0)
11487 				return (-EINVAL);	/* clearing option */
11488 			error = ip6_set_pktinfo(cr, connp,
11489 			    (struct in6_pktinfo *)invalp, first_mp);
11490 			if (error != 0)
11491 				*outlenp = 0;
11492 			else
11493 				*outlenp = inlen;
11494 			return (error);
11495 		case IPV6_NEXTHOP: {
11496 			struct sockaddr_in6 *sin6;
11497 
11498 			/* Verify that the nexthop is reachable */
11499 			if (inlen == 0)
11500 				return (-EINVAL);	/* clearing option */
11501 
11502 			sin6 = (struct sockaddr_in6 *)invalp;
11503 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11504 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11505 			    NULL, MATCH_IRE_DEFAULT, ipst);
11506 
11507 			if (ire == NULL) {
11508 				*outlenp = 0;
11509 				return (EHOSTUNREACH);
11510 			}
11511 			ire_refrele(ire);
11512 			return (-EINVAL);
11513 		}
11514 		case IPV6_SEC_OPT:
11515 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11516 			if (error != 0) {
11517 				*outlenp = 0;
11518 				return (error);
11519 			}
11520 			break;
11521 		case IPV6_SRC_PREFERENCES: {
11522 			/*
11523 			 * This is implemented strictly in the ip module
11524 			 * (here and in tcp_opt_*() to accomodate tcp
11525 			 * sockets).  Modules above ip pass this option
11526 			 * down here since ip is the only one that needs to
11527 			 * be aware of source address preferences.
11528 			 *
11529 			 * This socket option only affects connected
11530 			 * sockets that haven't already bound to a specific
11531 			 * IPv6 address.  In other words, sockets that
11532 			 * don't call bind() with an address other than the
11533 			 * unspecified address and that call connect().
11534 			 * ip_bind_connected_v6() passes these preferences
11535 			 * to the ipif_select_source_v6() function.
11536 			 */
11537 			if (inlen != sizeof (uint32_t))
11538 				return (EINVAL);
11539 			error = ip6_set_src_preferences(connp,
11540 			    *(uint32_t *)invalp);
11541 			if (error != 0) {
11542 				*outlenp = 0;
11543 				return (error);
11544 			} else {
11545 				*outlenp = sizeof (uint32_t);
11546 			}
11547 			break;
11548 		}
11549 		case IPV6_V6ONLY:
11550 			if (*i1 < 0 || *i1 > 1) {
11551 				return (EINVAL);
11552 			}
11553 			mutex_enter(&connp->conn_lock);
11554 			connp->conn_ipv6_v6only = *i1;
11555 			mutex_exit(&connp->conn_lock);
11556 			break;
11557 		default:
11558 			return (-EINVAL);
11559 		}
11560 		break;
11561 	default:
11562 		/*
11563 		 * "soft" error (negative)
11564 		 * option not handled at this level
11565 		 * Note: Do not modify *outlenp
11566 		 */
11567 		return (-EINVAL);
11568 	}
11569 	/*
11570 	 * Common case of return from an option that is sizeof (int)
11571 	 */
11572 	*(int *)outvalp = *i1;
11573 	*outlenp = sizeof (int);
11574 	return (0);
11575 }
11576 
11577 /*
11578  * This routine gets default values of certain options whose default
11579  * values are maintained by protocol specific code
11580  */
11581 /* ARGSUSED */
11582 int
11583 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11584 {
11585 	int *i1 = (int *)ptr;
11586 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11587 
11588 	switch (level) {
11589 	case IPPROTO_IP:
11590 		switch (name) {
11591 		case IP_MULTICAST_TTL:
11592 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11593 			return (sizeof (uchar_t));
11594 		case IP_MULTICAST_LOOP:
11595 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11596 			return (sizeof (uchar_t));
11597 		default:
11598 			return (-1);
11599 		}
11600 	case IPPROTO_IPV6:
11601 		switch (name) {
11602 		case IPV6_UNICAST_HOPS:
11603 			*i1 = ipst->ips_ipv6_def_hops;
11604 			return (sizeof (int));
11605 		case IPV6_MULTICAST_HOPS:
11606 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11607 			return (sizeof (int));
11608 		case IPV6_MULTICAST_LOOP:
11609 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11610 			return (sizeof (int));
11611 		case IPV6_V6ONLY:
11612 			*i1 = 1;
11613 			return (sizeof (int));
11614 		default:
11615 			return (-1);
11616 		}
11617 	default:
11618 		return (-1);
11619 	}
11620 	/* NOTREACHED */
11621 }
11622 
11623 /*
11624  * Given a destination address and a pointer to where to put the information
11625  * this routine fills in the mtuinfo.
11626  */
11627 int
11628 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11629     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11630 {
11631 	ire_t *ire;
11632 	ip_stack_t	*ipst = ns->netstack_ip;
11633 
11634 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11635 		return (-1);
11636 
11637 	bzero(mtuinfo, sizeof (*mtuinfo));
11638 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11639 	mtuinfo->ip6m_addr.sin6_port = port;
11640 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11641 
11642 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11643 	if (ire != NULL) {
11644 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11645 		ire_refrele(ire);
11646 	} else {
11647 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11648 	}
11649 	return (sizeof (struct ip6_mtuinfo));
11650 }
11651 
11652 /*
11653  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11654  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11655  * isn't.  This doesn't matter as the error checking is done properly for the
11656  * other MRT options coming in through ip_opt_set.
11657  */
11658 int
11659 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11660 {
11661 	conn_t		*connp = Q_TO_CONN(q);
11662 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11663 
11664 	switch (level) {
11665 	case IPPROTO_IP:
11666 		switch (name) {
11667 		case MRT_VERSION:
11668 		case MRT_ASSERT:
11669 			(void) ip_mrouter_get(name, q, ptr);
11670 			return (sizeof (int));
11671 		case IP_SEC_OPT:
11672 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11673 		case IP_NEXTHOP:
11674 			if (connp->conn_nexthop_set) {
11675 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11676 				return (sizeof (ipaddr_t));
11677 			} else
11678 				return (0);
11679 		case IP_RECVPKTINFO:
11680 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11681 			return (sizeof (int));
11682 		default:
11683 			break;
11684 		}
11685 		break;
11686 	case IPPROTO_IPV6:
11687 		switch (name) {
11688 		case IPV6_SEC_OPT:
11689 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11690 		case IPV6_SRC_PREFERENCES: {
11691 			return (ip6_get_src_preferences(connp,
11692 			    (uint32_t *)ptr));
11693 		}
11694 		case IPV6_V6ONLY:
11695 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11696 			return (sizeof (int));
11697 		case IPV6_PATHMTU:
11698 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11699 			    (struct ip6_mtuinfo *)ptr, connp->conn_netstack));
11700 		default:
11701 			break;
11702 		}
11703 		break;
11704 	default:
11705 		break;
11706 	}
11707 	return (-1);
11708 }
11709 /* Named Dispatch routine to get a current value out of our parameter table. */
11710 /* ARGSUSED */
11711 static int
11712 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11713 {
11714 	ipparam_t *ippa = (ipparam_t *)cp;
11715 
11716 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11717 	return (0);
11718 }
11719 
11720 /* ARGSUSED */
11721 static int
11722 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11723 {
11724 
11725 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11726 	return (0);
11727 }
11728 
11729 /*
11730  * Set ip{,6}_forwarding values.  This means walking through all of the
11731  * ill's and toggling their forwarding values.
11732  */
11733 /* ARGSUSED */
11734 static int
11735 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11736 {
11737 	long new_value;
11738 	int *forwarding_value = (int *)cp;
11739 	ill_t *ill;
11740 	boolean_t isv6;
11741 	ill_walk_context_t ctx;
11742 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11743 
11744 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11745 
11746 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11747 	    new_value < 0 || new_value > 1) {
11748 		return (EINVAL);
11749 	}
11750 
11751 	*forwarding_value = new_value;
11752 
11753 	/*
11754 	 * Regardless of the current value of ip_forwarding, set all per-ill
11755 	 * values of ip_forwarding to the value being set.
11756 	 *
11757 	 * Bring all the ill's up to date with the new global value.
11758 	 */
11759 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11760 
11761 	if (isv6)
11762 		ill = ILL_START_WALK_V6(&ctx, ipst);
11763 	else
11764 		ill = ILL_START_WALK_V4(&ctx, ipst);
11765 
11766 	for (; ill != NULL; ill = ill_next(&ctx, ill))
11767 		(void) ill_forward_set(ill, new_value != 0);
11768 
11769 	rw_exit(&ipst->ips_ill_g_lock);
11770 	return (0);
11771 }
11772 
11773 /*
11774  * Walk through the param array specified registering each element with the
11775  * Named Dispatch handler. This is called only during init. So it is ok
11776  * not to acquire any locks
11777  */
11778 static boolean_t
11779 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11780     ipndp_t *ipnd, size_t ipnd_cnt)
11781 {
11782 	for (; ippa_cnt-- > 0; ippa++) {
11783 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11784 			if (!nd_load(ndp, ippa->ip_param_name,
11785 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11786 				nd_free(ndp);
11787 				return (B_FALSE);
11788 			}
11789 		}
11790 	}
11791 
11792 	for (; ipnd_cnt-- > 0; ipnd++) {
11793 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11794 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11795 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11796 			    ipnd->ip_ndp_data)) {
11797 				nd_free(ndp);
11798 				return (B_FALSE);
11799 			}
11800 		}
11801 	}
11802 
11803 	return (B_TRUE);
11804 }
11805 
11806 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11807 /* ARGSUSED */
11808 static int
11809 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11810 {
11811 	long		new_value;
11812 	ipparam_t	*ippa = (ipparam_t *)cp;
11813 
11814 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11815 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11816 		return (EINVAL);
11817 	}
11818 	ippa->ip_param_value = new_value;
11819 	return (0);
11820 }
11821 
11822 /*
11823  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11824  * When an ipf is passed here for the first time, if
11825  * we already have in-order fragments on the queue, we convert from the fast-
11826  * path reassembly scheme to the hard-case scheme.  From then on, additional
11827  * fragments are reassembled here.  We keep track of the start and end offsets
11828  * of each piece, and the number of holes in the chain.  When the hole count
11829  * goes to zero, we are done!
11830  *
11831  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11832  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11833  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11834  * after the call to ip_reassemble().
11835  */
11836 int
11837 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11838     size_t msg_len)
11839 {
11840 	uint_t	end;
11841 	mblk_t	*next_mp;
11842 	mblk_t	*mp1;
11843 	uint_t	offset;
11844 	boolean_t incr_dups = B_TRUE;
11845 	boolean_t offset_zero_seen = B_FALSE;
11846 	boolean_t pkt_boundary_checked = B_FALSE;
11847 
11848 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11849 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11850 
11851 	/* Add in byte count */
11852 	ipf->ipf_count += msg_len;
11853 	if (ipf->ipf_end) {
11854 		/*
11855 		 * We were part way through in-order reassembly, but now there
11856 		 * is a hole.  We walk through messages already queued, and
11857 		 * mark them for hard case reassembly.  We know that up till
11858 		 * now they were in order starting from offset zero.
11859 		 */
11860 		offset = 0;
11861 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11862 			IP_REASS_SET_START(mp1, offset);
11863 			if (offset == 0) {
11864 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11865 				offset = -ipf->ipf_nf_hdr_len;
11866 			}
11867 			offset += mp1->b_wptr - mp1->b_rptr;
11868 			IP_REASS_SET_END(mp1, offset);
11869 		}
11870 		/* One hole at the end. */
11871 		ipf->ipf_hole_cnt = 1;
11872 		/* Brand it as a hard case, forever. */
11873 		ipf->ipf_end = 0;
11874 	}
11875 	/* Walk through all the new pieces. */
11876 	do {
11877 		end = start + (mp->b_wptr - mp->b_rptr);
11878 		/*
11879 		 * If start is 0, decrease 'end' only for the first mblk of
11880 		 * the fragment. Otherwise 'end' can get wrong value in the
11881 		 * second pass of the loop if first mblk is exactly the
11882 		 * size of ipf_nf_hdr_len.
11883 		 */
11884 		if (start == 0 && !offset_zero_seen) {
11885 			/* First segment */
11886 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11887 			end -= ipf->ipf_nf_hdr_len;
11888 			offset_zero_seen = B_TRUE;
11889 		}
11890 		next_mp = mp->b_cont;
11891 		/*
11892 		 * We are checking to see if there is any interesing data
11893 		 * to process.  If there isn't and the mblk isn't the
11894 		 * one which carries the unfragmentable header then we
11895 		 * drop it.  It's possible to have just the unfragmentable
11896 		 * header come through without any data.  That needs to be
11897 		 * saved.
11898 		 *
11899 		 * If the assert at the top of this function holds then the
11900 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11901 		 * is infrequently traveled enough that the test is left in
11902 		 * to protect against future code changes which break that
11903 		 * invariant.
11904 		 */
11905 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11906 			/* Empty.  Blast it. */
11907 			IP_REASS_SET_START(mp, 0);
11908 			IP_REASS_SET_END(mp, 0);
11909 			/*
11910 			 * If the ipf points to the mblk we are about to free,
11911 			 * update ipf to point to the next mblk (or NULL
11912 			 * if none).
11913 			 */
11914 			if (ipf->ipf_mp->b_cont == mp)
11915 				ipf->ipf_mp->b_cont = next_mp;
11916 			freeb(mp);
11917 			continue;
11918 		}
11919 		mp->b_cont = NULL;
11920 		IP_REASS_SET_START(mp, start);
11921 		IP_REASS_SET_END(mp, end);
11922 		if (!ipf->ipf_tail_mp) {
11923 			ipf->ipf_tail_mp = mp;
11924 			ipf->ipf_mp->b_cont = mp;
11925 			if (start == 0 || !more) {
11926 				ipf->ipf_hole_cnt = 1;
11927 				/*
11928 				 * if the first fragment comes in more than one
11929 				 * mblk, this loop will be executed for each
11930 				 * mblk. Need to adjust hole count so exiting
11931 				 * this routine will leave hole count at 1.
11932 				 */
11933 				if (next_mp)
11934 					ipf->ipf_hole_cnt++;
11935 			} else
11936 				ipf->ipf_hole_cnt = 2;
11937 			continue;
11938 		} else if (ipf->ipf_last_frag_seen && !more &&
11939 		    !pkt_boundary_checked) {
11940 			/*
11941 			 * We check datagram boundary only if this fragment
11942 			 * claims to be the last fragment and we have seen a
11943 			 * last fragment in the past too. We do this only
11944 			 * once for a given fragment.
11945 			 *
11946 			 * start cannot be 0 here as fragments with start=0
11947 			 * and MF=0 gets handled as a complete packet. These
11948 			 * fragments should not reach here.
11949 			 */
11950 
11951 			if (start + msgdsize(mp) !=
11952 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11953 				/*
11954 				 * We have two fragments both of which claim
11955 				 * to be the last fragment but gives conflicting
11956 				 * information about the whole datagram size.
11957 				 * Something fishy is going on. Drop the
11958 				 * fragment and free up the reassembly list.
11959 				 */
11960 				return (IP_REASS_FAILED);
11961 			}
11962 
11963 			/*
11964 			 * We shouldn't come to this code block again for this
11965 			 * particular fragment.
11966 			 */
11967 			pkt_boundary_checked = B_TRUE;
11968 		}
11969 
11970 		/* New stuff at or beyond tail? */
11971 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11972 		if (start >= offset) {
11973 			if (ipf->ipf_last_frag_seen) {
11974 				/* current fragment is beyond last fragment */
11975 				return (IP_REASS_FAILED);
11976 			}
11977 			/* Link it on end. */
11978 			ipf->ipf_tail_mp->b_cont = mp;
11979 			ipf->ipf_tail_mp = mp;
11980 			if (more) {
11981 				if (start != offset)
11982 					ipf->ipf_hole_cnt++;
11983 			} else if (start == offset && next_mp == NULL)
11984 					ipf->ipf_hole_cnt--;
11985 			continue;
11986 		}
11987 		mp1 = ipf->ipf_mp->b_cont;
11988 		offset = IP_REASS_START(mp1);
11989 		/* New stuff at the front? */
11990 		if (start < offset) {
11991 			if (start == 0) {
11992 				if (end >= offset) {
11993 					/* Nailed the hole at the begining. */
11994 					ipf->ipf_hole_cnt--;
11995 				}
11996 			} else if (end < offset) {
11997 				/*
11998 				 * A hole, stuff, and a hole where there used
11999 				 * to be just a hole.
12000 				 */
12001 				ipf->ipf_hole_cnt++;
12002 			}
12003 			mp->b_cont = mp1;
12004 			/* Check for overlap. */
12005 			while (end > offset) {
12006 				if (end < IP_REASS_END(mp1)) {
12007 					mp->b_wptr -= end - offset;
12008 					IP_REASS_SET_END(mp, offset);
12009 					BUMP_MIB(ill->ill_ip_mib,
12010 					    ipIfStatsReasmPartDups);
12011 					break;
12012 				}
12013 				/* Did we cover another hole? */
12014 				if ((mp1->b_cont &&
12015 				    IP_REASS_END(mp1) !=
12016 				    IP_REASS_START(mp1->b_cont) &&
12017 				    end >= IP_REASS_START(mp1->b_cont)) ||
12018 				    (!ipf->ipf_last_frag_seen && !more)) {
12019 					ipf->ipf_hole_cnt--;
12020 				}
12021 				/* Clip out mp1. */
12022 				if ((mp->b_cont = mp1->b_cont) == NULL) {
12023 					/*
12024 					 * After clipping out mp1, this guy
12025 					 * is now hanging off the end.
12026 					 */
12027 					ipf->ipf_tail_mp = mp;
12028 				}
12029 				IP_REASS_SET_START(mp1, 0);
12030 				IP_REASS_SET_END(mp1, 0);
12031 				/* Subtract byte count */
12032 				ipf->ipf_count -= mp1->b_datap->db_lim -
12033 				    mp1->b_datap->db_base;
12034 				freeb(mp1);
12035 				BUMP_MIB(ill->ill_ip_mib,
12036 				    ipIfStatsReasmPartDups);
12037 				mp1 = mp->b_cont;
12038 				if (!mp1)
12039 					break;
12040 				offset = IP_REASS_START(mp1);
12041 			}
12042 			ipf->ipf_mp->b_cont = mp;
12043 			continue;
12044 		}
12045 		/*
12046 		 * The new piece starts somewhere between the start of the head
12047 		 * and before the end of the tail.
12048 		 */
12049 		for (; mp1; mp1 = mp1->b_cont) {
12050 			offset = IP_REASS_END(mp1);
12051 			if (start < offset) {
12052 				if (end <= offset) {
12053 					/* Nothing new. */
12054 					IP_REASS_SET_START(mp, 0);
12055 					IP_REASS_SET_END(mp, 0);
12056 					/* Subtract byte count */
12057 					ipf->ipf_count -= mp->b_datap->db_lim -
12058 					    mp->b_datap->db_base;
12059 					if (incr_dups) {
12060 						ipf->ipf_num_dups++;
12061 						incr_dups = B_FALSE;
12062 					}
12063 					freeb(mp);
12064 					BUMP_MIB(ill->ill_ip_mib,
12065 					    ipIfStatsReasmDuplicates);
12066 					break;
12067 				}
12068 				/*
12069 				 * Trim redundant stuff off beginning of new
12070 				 * piece.
12071 				 */
12072 				IP_REASS_SET_START(mp, offset);
12073 				mp->b_rptr += offset - start;
12074 				BUMP_MIB(ill->ill_ip_mib,
12075 				    ipIfStatsReasmPartDups);
12076 				start = offset;
12077 				if (!mp1->b_cont) {
12078 					/*
12079 					 * After trimming, this guy is now
12080 					 * hanging off the end.
12081 					 */
12082 					mp1->b_cont = mp;
12083 					ipf->ipf_tail_mp = mp;
12084 					if (!more) {
12085 						ipf->ipf_hole_cnt--;
12086 					}
12087 					break;
12088 				}
12089 			}
12090 			if (start >= IP_REASS_START(mp1->b_cont))
12091 				continue;
12092 			/* Fill a hole */
12093 			if (start > offset)
12094 				ipf->ipf_hole_cnt++;
12095 			mp->b_cont = mp1->b_cont;
12096 			mp1->b_cont = mp;
12097 			mp1 = mp->b_cont;
12098 			offset = IP_REASS_START(mp1);
12099 			if (end >= offset) {
12100 				ipf->ipf_hole_cnt--;
12101 				/* Check for overlap. */
12102 				while (end > offset) {
12103 					if (end < IP_REASS_END(mp1)) {
12104 						mp->b_wptr -= end - offset;
12105 						IP_REASS_SET_END(mp, offset);
12106 						/*
12107 						 * TODO we might bump
12108 						 * this up twice if there is
12109 						 * overlap at both ends.
12110 						 */
12111 						BUMP_MIB(ill->ill_ip_mib,
12112 						    ipIfStatsReasmPartDups);
12113 						break;
12114 					}
12115 					/* Did we cover another hole? */
12116 					if ((mp1->b_cont &&
12117 					    IP_REASS_END(mp1)
12118 					    != IP_REASS_START(mp1->b_cont) &&
12119 					    end >=
12120 					    IP_REASS_START(mp1->b_cont)) ||
12121 					    (!ipf->ipf_last_frag_seen &&
12122 					    !more)) {
12123 						ipf->ipf_hole_cnt--;
12124 					}
12125 					/* Clip out mp1. */
12126 					if ((mp->b_cont = mp1->b_cont) ==
12127 					    NULL) {
12128 						/*
12129 						 * After clipping out mp1,
12130 						 * this guy is now hanging
12131 						 * off the end.
12132 						 */
12133 						ipf->ipf_tail_mp = mp;
12134 					}
12135 					IP_REASS_SET_START(mp1, 0);
12136 					IP_REASS_SET_END(mp1, 0);
12137 					/* Subtract byte count */
12138 					ipf->ipf_count -=
12139 					    mp1->b_datap->db_lim -
12140 					    mp1->b_datap->db_base;
12141 					freeb(mp1);
12142 					BUMP_MIB(ill->ill_ip_mib,
12143 					    ipIfStatsReasmPartDups);
12144 					mp1 = mp->b_cont;
12145 					if (!mp1)
12146 						break;
12147 					offset = IP_REASS_START(mp1);
12148 				}
12149 			}
12150 			break;
12151 		}
12152 	} while (start = end, mp = next_mp);
12153 
12154 	/* Fragment just processed could be the last one. Remember this fact */
12155 	if (!more)
12156 		ipf->ipf_last_frag_seen = B_TRUE;
12157 
12158 	/* Still got holes? */
12159 	if (ipf->ipf_hole_cnt)
12160 		return (IP_REASS_PARTIAL);
12161 	/* Clean up overloaded fields to avoid upstream disasters. */
12162 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12163 		IP_REASS_SET_START(mp1, 0);
12164 		IP_REASS_SET_END(mp1, 0);
12165 	}
12166 	return (IP_REASS_COMPLETE);
12167 }
12168 
12169 /*
12170  * ipsec processing for the fast path, used for input UDP Packets
12171  * Returns true if ready for passup to UDP.
12172  * Return false if packet is not passable to UDP (e.g. it failed IPsec policy,
12173  * was an ESP-in-UDP packet, etc.).
12174  */
12175 static boolean_t
12176 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
12177     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present, ire_t *ire)
12178 {
12179 	uint32_t	ill_index;
12180 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
12181 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
12182 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12183 	udp_t		*udp = connp->conn_udp;
12184 
12185 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12186 	/* The ill_index of the incoming ILL */
12187 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
12188 
12189 	/* pass packet up to the transport */
12190 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
12191 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
12192 		    NULL, mctl_present);
12193 		if (*first_mpp == NULL) {
12194 			return (B_FALSE);
12195 		}
12196 	}
12197 
12198 	/* Initiate IPPF processing for fastpath UDP */
12199 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12200 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
12201 		if (*mpp == NULL) {
12202 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
12203 			    "deferred/dropped during IPPF processing\n"));
12204 			return (B_FALSE);
12205 		}
12206 	}
12207 	/*
12208 	 * Remove 0-spi if it's 0, or move everything behind
12209 	 * the UDP header over it and forward to ESP via
12210 	 * ip_proto_input().
12211 	 */
12212 	if (udp->udp_nat_t_endpoint) {
12213 		if (mctl_present) {
12214 			/* mctl_present *shouldn't* happen. */
12215 			ip_drop_packet(*first_mpp, B_TRUE, NULL,
12216 			    NULL, DROPPER(ipss, ipds_esp_nat_t_ipsec),
12217 			    &ipss->ipsec_dropper);
12218 			*first_mpp = NULL;
12219 			return (B_FALSE);
12220 		}
12221 
12222 		/* "ill" is "recv_ill" in actuality. */
12223 		if (!zero_spi_check(q, *mpp, ire, ill, ipss))
12224 			return (B_FALSE);
12225 
12226 		/* Else continue like a normal UDP packet. */
12227 	}
12228 
12229 	/*
12230 	 * We make the checks as below since we are in the fast path
12231 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12232 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12233 	 */
12234 	if (connp->conn_recvif || connp->conn_recvslla ||
12235 	    connp->conn_ip_recvpktinfo) {
12236 		if (connp->conn_recvif) {
12237 			in_flags = IPF_RECVIF;
12238 		}
12239 		/*
12240 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12241 		 * so the flag passed to ip_add_info is based on IP version
12242 		 * of connp.
12243 		 */
12244 		if (connp->conn_ip_recvpktinfo) {
12245 			if (connp->conn_af_isv6) {
12246 				/*
12247 				 * V6 only needs index
12248 				 */
12249 				in_flags |= IPF_RECVIF;
12250 			} else {
12251 				/*
12252 				 * V4 needs index + matching address.
12253 				 */
12254 				in_flags |= IPF_RECVADDR;
12255 			}
12256 		}
12257 		if (connp->conn_recvslla) {
12258 			in_flags |= IPF_RECVSLLA;
12259 		}
12260 		/*
12261 		 * since in_flags are being set ill will be
12262 		 * referenced in ip_add_info, so it better not
12263 		 * be NULL.
12264 		 */
12265 		/*
12266 		 * the actual data will be contained in b_cont
12267 		 * upon successful return of the following call.
12268 		 * If the call fails then the original mblk is
12269 		 * returned.
12270 		 */
12271 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12272 		    ipst);
12273 	}
12274 
12275 	return (B_TRUE);
12276 }
12277 
12278 /*
12279  * Fragmentation reassembly.  Each ILL has a hash table for
12280  * queuing packets undergoing reassembly for all IPIFs
12281  * associated with the ILL.  The hash is based on the packet
12282  * IP ident field.  The ILL frag hash table was allocated
12283  * as a timer block at the time the ILL was created.  Whenever
12284  * there is anything on the reassembly queue, the timer will
12285  * be running.  Returns B_TRUE if successful else B_FALSE;
12286  * frees mp on failure.
12287  */
12288 static boolean_t
12289 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
12290     uint32_t *cksum_val, uint16_t *cksum_flags)
12291 {
12292 	uint32_t	frag_offset_flags;
12293 	ill_t		*ill = (ill_t *)q->q_ptr;
12294 	mblk_t		*mp = *mpp;
12295 	mblk_t		*t_mp;
12296 	ipaddr_t	dst;
12297 	uint8_t		proto = ipha->ipha_protocol;
12298 	uint32_t	sum_val;
12299 	uint16_t	sum_flags;
12300 	ipf_t		*ipf;
12301 	ipf_t		**ipfp;
12302 	ipfb_t		*ipfb;
12303 	uint16_t	ident;
12304 	uint32_t	offset;
12305 	ipaddr_t	src;
12306 	uint_t		hdr_length;
12307 	uint32_t	end;
12308 	mblk_t		*mp1;
12309 	mblk_t		*tail_mp;
12310 	size_t		count;
12311 	size_t		msg_len;
12312 	uint8_t		ecn_info = 0;
12313 	uint32_t	packet_size;
12314 	boolean_t	pruned = B_FALSE;
12315 	ip_stack_t *ipst = ill->ill_ipst;
12316 
12317 	if (cksum_val != NULL)
12318 		*cksum_val = 0;
12319 	if (cksum_flags != NULL)
12320 		*cksum_flags = 0;
12321 
12322 	/*
12323 	 * Drop the fragmented as early as possible, if
12324 	 * we don't have resource(s) to re-assemble.
12325 	 */
12326 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12327 		freemsg(mp);
12328 		return (B_FALSE);
12329 	}
12330 
12331 	/* Check for fragmentation offset; return if there's none */
12332 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12333 	    (IPH_MF | IPH_OFFSET)) == 0)
12334 		return (B_TRUE);
12335 
12336 	/*
12337 	 * We utilize hardware computed checksum info only for UDP since
12338 	 * IP fragmentation is a normal occurence for the protocol.  In
12339 	 * addition, checksum offload support for IP fragments carrying
12340 	 * UDP payload is commonly implemented across network adapters.
12341 	 */
12342 	ASSERT(ill != NULL);
12343 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
12344 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12345 		mblk_t *mp1 = mp->b_cont;
12346 		int32_t len;
12347 
12348 		/* Record checksum information from the packet */
12349 		sum_val = (uint32_t)DB_CKSUM16(mp);
12350 		sum_flags = DB_CKSUMFLAGS(mp);
12351 
12352 		/* IP payload offset from beginning of mblk */
12353 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12354 
12355 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12356 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12357 		    offset >= DB_CKSUMSTART(mp) &&
12358 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12359 			uint32_t adj;
12360 			/*
12361 			 * Partial checksum has been calculated by hardware
12362 			 * and attached to the packet; in addition, any
12363 			 * prepended extraneous data is even byte aligned.
12364 			 * If any such data exists, we adjust the checksum;
12365 			 * this would also handle any postpended data.
12366 			 */
12367 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12368 			    mp, mp1, len, adj);
12369 
12370 			/* One's complement subtract extraneous checksum */
12371 			if (adj >= sum_val)
12372 				sum_val = ~(adj - sum_val) & 0xFFFF;
12373 			else
12374 				sum_val -= adj;
12375 		}
12376 	} else {
12377 		sum_val = 0;
12378 		sum_flags = 0;
12379 	}
12380 
12381 	/* Clear hardware checksumming flag */
12382 	DB_CKSUMFLAGS(mp) = 0;
12383 
12384 	ident = ipha->ipha_ident;
12385 	offset = (frag_offset_flags << 3) & 0xFFFF;
12386 	src = ipha->ipha_src;
12387 	dst = ipha->ipha_dst;
12388 	hdr_length = IPH_HDR_LENGTH(ipha);
12389 	end = ntohs(ipha->ipha_length) - hdr_length;
12390 
12391 	/* If end == 0 then we have a packet with no data, so just free it */
12392 	if (end == 0) {
12393 		freemsg(mp);
12394 		return (B_FALSE);
12395 	}
12396 
12397 	/* Record the ECN field info. */
12398 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12399 	if (offset != 0) {
12400 		/*
12401 		 * If this isn't the first piece, strip the header, and
12402 		 * add the offset to the end value.
12403 		 */
12404 		mp->b_rptr += hdr_length;
12405 		end += offset;
12406 	}
12407 
12408 	msg_len = MBLKSIZE(mp);
12409 	tail_mp = mp;
12410 	while (tail_mp->b_cont != NULL) {
12411 		tail_mp = tail_mp->b_cont;
12412 		msg_len += MBLKSIZE(tail_mp);
12413 	}
12414 
12415 	/* If the reassembly list for this ILL will get too big, prune it */
12416 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12417 	    ipst->ips_ip_reass_queue_bytes) {
12418 		ill_frag_prune(ill,
12419 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12420 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12421 		pruned = B_TRUE;
12422 	}
12423 
12424 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12425 	mutex_enter(&ipfb->ipfb_lock);
12426 
12427 	ipfp = &ipfb->ipfb_ipf;
12428 	/* Try to find an existing fragment queue for this packet. */
12429 	for (;;) {
12430 		ipf = ipfp[0];
12431 		if (ipf != NULL) {
12432 			/*
12433 			 * It has to match on ident and src/dst address.
12434 			 */
12435 			if (ipf->ipf_ident == ident &&
12436 			    ipf->ipf_src == src &&
12437 			    ipf->ipf_dst == dst &&
12438 			    ipf->ipf_protocol == proto) {
12439 				/*
12440 				 * If we have received too many
12441 				 * duplicate fragments for this packet
12442 				 * free it.
12443 				 */
12444 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12445 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12446 					freemsg(mp);
12447 					mutex_exit(&ipfb->ipfb_lock);
12448 					return (B_FALSE);
12449 				}
12450 				/* Found it. */
12451 				break;
12452 			}
12453 			ipfp = &ipf->ipf_hash_next;
12454 			continue;
12455 		}
12456 
12457 		/*
12458 		 * If we pruned the list, do we want to store this new
12459 		 * fragment?. We apply an optimization here based on the
12460 		 * fact that most fragments will be received in order.
12461 		 * So if the offset of this incoming fragment is zero,
12462 		 * it is the first fragment of a new packet. We will
12463 		 * keep it.  Otherwise drop the fragment, as we have
12464 		 * probably pruned the packet already (since the
12465 		 * packet cannot be found).
12466 		 */
12467 		if (pruned && offset != 0) {
12468 			mutex_exit(&ipfb->ipfb_lock);
12469 			freemsg(mp);
12470 			return (B_FALSE);
12471 		}
12472 
12473 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12474 			/*
12475 			 * Too many fragmented packets in this hash
12476 			 * bucket. Free the oldest.
12477 			 */
12478 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12479 		}
12480 
12481 		/* New guy.  Allocate a frag message. */
12482 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12483 		if (mp1 == NULL) {
12484 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12485 			freemsg(mp);
12486 reass_done:
12487 			mutex_exit(&ipfb->ipfb_lock);
12488 			return (B_FALSE);
12489 		}
12490 
12491 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12492 		mp1->b_cont = mp;
12493 
12494 		/* Initialize the fragment header. */
12495 		ipf = (ipf_t *)mp1->b_rptr;
12496 		ipf->ipf_mp = mp1;
12497 		ipf->ipf_ptphn = ipfp;
12498 		ipfp[0] = ipf;
12499 		ipf->ipf_hash_next = NULL;
12500 		ipf->ipf_ident = ident;
12501 		ipf->ipf_protocol = proto;
12502 		ipf->ipf_src = src;
12503 		ipf->ipf_dst = dst;
12504 		ipf->ipf_nf_hdr_len = 0;
12505 		/* Record reassembly start time. */
12506 		ipf->ipf_timestamp = gethrestime_sec();
12507 		/* Record ipf generation and account for frag header */
12508 		ipf->ipf_gen = ill->ill_ipf_gen++;
12509 		ipf->ipf_count = MBLKSIZE(mp1);
12510 		ipf->ipf_last_frag_seen = B_FALSE;
12511 		ipf->ipf_ecn = ecn_info;
12512 		ipf->ipf_num_dups = 0;
12513 		ipfb->ipfb_frag_pkts++;
12514 		ipf->ipf_checksum = 0;
12515 		ipf->ipf_checksum_flags = 0;
12516 
12517 		/* Store checksum value in fragment header */
12518 		if (sum_flags != 0) {
12519 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12520 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12521 			ipf->ipf_checksum = sum_val;
12522 			ipf->ipf_checksum_flags = sum_flags;
12523 		}
12524 
12525 		/*
12526 		 * We handle reassembly two ways.  In the easy case,
12527 		 * where all the fragments show up in order, we do
12528 		 * minimal bookkeeping, and just clip new pieces on
12529 		 * the end.  If we ever see a hole, then we go off
12530 		 * to ip_reassemble which has to mark the pieces and
12531 		 * keep track of the number of holes, etc.  Obviously,
12532 		 * the point of having both mechanisms is so we can
12533 		 * handle the easy case as efficiently as possible.
12534 		 */
12535 		if (offset == 0) {
12536 			/* Easy case, in-order reassembly so far. */
12537 			ipf->ipf_count += msg_len;
12538 			ipf->ipf_tail_mp = tail_mp;
12539 			/*
12540 			 * Keep track of next expected offset in
12541 			 * ipf_end.
12542 			 */
12543 			ipf->ipf_end = end;
12544 			ipf->ipf_nf_hdr_len = hdr_length;
12545 		} else {
12546 			/* Hard case, hole at the beginning. */
12547 			ipf->ipf_tail_mp = NULL;
12548 			/*
12549 			 * ipf_end == 0 means that we have given up
12550 			 * on easy reassembly.
12551 			 */
12552 			ipf->ipf_end = 0;
12553 
12554 			/* Forget checksum offload from now on */
12555 			ipf->ipf_checksum_flags = 0;
12556 
12557 			/*
12558 			 * ipf_hole_cnt is set by ip_reassemble.
12559 			 * ipf_count is updated by ip_reassemble.
12560 			 * No need to check for return value here
12561 			 * as we don't expect reassembly to complete
12562 			 * or fail for the first fragment itself.
12563 			 */
12564 			(void) ip_reassemble(mp, ipf,
12565 			    (frag_offset_flags & IPH_OFFSET) << 3,
12566 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12567 		}
12568 		/* Update per ipfb and ill byte counts */
12569 		ipfb->ipfb_count += ipf->ipf_count;
12570 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12571 		atomic_add_32(&ill->ill_frag_count, ipf->ipf_count);
12572 		/* If the frag timer wasn't already going, start it. */
12573 		mutex_enter(&ill->ill_lock);
12574 		ill_frag_timer_start(ill);
12575 		mutex_exit(&ill->ill_lock);
12576 		goto reass_done;
12577 	}
12578 
12579 	/*
12580 	 * If the packet's flag has changed (it could be coming up
12581 	 * from an interface different than the previous, therefore
12582 	 * possibly different checksum capability), then forget about
12583 	 * any stored checksum states.  Otherwise add the value to
12584 	 * the existing one stored in the fragment header.
12585 	 */
12586 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12587 		sum_val += ipf->ipf_checksum;
12588 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12589 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12590 		ipf->ipf_checksum = sum_val;
12591 	} else if (ipf->ipf_checksum_flags != 0) {
12592 		/* Forget checksum offload from now on */
12593 		ipf->ipf_checksum_flags = 0;
12594 	}
12595 
12596 	/*
12597 	 * We have a new piece of a datagram which is already being
12598 	 * reassembled.  Update the ECN info if all IP fragments
12599 	 * are ECN capable.  If there is one which is not, clear
12600 	 * all the info.  If there is at least one which has CE
12601 	 * code point, IP needs to report that up to transport.
12602 	 */
12603 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12604 		if (ecn_info == IPH_ECN_CE)
12605 			ipf->ipf_ecn = IPH_ECN_CE;
12606 	} else {
12607 		ipf->ipf_ecn = IPH_ECN_NECT;
12608 	}
12609 	if (offset && ipf->ipf_end == offset) {
12610 		/* The new fragment fits at the end */
12611 		ipf->ipf_tail_mp->b_cont = mp;
12612 		/* Update the byte count */
12613 		ipf->ipf_count += msg_len;
12614 		/* Update per ipfb and ill byte counts */
12615 		ipfb->ipfb_count += msg_len;
12616 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12617 		atomic_add_32(&ill->ill_frag_count, msg_len);
12618 		if (frag_offset_flags & IPH_MF) {
12619 			/* More to come. */
12620 			ipf->ipf_end = end;
12621 			ipf->ipf_tail_mp = tail_mp;
12622 			goto reass_done;
12623 		}
12624 	} else {
12625 		/* Go do the hard cases. */
12626 		int ret;
12627 
12628 		if (offset == 0)
12629 			ipf->ipf_nf_hdr_len = hdr_length;
12630 
12631 		/* Save current byte count */
12632 		count = ipf->ipf_count;
12633 		ret = ip_reassemble(mp, ipf,
12634 		    (frag_offset_flags & IPH_OFFSET) << 3,
12635 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12636 		/* Count of bytes added and subtracted (freeb()ed) */
12637 		count = ipf->ipf_count - count;
12638 		if (count) {
12639 			/* Update per ipfb and ill byte counts */
12640 			ipfb->ipfb_count += count;
12641 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12642 			atomic_add_32(&ill->ill_frag_count, count);
12643 		}
12644 		if (ret == IP_REASS_PARTIAL) {
12645 			goto reass_done;
12646 		} else if (ret == IP_REASS_FAILED) {
12647 			/* Reassembly failed. Free up all resources */
12648 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12649 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12650 				IP_REASS_SET_START(t_mp, 0);
12651 				IP_REASS_SET_END(t_mp, 0);
12652 			}
12653 			freemsg(mp);
12654 			goto reass_done;
12655 		}
12656 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12657 	}
12658 	/*
12659 	 * We have completed reassembly.  Unhook the frag header from
12660 	 * the reassembly list.
12661 	 *
12662 	 * Before we free the frag header, record the ECN info
12663 	 * to report back to the transport.
12664 	 */
12665 	ecn_info = ipf->ipf_ecn;
12666 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12667 	ipfp = ipf->ipf_ptphn;
12668 
12669 	/* We need to supply these to caller */
12670 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12671 		sum_val = ipf->ipf_checksum;
12672 	else
12673 		sum_val = 0;
12674 
12675 	mp1 = ipf->ipf_mp;
12676 	count = ipf->ipf_count;
12677 	ipf = ipf->ipf_hash_next;
12678 	if (ipf != NULL)
12679 		ipf->ipf_ptphn = ipfp;
12680 	ipfp[0] = ipf;
12681 	atomic_add_32(&ill->ill_frag_count, -count);
12682 	ASSERT(ipfb->ipfb_count >= count);
12683 	ipfb->ipfb_count -= count;
12684 	ipfb->ipfb_frag_pkts--;
12685 	mutex_exit(&ipfb->ipfb_lock);
12686 	/* Ditch the frag header. */
12687 	mp = mp1->b_cont;
12688 
12689 	freeb(mp1);
12690 
12691 	/* Restore original IP length in header. */
12692 	packet_size = (uint32_t)msgdsize(mp);
12693 	if (packet_size > IP_MAXPACKET) {
12694 		freemsg(mp);
12695 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12696 		return (B_FALSE);
12697 	}
12698 
12699 	if (DB_REF(mp) > 1) {
12700 		mblk_t *mp2 = copymsg(mp);
12701 
12702 		freemsg(mp);
12703 		if (mp2 == NULL) {
12704 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12705 			return (B_FALSE);
12706 		}
12707 		mp = mp2;
12708 	}
12709 	ipha = (ipha_t *)mp->b_rptr;
12710 
12711 	ipha->ipha_length = htons((uint16_t)packet_size);
12712 	/* We're now complete, zip the frag state */
12713 	ipha->ipha_fragment_offset_and_flags = 0;
12714 	/* Record the ECN info. */
12715 	ipha->ipha_type_of_service &= 0xFC;
12716 	ipha->ipha_type_of_service |= ecn_info;
12717 	*mpp = mp;
12718 
12719 	/* Reassembly is successful; return checksum information if needed */
12720 	if (cksum_val != NULL)
12721 		*cksum_val = sum_val;
12722 	if (cksum_flags != NULL)
12723 		*cksum_flags = sum_flags;
12724 
12725 	return (B_TRUE);
12726 }
12727 
12728 /*
12729  * Perform ip header check sum update local options.
12730  * return B_TRUE if all is well, else return B_FALSE and release
12731  * the mp. caller is responsible for decrementing ire ref cnt.
12732  */
12733 static boolean_t
12734 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12735     ip_stack_t *ipst)
12736 {
12737 	mblk_t		*first_mp;
12738 	boolean_t	mctl_present;
12739 	uint16_t	sum;
12740 
12741 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12742 	/*
12743 	 * Don't do the checksum if it has gone through AH/ESP
12744 	 * processing.
12745 	 */
12746 	if (!mctl_present) {
12747 		sum = ip_csum_hdr(ipha);
12748 		if (sum != 0) {
12749 			if (ill != NULL) {
12750 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12751 			} else {
12752 				BUMP_MIB(&ipst->ips_ip_mib,
12753 				    ipIfStatsInCksumErrs);
12754 			}
12755 			freemsg(first_mp);
12756 			return (B_FALSE);
12757 		}
12758 	}
12759 
12760 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12761 		if (mctl_present)
12762 			freeb(first_mp);
12763 		return (B_FALSE);
12764 	}
12765 
12766 	return (B_TRUE);
12767 }
12768 
12769 /*
12770  * All udp packet are delivered to the local host via this routine.
12771  */
12772 void
12773 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12774     ill_t *recv_ill)
12775 {
12776 	uint32_t	sum;
12777 	uint32_t	u1;
12778 	boolean_t	mctl_present;
12779 	conn_t		*connp;
12780 	mblk_t		*first_mp;
12781 	uint16_t	*up;
12782 	ill_t		*ill = (ill_t *)q->q_ptr;
12783 	uint16_t	reass_hck_flags = 0;
12784 	ip_stack_t	*ipst;
12785 
12786 	ASSERT(recv_ill != NULL);
12787 	ipst = recv_ill->ill_ipst;
12788 
12789 #define	rptr    ((uchar_t *)ipha)
12790 
12791 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12792 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12793 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12794 	ASSERT(ill != NULL);
12795 
12796 	/*
12797 	 * FAST PATH for udp packets
12798 	 */
12799 
12800 	/* u1 is # words of IP options */
12801 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12802 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12803 
12804 	/* IP options present */
12805 	if (u1 != 0)
12806 		goto ipoptions;
12807 
12808 	/* Check the IP header checksum.  */
12809 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12810 		/* Clear the IP header h/w cksum flag */
12811 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12812 	} else if (!mctl_present) {
12813 		/*
12814 		 * Don't verify header checksum if this packet is coming
12815 		 * back from AH/ESP as we already did it.
12816 		 */
12817 #define	uph	((uint16_t *)ipha)
12818 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12819 		    uph[6] + uph[7] + uph[8] + uph[9];
12820 #undef	uph
12821 		/* finish doing IP checksum */
12822 		sum = (sum & 0xFFFF) + (sum >> 16);
12823 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12824 		if (sum != 0 && sum != 0xFFFF) {
12825 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12826 			freemsg(first_mp);
12827 			return;
12828 		}
12829 	}
12830 
12831 	/*
12832 	 * Count for SNMP of inbound packets for ire.
12833 	 * if mctl is present this might be a secure packet and
12834 	 * has already been counted for in ip_proto_input().
12835 	 */
12836 	if (!mctl_present) {
12837 		UPDATE_IB_PKT_COUNT(ire);
12838 		ire->ire_last_used_time = lbolt;
12839 	}
12840 
12841 	/* packet part of fragmented IP packet? */
12842 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12843 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12844 		goto fragmented;
12845 	}
12846 
12847 	/* u1 = IP header length (20 bytes) */
12848 	u1 = IP_SIMPLE_HDR_LENGTH;
12849 
12850 	/* packet does not contain complete IP & UDP headers */
12851 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12852 		goto udppullup;
12853 
12854 	/* up points to UDP header */
12855 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12856 #define	iphs    ((uint16_t *)ipha)
12857 
12858 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12859 	if (up[3] != 0) {
12860 		mblk_t *mp1 = mp->b_cont;
12861 		boolean_t cksum_err;
12862 		uint16_t hck_flags = 0;
12863 
12864 		/* Pseudo-header checksum */
12865 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12866 		    iphs[9] + up[2];
12867 
12868 		/*
12869 		 * Revert to software checksum calculation if the interface
12870 		 * isn't capable of checksum offload or if IPsec is present.
12871 		 */
12872 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12873 			hck_flags = DB_CKSUMFLAGS(mp);
12874 
12875 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12876 			IP_STAT(ipst, ip_in_sw_cksum);
12877 
12878 		IP_CKSUM_RECV(hck_flags, u1,
12879 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12880 		    (int32_t)((uchar_t *)up - rptr),
12881 		    mp, mp1, cksum_err);
12882 
12883 		if (cksum_err) {
12884 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12885 			if (hck_flags & HCK_FULLCKSUM)
12886 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12887 			else if (hck_flags & HCK_PARTIALCKSUM)
12888 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12889 			else
12890 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12891 
12892 			freemsg(first_mp);
12893 			return;
12894 		}
12895 	}
12896 
12897 	/* Non-fragmented broadcast or multicast packet? */
12898 	if (ire->ire_type == IRE_BROADCAST)
12899 		goto udpslowpath;
12900 
12901 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12902 	    ire->ire_zoneid, ipst)) != NULL) {
12903 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
12904 		IP_STAT(ipst, ip_udp_fast_path);
12905 
12906 		if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
12907 		    (!IPCL_IS_NONSTR(connp) && CONN_UDP_FLOWCTLD(connp))) {
12908 			freemsg(mp);
12909 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
12910 		} else {
12911 			if (!mctl_present) {
12912 				BUMP_MIB(ill->ill_ip_mib,
12913 				    ipIfStatsHCInDelivers);
12914 			}
12915 			/*
12916 			 * mp and first_mp can change.
12917 			 */
12918 			if (ip_udp_check(q, connp, recv_ill,
12919 			    ipha, &mp, &first_mp, mctl_present, ire)) {
12920 				/* Send it upstream */
12921 				(connp->conn_recv)(connp, mp, NULL);
12922 			}
12923 		}
12924 		/*
12925 		 * freeb() cannot deal with null mblk being passed
12926 		 * in and first_mp can be set to null in the call
12927 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12928 		 */
12929 		if (mctl_present && first_mp != NULL) {
12930 			freeb(first_mp);
12931 		}
12932 		CONN_DEC_REF(connp);
12933 		return;
12934 	}
12935 
12936 	/*
12937 	 * if we got here we know the packet is not fragmented and
12938 	 * has no options. The classifier could not find a conn_t and
12939 	 * most likely its an icmp packet so send it through slow path.
12940 	 */
12941 
12942 	goto udpslowpath;
12943 
12944 ipoptions:
12945 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
12946 		goto slow_done;
12947 	}
12948 
12949 	UPDATE_IB_PKT_COUNT(ire);
12950 	ire->ire_last_used_time = lbolt;
12951 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12952 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12953 fragmented:
12954 		/*
12955 		 * "sum" and "reass_hck_flags" are non-zero if the
12956 		 * reassembled packet has a valid hardware computed
12957 		 * checksum information associated with it.
12958 		 */
12959 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
12960 			goto slow_done;
12961 		/*
12962 		 * Make sure that first_mp points back to mp as
12963 		 * the mp we came in with could have changed in
12964 		 * ip_rput_fragment().
12965 		 */
12966 		ASSERT(!mctl_present);
12967 		ipha = (ipha_t *)mp->b_rptr;
12968 		first_mp = mp;
12969 	}
12970 
12971 	/* Now we have a complete datagram, destined for this machine. */
12972 	u1 = IPH_HDR_LENGTH(ipha);
12973 	/* Pull up the UDP header, if necessary. */
12974 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12975 udppullup:
12976 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12977 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12978 			freemsg(first_mp);
12979 			goto slow_done;
12980 		}
12981 		ipha = (ipha_t *)mp->b_rptr;
12982 	}
12983 
12984 	/*
12985 	 * Validate the checksum for the reassembled packet; for the
12986 	 * pullup case we calculate the payload checksum in software.
12987 	 */
12988 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12989 	if (up[3] != 0) {
12990 		boolean_t cksum_err;
12991 
12992 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12993 			IP_STAT(ipst, ip_in_sw_cksum);
12994 
12995 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12996 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12997 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12998 		    iphs[9] + up[2], sum, cksum_err);
12999 
13000 		if (cksum_err) {
13001 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
13002 
13003 			if (reass_hck_flags & HCK_FULLCKSUM)
13004 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
13005 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
13006 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
13007 			else
13008 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
13009 
13010 			freemsg(first_mp);
13011 			goto slow_done;
13012 		}
13013 	}
13014 udpslowpath:
13015 
13016 	/* Clear hardware checksum flag to be safe */
13017 	DB_CKSUMFLAGS(mp) = 0;
13018 
13019 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
13020 	    (ire->ire_type == IRE_BROADCAST),
13021 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
13022 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
13023 
13024 slow_done:
13025 	IP_STAT(ipst, ip_udp_slow_path);
13026 	return;
13027 
13028 #undef  iphs
13029 #undef  rptr
13030 }
13031 
13032 /* ARGSUSED */
13033 static mblk_t *
13034 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13035     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
13036     ill_rx_ring_t *ill_ring)
13037 {
13038 	conn_t		*connp;
13039 	uint32_t	sum;
13040 	uint32_t	u1;
13041 	uint16_t	*up;
13042 	int		offset;
13043 	ssize_t		len;
13044 	mblk_t		*mp1;
13045 	boolean_t	syn_present = B_FALSE;
13046 	tcph_t		*tcph;
13047 	uint_t		tcph_flags;
13048 	uint_t		ip_hdr_len;
13049 	ill_t		*ill = (ill_t *)q->q_ptr;
13050 	zoneid_t	zoneid = ire->ire_zoneid;
13051 	boolean_t	cksum_err;
13052 	uint16_t	hck_flags = 0;
13053 	ip_stack_t	*ipst = recv_ill->ill_ipst;
13054 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
13055 
13056 #define	rptr	((uchar_t *)ipha)
13057 
13058 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
13059 	ASSERT(ill != NULL);
13060 
13061 	/*
13062 	 * FAST PATH for tcp packets
13063 	 */
13064 
13065 	/* u1 is # words of IP options */
13066 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13067 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13068 
13069 	/* IP options present */
13070 	if (u1) {
13071 		goto ipoptions;
13072 	} else if (!mctl_present) {
13073 		/* Check the IP header checksum.  */
13074 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
13075 			/* Clear the IP header h/w cksum flag */
13076 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
13077 		} else if (!mctl_present) {
13078 			/*
13079 			 * Don't verify header checksum if this packet
13080 			 * is coming back from AH/ESP as we already did it.
13081 			 */
13082 #define	uph	((uint16_t *)ipha)
13083 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13084 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13085 #undef	uph
13086 			/* finish doing IP checksum */
13087 			sum = (sum & 0xFFFF) + (sum >> 16);
13088 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13089 			if (sum != 0 && sum != 0xFFFF) {
13090 				BUMP_MIB(ill->ill_ip_mib,
13091 				    ipIfStatsInCksumErrs);
13092 				goto error;
13093 			}
13094 		}
13095 	}
13096 
13097 	if (!mctl_present) {
13098 		UPDATE_IB_PKT_COUNT(ire);
13099 		ire->ire_last_used_time = lbolt;
13100 	}
13101 
13102 	/* packet part of fragmented IP packet? */
13103 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13104 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13105 		goto fragmented;
13106 	}
13107 
13108 	/* u1 = IP header length (20 bytes) */
13109 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
13110 
13111 	/* does packet contain IP+TCP headers? */
13112 	len = mp->b_wptr - rptr;
13113 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
13114 		IP_STAT(ipst, ip_tcppullup);
13115 		goto tcppullup;
13116 	}
13117 
13118 	/* TCP options present? */
13119 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
13120 
13121 	/*
13122 	 * If options need to be pulled up, then goto tcpoptions.
13123 	 * otherwise we are still in the fast path
13124 	 */
13125 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
13126 		IP_STAT(ipst, ip_tcpoptions);
13127 		goto tcpoptions;
13128 	}
13129 
13130 	/* multiple mblks of tcp data? */
13131 	if ((mp1 = mp->b_cont) != NULL) {
13132 		/* more then two? */
13133 		if (mp1->b_cont != NULL) {
13134 			IP_STAT(ipst, ip_multipkttcp);
13135 			goto multipkttcp;
13136 		}
13137 		len += mp1->b_wptr - mp1->b_rptr;
13138 	}
13139 
13140 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
13141 
13142 	/* part of pseudo checksum */
13143 
13144 	/* TCP datagram length */
13145 	u1 = len - IP_SIMPLE_HDR_LENGTH;
13146 
13147 #define	iphs    ((uint16_t *)ipha)
13148 
13149 #ifdef	_BIG_ENDIAN
13150 	u1 += IPPROTO_TCP;
13151 #else
13152 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13153 #endif
13154 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13155 
13156 	/*
13157 	 * Revert to software checksum calculation if the interface
13158 	 * isn't capable of checksum offload or if IPsec is present.
13159 	 */
13160 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
13161 		hck_flags = DB_CKSUMFLAGS(mp);
13162 
13163 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13164 		IP_STAT(ipst, ip_in_sw_cksum);
13165 
13166 	IP_CKSUM_RECV(hck_flags, u1,
13167 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
13168 	    (int32_t)((uchar_t *)up - rptr),
13169 	    mp, mp1, cksum_err);
13170 
13171 	if (cksum_err) {
13172 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13173 
13174 		if (hck_flags & HCK_FULLCKSUM)
13175 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
13176 		else if (hck_flags & HCK_PARTIALCKSUM)
13177 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
13178 		else
13179 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
13180 
13181 		goto error;
13182 	}
13183 
13184 try_again:
13185 
13186 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
13187 	    zoneid, ipst)) == NULL) {
13188 		/* Send the TH_RST */
13189 		goto no_conn;
13190 	}
13191 
13192 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
13193 	tcph_flags = tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG);
13194 
13195 	/*
13196 	 * TCP FAST PATH for AF_INET socket.
13197 	 *
13198 	 * TCP fast path to avoid extra work. An AF_INET socket type
13199 	 * does not have facility to receive extra information via
13200 	 * ip_process or ip_add_info. Also, when the connection was
13201 	 * established, we made a check if this connection is impacted
13202 	 * by any global IPsec policy or per connection policy (a
13203 	 * policy that comes in effect later will not apply to this
13204 	 * connection). Since all this can be determined at the
13205 	 * connection establishment time, a quick check of flags
13206 	 * can avoid extra work.
13207 	 */
13208 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13209 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13210 		ASSERT(first_mp == mp);
13211 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13212 		if (tcph_flags != (TH_SYN | TH_ACK)) {
13213 			SET_SQUEUE(mp, tcp_rput_data, connp);
13214 			return (mp);
13215 		}
13216 		mp->b_datap->db_struioflag |= STRUIO_CONNECT;
13217 		DB_CKSUMSTART(mp) = (intptr_t)ip_squeue_get(ill_ring);
13218 		SET_SQUEUE(mp, tcp_input, connp);
13219 		return (mp);
13220 	}
13221 
13222 	if (tcph_flags == TH_SYN) {
13223 		if (IPCL_IS_TCP(connp)) {
13224 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13225 			DB_CKSUMSTART(mp) =
13226 			    (intptr_t)ip_squeue_get(ill_ring);
13227 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13228 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13229 				BUMP_MIB(ill->ill_ip_mib,
13230 				    ipIfStatsHCInDelivers);
13231 				SET_SQUEUE(mp, connp->conn_recv, connp);
13232 				return (mp);
13233 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13234 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13235 				BUMP_MIB(ill->ill_ip_mib,
13236 				    ipIfStatsHCInDelivers);
13237 				ip_squeue_enter_unbound++;
13238 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13239 				    connp);
13240 				return (mp);
13241 			}
13242 			syn_present = B_TRUE;
13243 		}
13244 	}
13245 
13246 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13247 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13248 
13249 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13250 		/* No need to send this packet to TCP */
13251 		if ((flags & TH_RST) || (flags & TH_URG)) {
13252 			CONN_DEC_REF(connp);
13253 			freemsg(first_mp);
13254 			return (NULL);
13255 		}
13256 		if (flags & TH_ACK) {
13257 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
13258 			    ipst->ips_netstack->netstack_tcp, connp);
13259 			CONN_DEC_REF(connp);
13260 			return (NULL);
13261 		}
13262 
13263 		CONN_DEC_REF(connp);
13264 		freemsg(first_mp);
13265 		return (NULL);
13266 	}
13267 
13268 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13269 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13270 		    ipha, NULL, mctl_present);
13271 		if (first_mp == NULL) {
13272 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13273 			CONN_DEC_REF(connp);
13274 			return (NULL);
13275 		}
13276 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13277 			ASSERT(syn_present);
13278 			if (mctl_present) {
13279 				ASSERT(first_mp != mp);
13280 				first_mp->b_datap->db_struioflag |=
13281 				    STRUIO_POLICY;
13282 			} else {
13283 				ASSERT(first_mp == mp);
13284 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13285 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13286 			}
13287 		} else {
13288 			/*
13289 			 * Discard first_mp early since we're dealing with a
13290 			 * fully-connected conn_t and tcp doesn't do policy in
13291 			 * this case.
13292 			 */
13293 			if (mctl_present) {
13294 				freeb(first_mp);
13295 				mctl_present = B_FALSE;
13296 			}
13297 			first_mp = mp;
13298 		}
13299 	}
13300 
13301 	/* Initiate IPPF processing for fastpath */
13302 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13303 		uint32_t	ill_index;
13304 
13305 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13306 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13307 		if (mp == NULL) {
13308 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13309 			    "deferred/dropped during IPPF processing\n"));
13310 			CONN_DEC_REF(connp);
13311 			if (mctl_present)
13312 				freeb(first_mp);
13313 			return (NULL);
13314 		} else if (mctl_present) {
13315 			/*
13316 			 * ip_process might return a new mp.
13317 			 */
13318 			ASSERT(first_mp != mp);
13319 			first_mp->b_cont = mp;
13320 		} else {
13321 			first_mp = mp;
13322 		}
13323 
13324 	}
13325 
13326 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13327 		/*
13328 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13329 		 * make sure IPF_RECVIF is passed to ip_add_info.
13330 		 */
13331 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13332 		    IPCL_ZONEID(connp), ipst);
13333 		if (mp == NULL) {
13334 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13335 			CONN_DEC_REF(connp);
13336 			if (mctl_present)
13337 				freeb(first_mp);
13338 			return (NULL);
13339 		} else if (mctl_present) {
13340 			/*
13341 			 * ip_add_info might return a new mp.
13342 			 */
13343 			ASSERT(first_mp != mp);
13344 			first_mp->b_cont = mp;
13345 		} else {
13346 			first_mp = mp;
13347 		}
13348 	}
13349 
13350 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13351 	if (IPCL_IS_TCP(connp)) {
13352 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13353 		return (first_mp);
13354 	} else {
13355 		/* SOCK_RAW, IPPROTO_TCP case */
13356 		(connp->conn_recv)(connp, first_mp, NULL);
13357 		CONN_DEC_REF(connp);
13358 		return (NULL);
13359 	}
13360 
13361 no_conn:
13362 	/* Initiate IPPf processing, if needed. */
13363 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13364 		uint32_t ill_index;
13365 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13366 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13367 		if (first_mp == NULL) {
13368 			return (NULL);
13369 		}
13370 	}
13371 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13372 
13373 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13374 	    ipst->ips_netstack->netstack_tcp, NULL);
13375 	return (NULL);
13376 ipoptions:
13377 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13378 		goto slow_done;
13379 	}
13380 
13381 	UPDATE_IB_PKT_COUNT(ire);
13382 	ire->ire_last_used_time = lbolt;
13383 
13384 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13385 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13386 fragmented:
13387 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
13388 			if (mctl_present)
13389 				freeb(first_mp);
13390 			goto slow_done;
13391 		}
13392 		/*
13393 		 * Make sure that first_mp points back to mp as
13394 		 * the mp we came in with could have changed in
13395 		 * ip_rput_fragment().
13396 		 */
13397 		ASSERT(!mctl_present);
13398 		ipha = (ipha_t *)mp->b_rptr;
13399 		first_mp = mp;
13400 	}
13401 
13402 	/* Now we have a complete datagram, destined for this machine. */
13403 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13404 
13405 	len = mp->b_wptr - mp->b_rptr;
13406 	/* Pull up a minimal TCP header, if necessary. */
13407 	if (len < (u1 + 20)) {
13408 tcppullup:
13409 		if (!pullupmsg(mp, u1 + 20)) {
13410 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13411 			goto error;
13412 		}
13413 		ipha = (ipha_t *)mp->b_rptr;
13414 		len = mp->b_wptr - mp->b_rptr;
13415 	}
13416 
13417 	/*
13418 	 * Extract the offset field from the TCP header.  As usual, we
13419 	 * try to help the compiler more than the reader.
13420 	 */
13421 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13422 	if (offset != 5) {
13423 tcpoptions:
13424 		if (offset < 5) {
13425 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13426 			goto error;
13427 		}
13428 		/*
13429 		 * There must be TCP options.
13430 		 * Make sure we can grab them.
13431 		 */
13432 		offset <<= 2;
13433 		offset += u1;
13434 		if (len < offset) {
13435 			if (!pullupmsg(mp, offset)) {
13436 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13437 				goto error;
13438 			}
13439 			ipha = (ipha_t *)mp->b_rptr;
13440 			len = mp->b_wptr - rptr;
13441 		}
13442 	}
13443 
13444 	/* Get the total packet length in len, including headers. */
13445 	if (mp->b_cont) {
13446 multipkttcp:
13447 		len = msgdsize(mp);
13448 	}
13449 
13450 	/*
13451 	 * Check the TCP checksum by pulling together the pseudo-
13452 	 * header checksum, and passing it to ip_csum to be added in
13453 	 * with the TCP datagram.
13454 	 *
13455 	 * Since we are not using the hwcksum if available we must
13456 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13457 	 * If either of these fails along the way the mblk is freed.
13458 	 * If this logic ever changes and mblk is reused to say send
13459 	 * ICMP's back, then this flag may need to be cleared in
13460 	 * other places as well.
13461 	 */
13462 	DB_CKSUMFLAGS(mp) = 0;
13463 
13464 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13465 
13466 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13467 #ifdef	_BIG_ENDIAN
13468 	u1 += IPPROTO_TCP;
13469 #else
13470 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13471 #endif
13472 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13473 	/*
13474 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13475 	 */
13476 	IP_STAT(ipst, ip_in_sw_cksum);
13477 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13478 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13479 		goto error;
13480 	}
13481 
13482 	IP_STAT(ipst, ip_tcp_slow_path);
13483 	goto try_again;
13484 #undef  iphs
13485 #undef  rptr
13486 
13487 error:
13488 	freemsg(first_mp);
13489 slow_done:
13490 	return (NULL);
13491 }
13492 
13493 /* ARGSUSED */
13494 static void
13495 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13496     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13497 {
13498 	conn_t		*connp;
13499 	uint32_t	sum;
13500 	uint32_t	u1;
13501 	ssize_t		len;
13502 	sctp_hdr_t	*sctph;
13503 	zoneid_t	zoneid = ire->ire_zoneid;
13504 	uint32_t	pktsum;
13505 	uint32_t	calcsum;
13506 	uint32_t	ports;
13507 	in6_addr_t	map_src, map_dst;
13508 	ill_t		*ill = (ill_t *)q->q_ptr;
13509 	ip_stack_t	*ipst;
13510 	sctp_stack_t	*sctps;
13511 	boolean_t	sctp_csum_err = B_FALSE;
13512 
13513 	ASSERT(recv_ill != NULL);
13514 	ipst = recv_ill->ill_ipst;
13515 	sctps = ipst->ips_netstack->netstack_sctp;
13516 
13517 #define	rptr	((uchar_t *)ipha)
13518 
13519 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13520 	ASSERT(ill != NULL);
13521 
13522 	/* u1 is # words of IP options */
13523 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13524 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13525 
13526 	/* IP options present */
13527 	if (u1 > 0) {
13528 		goto ipoptions;
13529 	} else {
13530 		/* Check the IP header checksum.  */
13531 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill) &&
13532 		    !mctl_present) {
13533 #define	uph	((uint16_t *)ipha)
13534 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13535 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13536 #undef	uph
13537 			/* finish doing IP checksum */
13538 			sum = (sum & 0xFFFF) + (sum >> 16);
13539 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13540 			/*
13541 			 * Don't verify header checksum if this packet
13542 			 * is coming back from AH/ESP as we already did it.
13543 			 */
13544 			if (sum != 0 && sum != 0xFFFF) {
13545 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13546 				goto error;
13547 			}
13548 		}
13549 		/*
13550 		 * Since there is no SCTP h/w cksum support yet, just
13551 		 * clear the flag.
13552 		 */
13553 		DB_CKSUMFLAGS(mp) = 0;
13554 	}
13555 
13556 	/*
13557 	 * Don't verify header checksum if this packet is coming
13558 	 * back from AH/ESP as we already did it.
13559 	 */
13560 	if (!mctl_present) {
13561 		UPDATE_IB_PKT_COUNT(ire);
13562 		ire->ire_last_used_time = lbolt;
13563 	}
13564 
13565 	/* packet part of fragmented IP packet? */
13566 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13567 	if (u1 & (IPH_MF | IPH_OFFSET))
13568 		goto fragmented;
13569 
13570 	/* u1 = IP header length (20 bytes) */
13571 	u1 = IP_SIMPLE_HDR_LENGTH;
13572 
13573 find_sctp_client:
13574 	/* Pullup if we don't have the sctp common header. */
13575 	len = MBLKL(mp);
13576 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13577 		if (mp->b_cont == NULL ||
13578 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13579 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13580 			goto error;
13581 		}
13582 		ipha = (ipha_t *)mp->b_rptr;
13583 		len = MBLKL(mp);
13584 	}
13585 
13586 	sctph = (sctp_hdr_t *)(rptr + u1);
13587 #ifdef	DEBUG
13588 	if (!skip_sctp_cksum) {
13589 #endif
13590 		pktsum = sctph->sh_chksum;
13591 		sctph->sh_chksum = 0;
13592 		calcsum = sctp_cksum(mp, u1);
13593 		sctph->sh_chksum = pktsum;
13594 		if (calcsum != pktsum)
13595 			sctp_csum_err = B_TRUE;
13596 #ifdef	DEBUG	/* skip_sctp_cksum */
13597 	}
13598 #endif
13599 	/* get the ports */
13600 	ports = *(uint32_t *)&sctph->sh_sport;
13601 
13602 	IRE_REFRELE(ire);
13603 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13604 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13605 	if (sctp_csum_err) {
13606 		/*
13607 		 * No potential sctp checksum errors go to the Sun
13608 		 * sctp stack however they might be Adler-32 summed
13609 		 * packets a userland stack bound to a raw IP socket
13610 		 * could reasonably use. Note though that Adler-32 is
13611 		 * a long deprecated algorithm and customer sctp
13612 		 * networks should eventually migrate to CRC-32 at
13613 		 * which time this facility should be removed.
13614 		 */
13615 		flags |= IP_FF_SCTP_CSUM_ERR;
13616 		goto no_conn;
13617 	}
13618 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13619 	    sctps)) == NULL) {
13620 		/* Check for raw socket or OOTB handling */
13621 		goto no_conn;
13622 	}
13623 
13624 	/* Found a client; up it goes */
13625 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13626 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13627 	return;
13628 
13629 no_conn:
13630 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13631 	    ports, mctl_present, flags, B_TRUE, zoneid);
13632 	return;
13633 
13634 ipoptions:
13635 	DB_CKSUMFLAGS(mp) = 0;
13636 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13637 		goto slow_done;
13638 
13639 	UPDATE_IB_PKT_COUNT(ire);
13640 	ire->ire_last_used_time = lbolt;
13641 
13642 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13643 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13644 fragmented:
13645 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
13646 			goto slow_done;
13647 		/*
13648 		 * Make sure that first_mp points back to mp as
13649 		 * the mp we came in with could have changed in
13650 		 * ip_rput_fragment().
13651 		 */
13652 		ASSERT(!mctl_present);
13653 		ipha = (ipha_t *)mp->b_rptr;
13654 		first_mp = mp;
13655 	}
13656 
13657 	/* Now we have a complete datagram, destined for this machine. */
13658 	u1 = IPH_HDR_LENGTH(ipha);
13659 	goto find_sctp_client;
13660 #undef  iphs
13661 #undef  rptr
13662 
13663 error:
13664 	freemsg(first_mp);
13665 slow_done:
13666 	IRE_REFRELE(ire);
13667 }
13668 
13669 #define	VER_BITS	0xF0
13670 #define	VERSION_6	0x60
13671 
13672 static boolean_t
13673 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13674     ipaddr_t *dstp, ip_stack_t *ipst)
13675 {
13676 	uint_t	opt_len;
13677 	ipha_t *ipha;
13678 	ssize_t len;
13679 	uint_t	pkt_len;
13680 
13681 	ASSERT(ill != NULL);
13682 	IP_STAT(ipst, ip_ipoptions);
13683 	ipha = *iphapp;
13684 
13685 #define	rptr    ((uchar_t *)ipha)
13686 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13687 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13688 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13689 		freemsg(mp);
13690 		return (B_FALSE);
13691 	}
13692 
13693 	/* multiple mblk or too short */
13694 	pkt_len = ntohs(ipha->ipha_length);
13695 
13696 	/* Get the number of words of IP options in the IP header. */
13697 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13698 	if (opt_len) {
13699 		/* IP Options present!  Validate and process. */
13700 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13701 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13702 			goto done;
13703 		}
13704 		/*
13705 		 * Recompute complete header length and make sure we
13706 		 * have access to all of it.
13707 		 */
13708 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13709 		if (len > (mp->b_wptr - rptr)) {
13710 			if (len > pkt_len) {
13711 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13712 				goto done;
13713 			}
13714 			if (!pullupmsg(mp, len)) {
13715 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13716 				goto done;
13717 			}
13718 			ipha = (ipha_t *)mp->b_rptr;
13719 		}
13720 		/*
13721 		 * Go off to ip_rput_options which returns the next hop
13722 		 * destination address, which may have been affected
13723 		 * by source routing.
13724 		 */
13725 		IP_STAT(ipst, ip_opt);
13726 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13727 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13728 			return (B_FALSE);
13729 		}
13730 	}
13731 	*iphapp = ipha;
13732 	return (B_TRUE);
13733 done:
13734 	/* clear b_prev - used by ip_mroute_decap */
13735 	mp->b_prev = NULL;
13736 	freemsg(mp);
13737 	return (B_FALSE);
13738 #undef  rptr
13739 }
13740 
13741 /*
13742  * Deal with the fact that there is no ire for the destination.
13743  */
13744 static ire_t *
13745 ip_rput_noire(queue_t *q, mblk_t *mp, int ll_multicast, ipaddr_t dst)
13746 {
13747 	ipha_t	*ipha;
13748 	ill_t	*ill;
13749 	ire_t	*ire;
13750 	ip_stack_t *ipst;
13751 	enum	ire_forward_action ret_action;
13752 
13753 	ipha = (ipha_t *)mp->b_rptr;
13754 	ill = (ill_t *)q->q_ptr;
13755 
13756 	ASSERT(ill != NULL);
13757 	ipst = ill->ill_ipst;
13758 
13759 	/*
13760 	 * No IRE for this destination, so it can't be for us.
13761 	 * Unless we are forwarding, drop the packet.
13762 	 * We have to let source routed packets through
13763 	 * since we don't yet know if they are 'ping -l'
13764 	 * packets i.e. if they will go out over the
13765 	 * same interface as they came in on.
13766 	 */
13767 	if (ll_multicast) {
13768 		freemsg(mp);
13769 		return (NULL);
13770 	}
13771 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13772 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13773 		freemsg(mp);
13774 		return (NULL);
13775 	}
13776 
13777 	/*
13778 	 * Mark this packet as having originated externally.
13779 	 *
13780 	 * For non-forwarding code path, ire_send later double
13781 	 * checks this interface to see if it is still exists
13782 	 * post-ARP resolution.
13783 	 *
13784 	 * Also, IPQOS uses this to differentiate between
13785 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13786 	 * QOS packet processing in ip_wput_attach_llhdr().
13787 	 * The QoS module can mark the b_band for a fastpath message
13788 	 * or the dl_priority field in a unitdata_req header for
13789 	 * CoS marking. This info can only be found in
13790 	 * ip_wput_attach_llhdr().
13791 	 */
13792 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13793 	/*
13794 	 * Clear the indication that this may have a hardware checksum
13795 	 * as we are not using it
13796 	 */
13797 	DB_CKSUMFLAGS(mp) = 0;
13798 
13799 	ire = ire_forward(dst, &ret_action, NULL, NULL,
13800 	    MBLK_GETLABEL(mp), ipst);
13801 
13802 	if (ire == NULL && ret_action == Forward_check_multirt) {
13803 		/* Let ip_newroute handle CGTP  */
13804 		ip_newroute(q, mp, dst, NULL, GLOBAL_ZONEID, ipst);
13805 		return (NULL);
13806 	}
13807 
13808 	if (ire != NULL)
13809 		return (ire);
13810 
13811 	mp->b_prev = mp->b_next = 0;
13812 
13813 	if (ret_action == Forward_blackhole) {
13814 		freemsg(mp);
13815 		return (NULL);
13816 	}
13817 	/* send icmp unreachable */
13818 	q = WR(q);
13819 	/* Sent by forwarding path, and router is global zone */
13820 	if (ip_source_routed(ipha, ipst)) {
13821 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13822 		    GLOBAL_ZONEID, ipst);
13823 	} else {
13824 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13825 		    ipst);
13826 	}
13827 
13828 	return (NULL);
13829 
13830 }
13831 
13832 /*
13833  * check ip header length and align it.
13834  */
13835 static boolean_t
13836 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13837 {
13838 	ssize_t len;
13839 	ill_t *ill;
13840 	ipha_t	*ipha;
13841 
13842 	len = MBLKL(mp);
13843 
13844 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13845 		ill = (ill_t *)q->q_ptr;
13846 
13847 		if (!OK_32PTR(mp->b_rptr))
13848 			IP_STAT(ipst, ip_notaligned1);
13849 		else
13850 			IP_STAT(ipst, ip_notaligned2);
13851 		/* Guard against bogus device drivers */
13852 		if (len < 0) {
13853 			/* clear b_prev - used by ip_mroute_decap */
13854 			mp->b_prev = NULL;
13855 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13856 			freemsg(mp);
13857 			return (B_FALSE);
13858 		}
13859 
13860 		if (ip_rput_pullups++ == 0) {
13861 			ipha = (ipha_t *)mp->b_rptr;
13862 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13863 			    "ip_check_and_align_header: %s forced us to "
13864 			    " pullup pkt, hdr len %ld, hdr addr %p",
13865 			    ill->ill_name, len, (void *)ipha);
13866 		}
13867 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13868 			/* clear b_prev - used by ip_mroute_decap */
13869 			mp->b_prev = NULL;
13870 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13871 			freemsg(mp);
13872 			return (B_FALSE);
13873 		}
13874 	}
13875 	return (B_TRUE);
13876 }
13877 
13878 ire_t *
13879 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13880 {
13881 	ire_t		*new_ire;
13882 	ill_t		*ire_ill;
13883 	uint_t		ifindex;
13884 	ip_stack_t	*ipst = ill->ill_ipst;
13885 	boolean_t	strict_check = B_FALSE;
13886 
13887 	/*
13888 	 * This packet came in on an interface other than the one associated
13889 	 * with the first ire we found for the destination address. We do
13890 	 * another ire lookup here, using the ingress ill, to see if the
13891 	 * interface is in an interface group.
13892 	 * As long as the ills belong to the same group, we don't consider
13893 	 * them to be arriving on the wrong interface. Thus, if the switch
13894 	 * is doing inbound load spreading, we won't drop packets when the
13895 	 * ip*_strict_dst_multihoming switch is on. Note, the same holds true
13896 	 * for 'usesrc groups' where the destination address may belong to
13897 	 * another interface to allow multipathing to happen.
13898 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
13899 	 * where the local address may not be unique. In this case we were
13900 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
13901 	 * actually returned. The new lookup, which is more specific, should
13902 	 * only find the IRE_LOCAL associated with the ingress ill if one
13903 	 * exists.
13904 	 */
13905 
13906 	if (ire->ire_ipversion == IPV4_VERSION) {
13907 		if (ipst->ips_ip_strict_dst_multihoming)
13908 			strict_check = B_TRUE;
13909 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
13910 		    ill->ill_ipif, ALL_ZONES, NULL,
13911 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13912 	} else {
13913 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
13914 		if (ipst->ips_ipv6_strict_dst_multihoming)
13915 			strict_check = B_TRUE;
13916 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
13917 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
13918 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13919 	}
13920 	/*
13921 	 * If the same ire that was returned in ip_input() is found then this
13922 	 * is an indication that interface groups are in use. The packet
13923 	 * arrived on a different ill in the group than the one associated with
13924 	 * the destination address.  If a different ire was found then the same
13925 	 * IP address must be hosted on multiple ills. This is possible with
13926 	 * unnumbered point2point interfaces. We switch to use this new ire in
13927 	 * order to have accurate interface statistics.
13928 	 */
13929 	if (new_ire != NULL) {
13930 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
13931 			ire_refrele(ire);
13932 			ire = new_ire;
13933 		} else {
13934 			ire_refrele(new_ire);
13935 		}
13936 		return (ire);
13937 	} else if ((ire->ire_rfq == NULL) &&
13938 	    (ire->ire_ipversion == IPV4_VERSION)) {
13939 		/*
13940 		 * The best match could have been the original ire which
13941 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
13942 		 * the strict multihoming checks are irrelevant as we consider
13943 		 * local addresses hosted on lo0 to be interface agnostic. We
13944 		 * only expect a null ire_rfq on IREs which are associated with
13945 		 * lo0 hence we can return now.
13946 		 */
13947 		return (ire);
13948 	}
13949 
13950 	/*
13951 	 * Chase pointers once and store locally.
13952 	 */
13953 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
13954 	    (ill_t *)(ire->ire_rfq->q_ptr);
13955 	ifindex = ill->ill_usesrc_ifindex;
13956 
13957 	/*
13958 	 * Check if it's a legal address on the 'usesrc' interface.
13959 	 */
13960 	if ((ifindex != 0) && (ire_ill != NULL) &&
13961 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
13962 		return (ire);
13963 	}
13964 
13965 	/*
13966 	 * If the ip*_strict_dst_multihoming switch is on then we can
13967 	 * only accept this packet if the interface is marked as routing.
13968 	 */
13969 	if (!(strict_check))
13970 		return (ire);
13971 
13972 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
13973 	    ILLF_ROUTER) != 0) {
13974 		return (ire);
13975 	}
13976 
13977 	ire_refrele(ire);
13978 	return (NULL);
13979 }
13980 
13981 /*
13982  *
13983  * This is the fast forward path. If we are here, we dont need to
13984  * worry about RSVP, CGTP, or TSol. Furthermore the ftable lookup
13985  * needed to find the nexthop in this case is much simpler
13986  */
13987 ire_t *
13988 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13989 {
13990 	ipha_t	*ipha;
13991 	ire_t	*src_ire;
13992 	ill_t	*stq_ill;
13993 	uint_t	hlen;
13994 	uint_t	pkt_len;
13995 	uint32_t sum;
13996 	queue_t	*dev_q;
13997 	ip_stack_t *ipst = ill->ill_ipst;
13998 	mblk_t *fpmp;
13999 	enum	ire_forward_action ret_action;
14000 
14001 	ipha = (ipha_t *)mp->b_rptr;
14002 
14003 	if (ire != NULL &&
14004 	    ire->ire_zoneid != GLOBAL_ZONEID &&
14005 	    ire->ire_zoneid != ALL_ZONES) {
14006 		/*
14007 		 * Should only use IREs that are visible to the global
14008 		 * zone for forwarding.
14009 		 */
14010 		ire_refrele(ire);
14011 		ire = ire_cache_lookup(dst, GLOBAL_ZONEID, NULL, ipst);
14012 		/*
14013 		 * ire_cache_lookup() can return ire of IRE_LOCAL in
14014 		 * transient cases. In such case, just drop the packet
14015 		 */
14016 		if (ire->ire_type != IRE_CACHE)
14017 			goto drop;
14018 	}
14019 
14020 	/*
14021 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
14022 	 * The loopback address check for both src and dst has already
14023 	 * been checked in ip_input
14024 	 */
14025 
14026 	if (dst == INADDR_ANY || CLASSD(ipha->ipha_src)) {
14027 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14028 		goto drop;
14029 	}
14030 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14031 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14032 
14033 	if (src_ire != NULL) {
14034 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14035 		ire_refrele(src_ire);
14036 		goto drop;
14037 	}
14038 
14039 	/* No ire cache of nexthop. So first create one  */
14040 	if (ire == NULL) {
14041 
14042 		ire = ire_forward_simple(dst, &ret_action, ipst);
14043 
14044 		/*
14045 		 * We only come to ip_fast_forward if ip_cgtp_filter
14046 		 * is not set. So ire_forward() should not return with
14047 		 * Forward_check_multirt as the next action.
14048 		 */
14049 		ASSERT(ret_action != Forward_check_multirt);
14050 		if (ire == NULL) {
14051 			/* An attempt was made to forward the packet */
14052 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14053 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14054 			mp->b_prev = mp->b_next = 0;
14055 			/* send icmp unreachable */
14056 			/* Sent by forwarding path, and router is global zone */
14057 			if (ret_action == Forward_ret_icmp_err) {
14058 				if (ip_source_routed(ipha, ipst)) {
14059 					icmp_unreachable(ill->ill_wq, mp,
14060 					    ICMP_SOURCE_ROUTE_FAILED,
14061 					    GLOBAL_ZONEID, ipst);
14062 				} else {
14063 					icmp_unreachable(ill->ill_wq, mp,
14064 					    ICMP_HOST_UNREACHABLE,
14065 					    GLOBAL_ZONEID, ipst);
14066 				}
14067 			} else {
14068 				freemsg(mp);
14069 			}
14070 			return (NULL);
14071 		}
14072 	}
14073 
14074 	/*
14075 	 * Forwarding fastpath exception case:
14076 	 * If either of the follwoing case is true, we take
14077 	 * the slowpath
14078 	 *	o forwarding is not enabled
14079 	 *	o incoming and outgoing interface are the same, or the same
14080 	 *	  IPMP group
14081 	 *	o corresponding ire is in incomplete state
14082 	 *	o packet needs fragmentation
14083 	 *	o ARP cache is not resolved
14084 	 *
14085 	 * The codeflow from here on is thus:
14086 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
14087 	 */
14088 	pkt_len = ntohs(ipha->ipha_length);
14089 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
14090 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
14091 	    (ill == stq_ill) ||
14092 	    (ill->ill_group != NULL && ill->ill_group == stq_ill->ill_group) ||
14093 	    (ire->ire_nce == NULL) ||
14094 	    (pkt_len > ire->ire_max_frag) ||
14095 	    ((fpmp = ire->ire_nce->nce_fp_mp) == NULL) ||
14096 	    ((hlen = MBLKL(fpmp)) > MBLKHEAD(mp)) ||
14097 	    ipha->ipha_ttl <= 1) {
14098 		ip_rput_process_forward(ill->ill_rq, mp, ire,
14099 		    ipha, ill, B_FALSE, B_TRUE);
14100 		return (ire);
14101 	}
14102 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14103 
14104 	DTRACE_PROBE4(ip4__forwarding__start,
14105 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
14106 
14107 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
14108 	    ipst->ips_ipv4firewall_forwarding,
14109 	    ill, stq_ill, ipha, mp, mp, 0, ipst);
14110 
14111 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
14112 
14113 	if (mp == NULL)
14114 		goto drop;
14115 
14116 	mp->b_datap->db_struioun.cksum.flags = 0;
14117 	/* Adjust the checksum to reflect the ttl decrement. */
14118 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
14119 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
14120 	ipha->ipha_ttl--;
14121 
14122 	/*
14123 	 * Write the link layer header.  We can do this safely here,
14124 	 * because we have already tested to make sure that the IP
14125 	 * policy is not set, and that we have a fast path destination
14126 	 * header.
14127 	 */
14128 	mp->b_rptr -= hlen;
14129 	bcopy(fpmp->b_rptr, mp->b_rptr, hlen);
14130 
14131 	UPDATE_IB_PKT_COUNT(ire);
14132 	ire->ire_last_used_time = lbolt;
14133 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
14134 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14135 	UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets, pkt_len);
14136 
14137 	if (!ILL_DIRECT_CAPABLE(stq_ill) || DB_TYPE(mp) != M_DATA) {
14138 		dev_q = ire->ire_stq->q_next;
14139 		if (DEV_Q_FLOW_BLOCKED(dev_q))
14140 			goto indiscard;
14141 	}
14142 
14143 	DTRACE_PROBE4(ip4__physical__out__start,
14144 	    ill_t *, NULL, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
14145 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
14146 	    ipst->ips_ipv4firewall_physical_out,
14147 	    NULL, stq_ill, ipha, mp, mp, 0, ipst);
14148 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
14149 	DTRACE_IP7(send, mblk_t *, mp, conn_t *, NULL, void_ip_t *,
14150 	    ipha, __dtrace_ipsr_ill_t *, stq_ill, ipha_t *, ipha,
14151 	    ip6_t *, NULL, int, 0);
14152 
14153 	if (mp != NULL) {
14154 		if (ipst->ips_ipobs_enabled) {
14155 			zoneid_t szone;
14156 
14157 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
14158 			    ipst, ALL_ZONES);
14159 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
14160 			    ALL_ZONES, ill, IPV4_VERSION, hlen, ipst);
14161 		}
14162 
14163 		ILL_SEND_TX(stq_ill, ire, dst, mp, IP_DROP_ON_NO_DESC);
14164 	}
14165 	return (ire);
14166 
14167 indiscard:
14168 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14169 drop:
14170 	if (mp != NULL)
14171 		freemsg(mp);
14172 	return (ire);
14173 
14174 }
14175 
14176 /*
14177  * This function is called in the forwarding slowpath, when
14178  * either the ire lacks the link-layer address, or the packet needs
14179  * further processing(eg. fragmentation), before transmission.
14180  */
14181 
14182 static void
14183 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14184     ill_t *ill, boolean_t ll_multicast, boolean_t from_ip_fast_forward)
14185 {
14186 	ill_group_t	*ill_group;
14187 	ill_group_t	*ire_group;
14188 	queue_t		*dev_q;
14189 	ire_t		*src_ire;
14190 	ip_stack_t	*ipst = ill->ill_ipst;
14191 
14192 	ASSERT(ire->ire_stq != NULL);
14193 
14194 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14195 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14196 
14197 	/*
14198 	 * If the caller of this function is ip_fast_forward() skip the
14199 	 * next three checks as it does not apply.
14200 	 */
14201 	if (from_ip_fast_forward) {
14202 		ill_group = ill->ill_group;
14203 		ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
14204 		goto skip;
14205 	}
14206 
14207 	if (ll_multicast != 0) {
14208 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14209 		goto drop_pkt;
14210 	}
14211 
14212 	/*
14213 	 * check if ipha_src is a broadcast address. Note that this
14214 	 * check is redundant when we get here from ip_fast_forward()
14215 	 * which has already done this check. However, since we can
14216 	 * also get here from ip_rput_process_broadcast() or, for
14217 	 * for the slow path through ip_fast_forward(), we perform
14218 	 * the check again for code-reusability
14219 	 */
14220 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14221 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14222 	if (src_ire != NULL || ipha->ipha_dst == INADDR_ANY) {
14223 		if (src_ire != NULL)
14224 			ire_refrele(src_ire);
14225 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14226 		ip2dbg(("ip_rput_process_forward: Received packet with"
14227 		    " bad src/dst address on %s\n", ill->ill_name));
14228 		goto drop_pkt;
14229 	}
14230 
14231 	ill_group = ill->ill_group;
14232 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
14233 	/*
14234 	 * Check if we want to forward this one at this time.
14235 	 * We allow source routed packets on a host provided that
14236 	 * they go out the same interface or same interface group
14237 	 * as they came in on.
14238 	 *
14239 	 * XXX To be quicker, we may wish to not chase pointers to
14240 	 * get the ILLF_ROUTER flag and instead store the
14241 	 * forwarding policy in the ire.  An unfortunate
14242 	 * side-effect of that would be requiring an ire flush
14243 	 * whenever the ILLF_ROUTER flag changes.
14244 	 */
14245 skip:
14246 	if (((ill->ill_flags &
14247 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
14248 	    ILLF_ROUTER) == 0) &&
14249 	    !(ip_source_routed(ipha, ipst) && (ire->ire_rfq == q ||
14250 	    (ill_group != NULL && ill_group == ire_group)))) {
14251 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14252 		if (ip_source_routed(ipha, ipst)) {
14253 			q = WR(q);
14254 			/*
14255 			 * Clear the indication that this may have
14256 			 * hardware checksum as we are not using it.
14257 			 */
14258 			DB_CKSUMFLAGS(mp) = 0;
14259 			/* Sent by forwarding path, and router is global zone */
14260 			icmp_unreachable(q, mp,
14261 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
14262 			return;
14263 		}
14264 		goto drop_pkt;
14265 	}
14266 
14267 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14268 
14269 	/* Packet is being forwarded. Turning off hwcksum flag. */
14270 	DB_CKSUMFLAGS(mp) = 0;
14271 	if (ipst->ips_ip_g_send_redirects) {
14272 		/*
14273 		 * Check whether the incoming interface and outgoing
14274 		 * interface is part of the same group. If so,
14275 		 * send redirects.
14276 		 *
14277 		 * Check the source address to see if it originated
14278 		 * on the same logical subnet it is going back out on.
14279 		 * If so, we should be able to send it a redirect.
14280 		 * Avoid sending a redirect if the destination
14281 		 * is directly connected (i.e., ipha_dst is the same
14282 		 * as ire_gateway_addr or the ire_addr of the
14283 		 * nexthop IRE_CACHE ), or if the packet was source
14284 		 * routed out this interface.
14285 		 */
14286 		ipaddr_t src, nhop;
14287 		mblk_t	*mp1;
14288 		ire_t	*nhop_ire = NULL;
14289 
14290 		/*
14291 		 * Check whether ire_rfq and q are from the same ill
14292 		 * or if they are not same, they at least belong
14293 		 * to the same group. If so, send redirects.
14294 		 */
14295 		if ((ire->ire_rfq == q ||
14296 		    (ill_group != NULL && ill_group == ire_group)) &&
14297 		    !ip_source_routed(ipha, ipst)) {
14298 
14299 			nhop = (ire->ire_gateway_addr != 0 ?
14300 			    ire->ire_gateway_addr : ire->ire_addr);
14301 
14302 			if (ipha->ipha_dst == nhop) {
14303 				/*
14304 				 * We avoid sending a redirect if the
14305 				 * destination is directly connected
14306 				 * because it is possible that multiple
14307 				 * IP subnets may have been configured on
14308 				 * the link, and the source may not
14309 				 * be on the same subnet as ip destination,
14310 				 * even though they are on the same
14311 				 * physical link.
14312 				 */
14313 				goto sendit;
14314 			}
14315 
14316 			src = ipha->ipha_src;
14317 
14318 			/*
14319 			 * We look up the interface ire for the nexthop,
14320 			 * to see if ipha_src is in the same subnet
14321 			 * as the nexthop.
14322 			 *
14323 			 * Note that, if, in the future, IRE_CACHE entries
14324 			 * are obsoleted,  this lookup will not be needed,
14325 			 * as the ire passed to this function will be the
14326 			 * same as the nhop_ire computed below.
14327 			 */
14328 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14329 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14330 			    0, NULL, MATCH_IRE_TYPE, ipst);
14331 
14332 			if (nhop_ire != NULL) {
14333 				if ((src & nhop_ire->ire_mask) ==
14334 				    (nhop & nhop_ire->ire_mask)) {
14335 					/*
14336 					 * The source is directly connected.
14337 					 * Just copy the ip header (which is
14338 					 * in the first mblk)
14339 					 */
14340 					mp1 = copyb(mp);
14341 					if (mp1 != NULL) {
14342 						icmp_send_redirect(WR(q), mp1,
14343 						    nhop, ipst);
14344 					}
14345 				}
14346 				ire_refrele(nhop_ire);
14347 			}
14348 		}
14349 	}
14350 sendit:
14351 	dev_q = ire->ire_stq->q_next;
14352 	if (DEV_Q_FLOW_BLOCKED(dev_q)) {
14353 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14354 		freemsg(mp);
14355 		return;
14356 	}
14357 
14358 	ip_rput_forward(ire, ipha, mp, ill);
14359 	return;
14360 
14361 drop_pkt:
14362 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14363 	freemsg(mp);
14364 }
14365 
14366 ire_t *
14367 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14368     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14369 {
14370 	queue_t		*q;
14371 	uint16_t	hcksumflags;
14372 	ip_stack_t	*ipst = ill->ill_ipst;
14373 
14374 	q = *qp;
14375 
14376 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14377 
14378 	/*
14379 	 * Clear the indication that this may have hardware
14380 	 * checksum as we are not using it for forwarding.
14381 	 */
14382 	hcksumflags = DB_CKSUMFLAGS(mp);
14383 	DB_CKSUMFLAGS(mp) = 0;
14384 
14385 	/*
14386 	 * Directed broadcast forwarding: if the packet came in over a
14387 	 * different interface then it is routed out over we can forward it.
14388 	 */
14389 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14390 		ire_refrele(ire);
14391 		freemsg(mp);
14392 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14393 		return (NULL);
14394 	}
14395 	/*
14396 	 * For multicast we have set dst to be INADDR_BROADCAST
14397 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
14398 	 * only for broadcast packets.
14399 	 */
14400 	if (!CLASSD(ipha->ipha_dst)) {
14401 		ire_t *new_ire;
14402 		ipif_t *ipif;
14403 		/*
14404 		 * For ill groups, as the switch duplicates broadcasts
14405 		 * across all the ports, we need to filter out and
14406 		 * send up only one copy. There is one copy for every
14407 		 * broadcast address on each ill. Thus, we look for a
14408 		 * specific IRE on this ill and look at IRE_MARK_NORECV
14409 		 * later to see whether this ill is eligible to receive
14410 		 * them or not. ill_nominate_bcast_rcv() nominates only
14411 		 * one set of IREs for receiving.
14412 		 */
14413 
14414 		ipif = ipif_get_next_ipif(NULL, ill);
14415 		if (ipif == NULL) {
14416 			ire_refrele(ire);
14417 			freemsg(mp);
14418 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14419 			return (NULL);
14420 		}
14421 		new_ire = ire_ctable_lookup(dst, 0, 0,
14422 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14423 		ipif_refrele(ipif);
14424 
14425 		if (new_ire != NULL) {
14426 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
14427 				ire_refrele(ire);
14428 				ire_refrele(new_ire);
14429 				freemsg(mp);
14430 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14431 				return (NULL);
14432 			}
14433 			/*
14434 			 * In the special case of multirouted broadcast
14435 			 * packets, we unconditionally need to "gateway"
14436 			 * them to the appropriate interface here.
14437 			 * In the normal case, this cannot happen, because
14438 			 * there is no broadcast IRE tagged with the
14439 			 * RTF_MULTIRT flag.
14440 			 */
14441 			if (new_ire->ire_flags & RTF_MULTIRT) {
14442 				ire_refrele(new_ire);
14443 				if (ire->ire_rfq != NULL) {
14444 					q = ire->ire_rfq;
14445 					*qp = q;
14446 				}
14447 			} else {
14448 				ire_refrele(ire);
14449 				ire = new_ire;
14450 			}
14451 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14452 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14453 				/*
14454 				 * Free the message if
14455 				 * ip_g_forward_directed_bcast is turned
14456 				 * off for non-local broadcast.
14457 				 */
14458 				ire_refrele(ire);
14459 				freemsg(mp);
14460 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14461 				return (NULL);
14462 			}
14463 		} else {
14464 			/*
14465 			 * This CGTP packet successfully passed the
14466 			 * CGTP filter, but the related CGTP
14467 			 * broadcast IRE has not been found,
14468 			 * meaning that the redundant ipif is
14469 			 * probably down. However, if we discarded
14470 			 * this packet, its duplicate would be
14471 			 * filtered out by the CGTP filter so none
14472 			 * of them would get through. So we keep
14473 			 * going with this one.
14474 			 */
14475 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14476 			if (ire->ire_rfq != NULL) {
14477 				q = ire->ire_rfq;
14478 				*qp = q;
14479 			}
14480 		}
14481 	}
14482 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14483 		/*
14484 		 * Verify that there are not more then one
14485 		 * IRE_BROADCAST with this broadcast address which
14486 		 * has ire_stq set.
14487 		 * TODO: simplify, loop over all IRE's
14488 		 */
14489 		ire_t	*ire1;
14490 		int	num_stq = 0;
14491 		mblk_t	*mp1;
14492 
14493 		/* Find the first one with ire_stq set */
14494 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14495 		for (ire1 = ire; ire1 &&
14496 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14497 		    ire1 = ire1->ire_next)
14498 			;
14499 		if (ire1) {
14500 			ire_refrele(ire);
14501 			ire = ire1;
14502 			IRE_REFHOLD(ire);
14503 		}
14504 
14505 		/* Check if there are additional ones with stq set */
14506 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14507 			if (ire->ire_addr != ire1->ire_addr)
14508 				break;
14509 			if (ire1->ire_stq) {
14510 				num_stq++;
14511 				break;
14512 			}
14513 		}
14514 		rw_exit(&ire->ire_bucket->irb_lock);
14515 		if (num_stq == 1 && ire->ire_stq != NULL) {
14516 			ip1dbg(("ip_rput_process_broadcast: directed "
14517 			    "broadcast to 0x%x\n",
14518 			    ntohl(ire->ire_addr)));
14519 			mp1 = copymsg(mp);
14520 			if (mp1) {
14521 				switch (ipha->ipha_protocol) {
14522 				case IPPROTO_UDP:
14523 					ip_udp_input(q, mp1, ipha, ire, ill);
14524 					break;
14525 				default:
14526 					ip_proto_input(q, mp1, ipha, ire, ill,
14527 					    0);
14528 					break;
14529 				}
14530 			}
14531 			/*
14532 			 * Adjust ttl to 2 (1+1 - the forward engine
14533 			 * will decrement it by one.
14534 			 */
14535 			if (ip_csum_hdr(ipha)) {
14536 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14537 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14538 				freemsg(mp);
14539 				ire_refrele(ire);
14540 				return (NULL);
14541 			}
14542 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14543 			ipha->ipha_hdr_checksum = 0;
14544 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14545 			ip_rput_process_forward(q, mp, ire, ipha,
14546 			    ill, ll_multicast, B_FALSE);
14547 			ire_refrele(ire);
14548 			return (NULL);
14549 		}
14550 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14551 		    ntohl(ire->ire_addr)));
14552 	}
14553 
14554 
14555 	/* Restore any hardware checksum flags */
14556 	DB_CKSUMFLAGS(mp) = hcksumflags;
14557 	return (ire);
14558 }
14559 
14560 /* ARGSUSED */
14561 static boolean_t
14562 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14563     int *ll_multicast, ipaddr_t *dstp)
14564 {
14565 	ip_stack_t	*ipst = ill->ill_ipst;
14566 
14567 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14568 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14569 	    ntohs(ipha->ipha_length));
14570 
14571 	/*
14572 	 * Forward packets only if we have joined the allmulti
14573 	 * group on this interface.
14574 	 */
14575 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14576 		int retval;
14577 
14578 		/*
14579 		 * Clear the indication that this may have hardware
14580 		 * checksum as we are not using it.
14581 		 */
14582 		DB_CKSUMFLAGS(mp) = 0;
14583 		retval = ip_mforward(ill, ipha, mp);
14584 		/* ip_mforward updates mib variables if needed */
14585 		/* clear b_prev - used by ip_mroute_decap */
14586 		mp->b_prev = NULL;
14587 
14588 		switch (retval) {
14589 		case 0:
14590 			/*
14591 			 * pkt is okay and arrived on phyint.
14592 			 *
14593 			 * If we are running as a multicast router
14594 			 * we need to see all IGMP and/or PIM packets.
14595 			 */
14596 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14597 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14598 				goto done;
14599 			}
14600 			break;
14601 		case -1:
14602 			/* pkt is mal-formed, toss it */
14603 			goto drop_pkt;
14604 		case 1:
14605 			/* pkt is okay and arrived on a tunnel */
14606 			/*
14607 			 * If we are running a multicast router
14608 			 *  we need to see all igmp packets.
14609 			 */
14610 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14611 				*dstp = INADDR_BROADCAST;
14612 				*ll_multicast = 1;
14613 				return (B_FALSE);
14614 			}
14615 
14616 			goto drop_pkt;
14617 		}
14618 	}
14619 
14620 	ILM_WALKER_HOLD(ill);
14621 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14622 		/*
14623 		 * This might just be caused by the fact that
14624 		 * multiple IP Multicast addresses map to the same
14625 		 * link layer multicast - no need to increment counter!
14626 		 */
14627 		ILM_WALKER_RELE(ill);
14628 		freemsg(mp);
14629 		return (B_TRUE);
14630 	}
14631 	ILM_WALKER_RELE(ill);
14632 done:
14633 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14634 	/*
14635 	 * This assumes the we deliver to all streams for multicast
14636 	 * and broadcast packets.
14637 	 */
14638 	*dstp = INADDR_BROADCAST;
14639 	*ll_multicast = 1;
14640 	return (B_FALSE);
14641 drop_pkt:
14642 	ip2dbg(("ip_rput: drop pkt\n"));
14643 	freemsg(mp);
14644 	return (B_TRUE);
14645 }
14646 
14647 /*
14648  * This function is used to both return an indication of whether or not
14649  * the packet received is a non-unicast packet (by way of the DL_UNITDATA_IND)
14650  * and in doing so, determine whether or not it is broadcast vs multicast.
14651  * For it to be a broadcast packet, we must have the appropriate mblk_t
14652  * hanging off the ill_t.  If this is either not present or doesn't match
14653  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
14654  * to be multicast.  Thus NICs that have no broadcast address (or no
14655  * capability for one, such as point to point links) cannot return as
14656  * the packet being broadcast.  The use of HPE_BROADCAST/HPE_MULTICAST as
14657  * the return values simplifies the current use of the return value of this
14658  * function, which is to pass through the multicast/broadcast characteristic
14659  * to consumers of the netinfo/pfhooks API.  While this is not cast in stone,
14660  * changing the return value to some other symbol demands the appropriate
14661  * "translation" when hpe_flags is set prior to calling hook_run() for
14662  * packet events.
14663  */
14664 int
14665 ip_get_dlpi_mbcast(ill_t *ill, mblk_t *mb)
14666 {
14667 	dl_unitdata_ind_t *ind = (dl_unitdata_ind_t *)mb->b_rptr;
14668 	mblk_t *bmp;
14669 
14670 	if (ind->dl_group_address) {
14671 		if (ind->dl_dest_addr_offset > sizeof (*ind) &&
14672 		    ind->dl_dest_addr_offset + ind->dl_dest_addr_length <
14673 		    MBLKL(mb) &&
14674 		    (bmp = ill->ill_bcast_mp) != NULL) {
14675 			dl_unitdata_req_t *dlur;
14676 			uint8_t *bphys_addr;
14677 
14678 			dlur = (dl_unitdata_req_t *)bmp->b_rptr;
14679 			if (ill->ill_sap_length < 0)
14680 				bphys_addr = (uchar_t *)dlur +
14681 				    dlur->dl_dest_addr_offset;
14682 			else
14683 				bphys_addr = (uchar_t *)dlur +
14684 				    dlur->dl_dest_addr_offset +
14685 				    ill->ill_sap_length;
14686 
14687 			if (bcmp(mb->b_rptr + ind->dl_dest_addr_offset,
14688 			    bphys_addr, ind->dl_dest_addr_length) == 0) {
14689 				return (HPE_BROADCAST);
14690 			}
14691 			return (HPE_MULTICAST);
14692 		}
14693 		return (HPE_MULTICAST);
14694 	}
14695 	return (0);
14696 }
14697 
14698 static boolean_t
14699 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14700     int *ll_multicast, mblk_t **mpp)
14701 {
14702 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14703 	boolean_t must_copy = B_FALSE;
14704 	struct iocblk   *iocp;
14705 	ipha_t		*ipha;
14706 	ip_stack_t	*ipst = ill->ill_ipst;
14707 
14708 #define	rptr    ((uchar_t *)ipha)
14709 
14710 	first_mp = *first_mpp;
14711 	mp = *mpp;
14712 
14713 	ASSERT(first_mp == mp);
14714 
14715 	/*
14716 	 * if db_ref > 1 then copymsg and free original. Packet may be
14717 	 * changed and do not want other entity who has a reference to this
14718 	 * message to trip over the changes. This is a blind change because
14719 	 * trying to catch all places that might change packet is too
14720 	 * difficult (since it may be a module above this one)
14721 	 *
14722 	 * This corresponds to the non-fast path case. We walk down the full
14723 	 * chain in this case, and check the db_ref count of all the dblks,
14724 	 * and do a copymsg if required. It is possible that the db_ref counts
14725 	 * of the data blocks in the mblk chain can be different.
14726 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14727 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14728 	 * 'snoop' is running.
14729 	 */
14730 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14731 		if (mp1->b_datap->db_ref > 1) {
14732 			must_copy = B_TRUE;
14733 			break;
14734 		}
14735 	}
14736 
14737 	if (must_copy) {
14738 		mp1 = copymsg(mp);
14739 		if (mp1 == NULL) {
14740 			for (mp1 = mp; mp1 != NULL;
14741 			    mp1 = mp1->b_cont) {
14742 				mp1->b_next = NULL;
14743 				mp1->b_prev = NULL;
14744 			}
14745 			freemsg(mp);
14746 			if (ill != NULL) {
14747 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14748 			} else {
14749 				BUMP_MIB(&ipst->ips_ip_mib,
14750 				    ipIfStatsInDiscards);
14751 			}
14752 			return (B_TRUE);
14753 		}
14754 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14755 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14756 			/* Copy b_prev - used by ip_mroute_decap */
14757 			to_mp->b_prev = from_mp->b_prev;
14758 			from_mp->b_prev = NULL;
14759 		}
14760 		*first_mpp = first_mp = mp1;
14761 		freemsg(mp);
14762 		mp = mp1;
14763 		*mpp = mp1;
14764 	}
14765 
14766 	ipha = (ipha_t *)mp->b_rptr;
14767 
14768 	/*
14769 	 * previous code has a case for M_DATA.
14770 	 * We want to check how that happens.
14771 	 */
14772 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14773 	switch (first_mp->b_datap->db_type) {
14774 	case M_PROTO:
14775 	case M_PCPROTO:
14776 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14777 		    DL_UNITDATA_IND) {
14778 			/* Go handle anything other than data elsewhere. */
14779 			ip_rput_dlpi(q, mp);
14780 			return (B_TRUE);
14781 		}
14782 
14783 		*ll_multicast = ip_get_dlpi_mbcast(ill, mp);
14784 		/* Ditch the DLPI header. */
14785 		mp1 = mp->b_cont;
14786 		ASSERT(first_mp == mp);
14787 		*first_mpp = mp1;
14788 		freeb(mp);
14789 		*mpp = mp1;
14790 		return (B_FALSE);
14791 	case M_IOCACK:
14792 		ip1dbg(("got iocack "));
14793 		iocp = (struct iocblk *)mp->b_rptr;
14794 		switch (iocp->ioc_cmd) {
14795 		case DL_IOC_HDR_INFO:
14796 			ill = (ill_t *)q->q_ptr;
14797 			ill_fastpath_ack(ill, mp);
14798 			return (B_TRUE);
14799 		case SIOCSTUNPARAM:
14800 		case OSIOCSTUNPARAM:
14801 			/* Go through qwriter_ip */
14802 			break;
14803 		case SIOCGTUNPARAM:
14804 		case OSIOCGTUNPARAM:
14805 			ip_rput_other(NULL, q, mp, NULL);
14806 			return (B_TRUE);
14807 		default:
14808 			putnext(q, mp);
14809 			return (B_TRUE);
14810 		}
14811 		/* FALLTHRU */
14812 	case M_ERROR:
14813 	case M_HANGUP:
14814 		/*
14815 		 * Since this is on the ill stream we unconditionally
14816 		 * bump up the refcount
14817 		 */
14818 		ill_refhold(ill);
14819 		qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14820 		return (B_TRUE);
14821 	case M_CTL:
14822 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14823 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14824 		    IPHADA_M_CTL)) {
14825 			/*
14826 			 * It's an IPsec accelerated packet.
14827 			 * Make sure that the ill from which we received the
14828 			 * packet has enabled IPsec hardware acceleration.
14829 			 */
14830 			if (!(ill->ill_capabilities &
14831 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14832 				/* IPsec kstats: bean counter */
14833 				freemsg(mp);
14834 				return (B_TRUE);
14835 			}
14836 
14837 			/*
14838 			 * Make mp point to the mblk following the M_CTL,
14839 			 * then process according to type of mp.
14840 			 * After this processing, first_mp will point to
14841 			 * the data-attributes and mp to the pkt following
14842 			 * the M_CTL.
14843 			 */
14844 			mp = first_mp->b_cont;
14845 			if (mp == NULL) {
14846 				freemsg(first_mp);
14847 				return (B_TRUE);
14848 			}
14849 			/*
14850 			 * A Hardware Accelerated packet can only be M_DATA
14851 			 * ESP or AH packet.
14852 			 */
14853 			if (mp->b_datap->db_type != M_DATA) {
14854 				/* non-M_DATA IPsec accelerated packet */
14855 				IPSECHW_DEBUG(IPSECHW_PKT,
14856 				    ("non-M_DATA IPsec accelerated pkt\n"));
14857 				freemsg(first_mp);
14858 				return (B_TRUE);
14859 			}
14860 			ipha = (ipha_t *)mp->b_rptr;
14861 			if (ipha->ipha_protocol != IPPROTO_AH &&
14862 			    ipha->ipha_protocol != IPPROTO_ESP) {
14863 				IPSECHW_DEBUG(IPSECHW_PKT,
14864 				    ("non-M_DATA IPsec accelerated pkt\n"));
14865 				freemsg(first_mp);
14866 				return (B_TRUE);
14867 			}
14868 			*mpp = mp;
14869 			return (B_FALSE);
14870 		}
14871 		putnext(q, mp);
14872 		return (B_TRUE);
14873 	case M_IOCNAK:
14874 		ip1dbg(("got iocnak "));
14875 		iocp = (struct iocblk *)mp->b_rptr;
14876 		switch (iocp->ioc_cmd) {
14877 		case SIOCSTUNPARAM:
14878 		case OSIOCSTUNPARAM:
14879 			/*
14880 			 * Since this is on the ill stream we unconditionally
14881 			 * bump up the refcount
14882 			 */
14883 			ill_refhold(ill);
14884 			qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14885 			return (B_TRUE);
14886 		case DL_IOC_HDR_INFO:
14887 		case SIOCGTUNPARAM:
14888 		case OSIOCGTUNPARAM:
14889 			ip_rput_other(NULL, q, mp, NULL);
14890 			return (B_TRUE);
14891 		default:
14892 			break;
14893 		}
14894 		/* FALLTHRU */
14895 	default:
14896 		putnext(q, mp);
14897 		return (B_TRUE);
14898 	}
14899 }
14900 
14901 /* Read side put procedure.  Packets coming from the wire arrive here. */
14902 void
14903 ip_rput(queue_t *q, mblk_t *mp)
14904 {
14905 	ill_t	*ill;
14906 	union DL_primitives *dl;
14907 
14908 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14909 
14910 	ill = (ill_t *)q->q_ptr;
14911 
14912 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14913 		/*
14914 		 * If things are opening or closing, only accept high-priority
14915 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
14916 		 * created; on close, things hanging off the ill may have been
14917 		 * freed already.)
14918 		 */
14919 		dl = (union DL_primitives *)mp->b_rptr;
14920 		if (DB_TYPE(mp) != M_PCPROTO ||
14921 		    dl->dl_primitive == DL_UNITDATA_IND) {
14922 			/*
14923 			 * SIOC[GS]TUNPARAM ioctls can come here.
14924 			 */
14925 			inet_freemsg(mp);
14926 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14927 			    "ip_rput_end: q %p (%S)", q, "uninit");
14928 			return;
14929 		}
14930 	}
14931 
14932 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14933 	    "ip_rput_end: q %p (%S)", q, "end");
14934 
14935 	ip_input(ill, NULL, mp, NULL);
14936 }
14937 
14938 static mblk_t *
14939 ip_fix_dbref(ill_t *ill, mblk_t *mp)
14940 {
14941 	mblk_t *mp1;
14942 	boolean_t adjusted = B_FALSE;
14943 	ip_stack_t *ipst = ill->ill_ipst;
14944 
14945 	IP_STAT(ipst, ip_db_ref);
14946 	/*
14947 	 * The IP_RECVSLLA option depends on having the
14948 	 * link layer header. First check that:
14949 	 * a> the underlying device is of type ether,
14950 	 * since this option is currently supported only
14951 	 * over ethernet.
14952 	 * b> there is enough room to copy over the link
14953 	 * layer header.
14954 	 *
14955 	 * Once the checks are done, adjust rptr so that
14956 	 * the link layer header will be copied via
14957 	 * copymsg. Note that, IFT_ETHER may be returned
14958 	 * by some non-ethernet drivers but in this case
14959 	 * the second check will fail.
14960 	 */
14961 	if (ill->ill_type == IFT_ETHER &&
14962 	    (mp->b_rptr - mp->b_datap->db_base) >=
14963 	    sizeof (struct ether_header)) {
14964 		mp->b_rptr -= sizeof (struct ether_header);
14965 		adjusted = B_TRUE;
14966 	}
14967 	mp1 = copymsg(mp);
14968 
14969 	if (mp1 == NULL) {
14970 		mp->b_next = NULL;
14971 		/* clear b_prev - used by ip_mroute_decap */
14972 		mp->b_prev = NULL;
14973 		freemsg(mp);
14974 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14975 		return (NULL);
14976 	}
14977 
14978 	if (adjusted) {
14979 		/*
14980 		 * Copy is done. Restore the pointer in
14981 		 * the _new_ mblk
14982 		 */
14983 		mp1->b_rptr += sizeof (struct ether_header);
14984 	}
14985 
14986 	/* Copy b_prev - used by ip_mroute_decap */
14987 	mp1->b_prev = mp->b_prev;
14988 	mp->b_prev = NULL;
14989 
14990 	/* preserve the hardware checksum flags and data, if present */
14991 	if (DB_CKSUMFLAGS(mp) != 0) {
14992 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
14993 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
14994 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
14995 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
14996 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
14997 	}
14998 
14999 	freemsg(mp);
15000 	return (mp1);
15001 }
15002 
15003 #define	ADD_TO_CHAIN(head, tail, cnt, mp) {    			\
15004 	if (tail != NULL)					\
15005 		tail->b_next = mp;				\
15006 	else							\
15007 		head = mp;					\
15008 	tail = mp;						\
15009 	cnt++;							\
15010 }
15011 
15012 /*
15013  * Direct read side procedure capable of dealing with chains. GLDv3 based
15014  * drivers call this function directly with mblk chains while STREAMS
15015  * read side procedure ip_rput() calls this for single packet with ip_ring
15016  * set to NULL to process one packet at a time.
15017  *
15018  * The ill will always be valid if this function is called directly from
15019  * the driver.
15020  *
15021  * If ip_input() is called from GLDv3:
15022  *
15023  *   - This must be a non-VLAN IP stream.
15024  *   - 'mp' is either an untagged or a special priority-tagged packet.
15025  *   - Any VLAN tag that was in the MAC header has been stripped.
15026  *
15027  * If the IP header in packet is not 32-bit aligned, every message in the
15028  * chain will be aligned before further operations. This is required on SPARC
15029  * platform.
15030  */
15031 /* ARGSUSED */
15032 void
15033 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
15034     struct mac_header_info_s *mhip)
15035 {
15036 	ipaddr_t		dst = NULL;
15037 	ipaddr_t		prev_dst;
15038 	ire_t			*ire = NULL;
15039 	ipha_t			*ipha;
15040 	uint_t			pkt_len;
15041 	ssize_t			len;
15042 	uint_t			opt_len;
15043 	int			ll_multicast;
15044 	int			cgtp_flt_pkt;
15045 	queue_t			*q = ill->ill_rq;
15046 	squeue_t		*curr_sqp = NULL;
15047 	mblk_t 			*head = NULL;
15048 	mblk_t			*tail = NULL;
15049 	mblk_t			*first_mp;
15050 	int			cnt = 0;
15051 	ip_stack_t		*ipst = ill->ill_ipst;
15052 	mblk_t			*mp;
15053 	mblk_t			*dmp;
15054 	uint8_t			tag;
15055 
15056 	ASSERT(mp_chain != NULL);
15057 	ASSERT(ill != NULL);
15058 
15059 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
15060 
15061 	tag = (ip_ring != NULL) ? SQTAG_IP_INPUT_RX_RING : SQTAG_IP_INPUT;
15062 
15063 #define	rptr	((uchar_t *)ipha)
15064 
15065 	while (mp_chain != NULL) {
15066 		mp = mp_chain;
15067 		mp_chain = mp_chain->b_next;
15068 		mp->b_next = NULL;
15069 		ll_multicast = 0;
15070 
15071 		/*
15072 		 * We do ire caching from one iteration to
15073 		 * another. In the event the packet chain contains
15074 		 * all packets from the same dst, this caching saves
15075 		 * an ire_cache_lookup for each of the succeeding
15076 		 * packets in a packet chain.
15077 		 */
15078 		prev_dst = dst;
15079 
15080 		/*
15081 		 * if db_ref > 1 then copymsg and free original. Packet
15082 		 * may be changed and we do not want the other entity
15083 		 * who has a reference to this message to trip over the
15084 		 * changes. This is a blind change because trying to
15085 		 * catch all places that might change the packet is too
15086 		 * difficult.
15087 		 *
15088 		 * This corresponds to the fast path case, where we have
15089 		 * a chain of M_DATA mblks.  We check the db_ref count
15090 		 * of only the 1st data block in the mblk chain. There
15091 		 * doesn't seem to be a reason why a device driver would
15092 		 * send up data with varying db_ref counts in the mblk
15093 		 * chain. In any case the Fast path is a private
15094 		 * interface, and our drivers don't do such a thing.
15095 		 * Given the above assumption, there is no need to walk
15096 		 * down the entire mblk chain (which could have a
15097 		 * potential performance problem)
15098 		 *
15099 		 * The "(DB_REF(mp) > 1)" check was moved from ip_rput()
15100 		 * to here because of exclusive ip stacks and vnics.
15101 		 * Packets transmitted from exclusive stack over vnic
15102 		 * can have db_ref > 1 and when it gets looped back to
15103 		 * another vnic in a different zone, you have ip_input()
15104 		 * getting dblks with db_ref > 1. So if someone
15105 		 * complains of TCP performance under this scenario,
15106 		 * take a serious look here on the impact of copymsg().
15107 		 */
15108 
15109 		if (DB_REF(mp) > 1) {
15110 			if ((mp = ip_fix_dbref(ill, mp)) == NULL)
15111 				continue;
15112 		}
15113 
15114 		/*
15115 		 * Check and align the IP header.
15116 		 */
15117 		first_mp = mp;
15118 		if (DB_TYPE(mp) == M_DATA) {
15119 			dmp = mp;
15120 		} else if (DB_TYPE(mp) == M_PROTO &&
15121 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
15122 			dmp = mp->b_cont;
15123 		} else {
15124 			dmp = NULL;
15125 		}
15126 		if (dmp != NULL) {
15127 			/*
15128 			 * IP header ptr not aligned?
15129 			 * OR IP header not complete in first mblk
15130 			 */
15131 			if (!OK_32PTR(dmp->b_rptr) ||
15132 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
15133 				if (!ip_check_and_align_header(q, dmp, ipst))
15134 					continue;
15135 			}
15136 		}
15137 
15138 		/*
15139 		 * ip_input fast path
15140 		 */
15141 
15142 		/* mblk type is not M_DATA */
15143 		if (DB_TYPE(mp) != M_DATA) {
15144 			if (ip_rput_process_notdata(q, &first_mp, ill,
15145 			    &ll_multicast, &mp))
15146 				continue;
15147 
15148 			/*
15149 			 * The only way we can get here is if we had a
15150 			 * packet that was either a DL_UNITDATA_IND or
15151 			 * an M_CTL for an IPsec accelerated packet.
15152 			 *
15153 			 * In either case, the first_mp will point to
15154 			 * the leading M_PROTO or M_CTL.
15155 			 */
15156 			ASSERT(first_mp != NULL);
15157 		} else if (mhip != NULL) {
15158 			/*
15159 			 * ll_multicast is set here so that it is ready
15160 			 * for easy use with FW_HOOKS().  ip_get_dlpi_mbcast
15161 			 * manipulates ll_multicast in the same fashion when
15162 			 * called from ip_rput_process_notdata.
15163 			 */
15164 			switch (mhip->mhi_dsttype) {
15165 			case MAC_ADDRTYPE_MULTICAST :
15166 				ll_multicast = HPE_MULTICAST;
15167 				break;
15168 			case MAC_ADDRTYPE_BROADCAST :
15169 				ll_multicast = HPE_BROADCAST;
15170 				break;
15171 			default :
15172 				break;
15173 			}
15174 		}
15175 
15176 		/* Only M_DATA can come here and it is always aligned */
15177 		ASSERT(DB_TYPE(mp) == M_DATA);
15178 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
15179 
15180 		ipha = (ipha_t *)mp->b_rptr;
15181 		len = mp->b_wptr - rptr;
15182 		pkt_len = ntohs(ipha->ipha_length);
15183 
15184 		/*
15185 		 * We must count all incoming packets, even if they end
15186 		 * up being dropped later on.
15187 		 */
15188 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15189 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15190 
15191 		/* multiple mblk or too short */
15192 		len -= pkt_len;
15193 		if (len != 0) {
15194 			/*
15195 			 * Make sure we have data length consistent
15196 			 * with the IP header.
15197 			 */
15198 			if (mp->b_cont == NULL) {
15199 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15200 					BUMP_MIB(ill->ill_ip_mib,
15201 					    ipIfStatsInHdrErrors);
15202 					ip2dbg(("ip_input: drop pkt\n"));
15203 					freemsg(mp);
15204 					continue;
15205 				}
15206 				mp->b_wptr = rptr + pkt_len;
15207 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
15208 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15209 					BUMP_MIB(ill->ill_ip_mib,
15210 					    ipIfStatsInHdrErrors);
15211 					ip2dbg(("ip_input: drop pkt\n"));
15212 					freemsg(mp);
15213 					continue;
15214 				}
15215 				(void) adjmsg(mp, -len);
15216 				IP_STAT(ipst, ip_multimblk3);
15217 			}
15218 		}
15219 
15220 		/* Obtain the dst of the current packet */
15221 		dst = ipha->ipha_dst;
15222 
15223 		DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL,
15224 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *,
15225 		    ipha, ip6_t *, NULL, int, 0);
15226 
15227 		/*
15228 		 * The following test for loopback is faster than
15229 		 * IP_LOOPBACK_ADDR(), because it avoids any bitwise
15230 		 * operations.
15231 		 * Note that these addresses are always in network byte order
15232 		 */
15233 		if (((*(uchar_t *)&ipha->ipha_dst) == 127) ||
15234 		    ((*(uchar_t *)&ipha->ipha_src) == 127)) {
15235 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
15236 			freemsg(mp);
15237 			continue;
15238 		}
15239 
15240 		/*
15241 		 * The event for packets being received from a 'physical'
15242 		 * interface is placed after validation of the source and/or
15243 		 * destination address as being local so that packets can be
15244 		 * redirected to loopback addresses using ipnat.
15245 		 */
15246 		DTRACE_PROBE4(ip4__physical__in__start,
15247 		    ill_t *, ill, ill_t *, NULL,
15248 		    ipha_t *, ipha, mblk_t *, first_mp);
15249 
15250 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15251 		    ipst->ips_ipv4firewall_physical_in,
15252 		    ill, NULL, ipha, first_mp, mp, ll_multicast, ipst);
15253 
15254 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
15255 
15256 		if (first_mp == NULL) {
15257 			continue;
15258 		}
15259 		dst = ipha->ipha_dst;
15260 		/*
15261 		 * Attach any necessary label information to
15262 		 * this packet
15263 		 */
15264 		if (is_system_labeled() &&
15265 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
15266 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
15267 			freemsg(mp);
15268 			continue;
15269 		}
15270 
15271 		if (ipst->ips_ipobs_enabled) {
15272 			zoneid_t dzone;
15273 
15274 			/*
15275 			 * On the inbound path the src zone will be unknown as
15276 			 * this packet has come from the wire.
15277 			 */
15278 			dzone = ip_get_zoneid_v4(dst, mp, ipst, ALL_ZONES);
15279 			ipobs_hook(mp, IPOBS_HOOK_INBOUND, ALL_ZONES, dzone,
15280 			    ill, IPV4_VERSION, 0, ipst);
15281 		}
15282 
15283 		/*
15284 		 * Reuse the cached ire only if the ipha_dst of the previous
15285 		 * packet is the same as the current packet AND it is not
15286 		 * INADDR_ANY.
15287 		 */
15288 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15289 		    (ire != NULL)) {
15290 			ire_refrele(ire);
15291 			ire = NULL;
15292 		}
15293 
15294 		opt_len = ipha->ipha_version_and_hdr_length -
15295 		    IP_SIMPLE_HDR_VERSION;
15296 
15297 		/*
15298 		 * Check to see if we can take the fastpath.
15299 		 * That is possible if the following conditions are met
15300 		 *	o Tsol disabled
15301 		 *	o CGTP disabled
15302 		 *	o ipp_action_count is 0
15303 		 *	o no options in the packet
15304 		 *	o not a RSVP packet
15305 		 * 	o not a multicast packet
15306 		 *	o ill not in IP_DHCPINIT_IF mode
15307 		 */
15308 		if (!is_system_labeled() &&
15309 		    !ipst->ips_ip_cgtp_filter && ipp_action_count == 0 &&
15310 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
15311 		    !ll_multicast && !CLASSD(dst) && ill->ill_dhcpinit == 0) {
15312 			if (ire == NULL)
15313 				ire = ire_cache_lookup_simple(dst, ipst);
15314 			/*
15315 			 * Unless forwarding is enabled, dont call
15316 			 * ip_fast_forward(). Incoming packet is for forwarding
15317 			 */
15318 			if ((ill->ill_flags & ILLF_ROUTER) &&
15319 			    (ire == NULL || (ire->ire_type & IRE_CACHE))) {
15320 				ire = ip_fast_forward(ire, dst, ill, mp);
15321 				continue;
15322 			}
15323 			/* incoming packet is for local consumption */
15324 			if ((ire != NULL) && (ire->ire_type & IRE_LOCAL))
15325 				goto local;
15326 		}
15327 
15328 		/*
15329 		 * Disable ire caching for anything more complex
15330 		 * than the simple fast path case we checked for above.
15331 		 */
15332 		if (ire != NULL) {
15333 			ire_refrele(ire);
15334 			ire = NULL;
15335 		}
15336 
15337 		/*
15338 		 * Brutal hack for DHCPv4 unicast: RFC2131 allows a DHCP
15339 		 * server to unicast DHCP packets to a DHCP client using the
15340 		 * IP address it is offering to the client.  This can be
15341 		 * disabled through the "broadcast bit", but not all DHCP
15342 		 * servers honor that bit.  Therefore, to interoperate with as
15343 		 * many DHCP servers as possible, the DHCP client allows the
15344 		 * server to unicast, but we treat those packets as broadcast
15345 		 * here.  Note that we don't rewrite the packet itself since
15346 		 * (a) that would mess up the checksums and (b) the DHCP
15347 		 * client conn is bound to INADDR_ANY so ip_fanout_udp() will
15348 		 * hand it the packet regardless.
15349 		 */
15350 		if (ill->ill_dhcpinit != 0 &&
15351 		    IS_SIMPLE_IPH(ipha) && ipha->ipha_protocol == IPPROTO_UDP &&
15352 		    pullupmsg(mp, sizeof (ipha_t) + sizeof (udpha_t)) == 1) {
15353 			udpha_t *udpha;
15354 
15355 			/*
15356 			 * Reload ipha since pullupmsg() can change b_rptr.
15357 			 */
15358 			ipha = (ipha_t *)mp->b_rptr;
15359 			udpha = (udpha_t *)&ipha[1];
15360 
15361 			if (ntohs(udpha->uha_dst_port) == IPPORT_BOOTPC) {
15362 				DTRACE_PROBE2(ip4__dhcpinit__pkt, ill_t *, ill,
15363 				    mblk_t *, mp);
15364 				dst = INADDR_BROADCAST;
15365 			}
15366 		}
15367 
15368 		/* Full-blown slow path */
15369 		if (opt_len != 0) {
15370 			if (len != 0)
15371 				IP_STAT(ipst, ip_multimblk4);
15372 			else
15373 				IP_STAT(ipst, ip_ipoptions);
15374 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15375 			    &dst, ipst))
15376 				continue;
15377 		}
15378 
15379 		/*
15380 		 * Invoke the CGTP (multirouting) filtering module to process
15381 		 * the incoming packet. Packets identified as duplicates
15382 		 * must be discarded. Filtering is active only if the
15383 		 * the ip_cgtp_filter ndd variable is non-zero.
15384 		 */
15385 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15386 		if (ipst->ips_ip_cgtp_filter &&
15387 		    ipst->ips_ip_cgtp_filter_ops != NULL) {
15388 			netstackid_t stackid;
15389 
15390 			stackid = ipst->ips_netstack->netstack_stackid;
15391 			cgtp_flt_pkt =
15392 			    ipst->ips_ip_cgtp_filter_ops->cfo_filter(stackid,
15393 			    ill->ill_phyint->phyint_ifindex, mp);
15394 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15395 				freemsg(first_mp);
15396 				continue;
15397 			}
15398 		}
15399 
15400 		/*
15401 		 * If rsvpd is running, let RSVP daemon handle its processing
15402 		 * and forwarding of RSVP multicast/unicast packets.
15403 		 * If rsvpd is not running but mrouted is running, RSVP
15404 		 * multicast packets are forwarded as multicast traffic
15405 		 * and RSVP unicast packets are forwarded by unicast router.
15406 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15407 		 * packets are not forwarded, but the unicast packets are
15408 		 * forwarded like unicast traffic.
15409 		 */
15410 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15411 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15412 		    NULL) {
15413 			/* RSVP packet and rsvpd running. Treat as ours */
15414 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15415 			/*
15416 			 * This assumes that we deliver to all streams for
15417 			 * multicast and broadcast packets.
15418 			 * We have to force ll_multicast to 1 to handle the
15419 			 * M_DATA messages passed in from ip_mroute_decap.
15420 			 */
15421 			dst = INADDR_BROADCAST;
15422 			ll_multicast = 1;
15423 		} else if (CLASSD(dst)) {
15424 			/* packet is multicast */
15425 			mp->b_next = NULL;
15426 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15427 			    &ll_multicast, &dst))
15428 				continue;
15429 		}
15430 
15431 		if (ire == NULL) {
15432 			ire = ire_cache_lookup(dst, ALL_ZONES,
15433 			    MBLK_GETLABEL(mp), ipst);
15434 		}
15435 
15436 		if (ire != NULL && ire->ire_stq != NULL &&
15437 		    ire->ire_zoneid != GLOBAL_ZONEID &&
15438 		    ire->ire_zoneid != ALL_ZONES) {
15439 			/*
15440 			 * Should only use IREs that are visible from the
15441 			 * global zone for forwarding.
15442 			 */
15443 			ire_refrele(ire);
15444 			ire = ire_cache_lookup(dst, GLOBAL_ZONEID,
15445 			    MBLK_GETLABEL(mp), ipst);
15446 		}
15447 
15448 		if (ire == NULL) {
15449 			/*
15450 			 * No IRE for this destination, so it can't be for us.
15451 			 * Unless we are forwarding, drop the packet.
15452 			 * We have to let source routed packets through
15453 			 * since we don't yet know if they are 'ping -l'
15454 			 * packets i.e. if they will go out over the
15455 			 * same interface as they came in on.
15456 			 */
15457 			ire = ip_rput_noire(q, mp, ll_multicast, dst);
15458 			if (ire == NULL)
15459 				continue;
15460 		}
15461 
15462 		/*
15463 		 * Broadcast IRE may indicate either broadcast or
15464 		 * multicast packet
15465 		 */
15466 		if (ire->ire_type == IRE_BROADCAST) {
15467 			/*
15468 			 * Skip broadcast checks if packet is UDP multicast;
15469 			 * we'd rather not enter ip_rput_process_broadcast()
15470 			 * unless the packet is broadcast for real, since
15471 			 * that routine is a no-op for multicast.
15472 			 */
15473 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15474 			    !CLASSD(ipha->ipha_dst)) {
15475 				ire = ip_rput_process_broadcast(&q, mp,
15476 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15477 				    ll_multicast);
15478 				if (ire == NULL)
15479 					continue;
15480 			}
15481 		} else if (ire->ire_stq != NULL) {
15482 			/* fowarding? */
15483 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15484 			    ll_multicast, B_FALSE);
15485 			/* ip_rput_process_forward consumed the packet */
15486 			continue;
15487 		}
15488 
15489 local:
15490 		/*
15491 		 * If the queue in the ire is different to the ingress queue
15492 		 * then we need to check to see if we can accept the packet.
15493 		 * Note that for multicast packets and broadcast packets sent
15494 		 * to a broadcast address which is shared between multiple
15495 		 * interfaces we should not do this since we just got a random
15496 		 * broadcast ire.
15497 		 */
15498 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15499 			if ((ire = ip_check_multihome(&ipha->ipha_dst, ire,
15500 			    ill)) == NULL) {
15501 				/* Drop packet */
15502 				BUMP_MIB(ill->ill_ip_mib,
15503 				    ipIfStatsForwProhibits);
15504 				freemsg(mp);
15505 				continue;
15506 			}
15507 			if (ire->ire_rfq != NULL)
15508 				q = ire->ire_rfq;
15509 		}
15510 
15511 		switch (ipha->ipha_protocol) {
15512 		case IPPROTO_TCP:
15513 			ASSERT(first_mp == mp);
15514 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15515 			    mp, 0, q, ip_ring)) != NULL) {
15516 				if (curr_sqp == NULL) {
15517 					curr_sqp = GET_SQUEUE(mp);
15518 					ASSERT(cnt == 0);
15519 					cnt++;
15520 					head = tail = mp;
15521 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15522 					ASSERT(tail != NULL);
15523 					cnt++;
15524 					tail->b_next = mp;
15525 					tail = mp;
15526 				} else {
15527 					/*
15528 					 * A different squeue. Send the
15529 					 * chain for the previous squeue on
15530 					 * its way. This shouldn't happen
15531 					 * often unless interrupt binding
15532 					 * changes.
15533 					 */
15534 					IP_STAT(ipst, ip_input_multi_squeue);
15535 					SQUEUE_ENTER(curr_sqp, head,
15536 					    tail, cnt, SQ_PROCESS, tag);
15537 					curr_sqp = GET_SQUEUE(mp);
15538 					head = mp;
15539 					tail = mp;
15540 					cnt = 1;
15541 				}
15542 			}
15543 			continue;
15544 		case IPPROTO_UDP:
15545 			ASSERT(first_mp == mp);
15546 			ip_udp_input(q, mp, ipha, ire, ill);
15547 			continue;
15548 		case IPPROTO_SCTP:
15549 			ASSERT(first_mp == mp);
15550 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15551 			    q, dst);
15552 			/* ire has been released by ip_sctp_input */
15553 			ire = NULL;
15554 			continue;
15555 		default:
15556 			ip_proto_input(q, first_mp, ipha, ire, ill, 0);
15557 			continue;
15558 		}
15559 	}
15560 
15561 	if (ire != NULL)
15562 		ire_refrele(ire);
15563 
15564 	if (head != NULL)
15565 		SQUEUE_ENTER(curr_sqp, head, tail, cnt, SQ_PROCESS, tag);
15566 
15567 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15568 	    "ip_input_end: q %p (%S)", q, "end");
15569 #undef  rptr
15570 }
15571 
15572 /*
15573  * ip_accept_tcp() - This function is called by the squeue when it retrieves
15574  * a chain of packets in the poll mode. The packets have gone through the
15575  * data link processing but not IP processing. For performance and latency
15576  * reasons, the squeue wants to process the chain in line instead of feeding
15577  * it back via ip_input path.
15578  *
15579  * So this is a light weight function which checks to see if the packets
15580  * retrived are indeed TCP packets (TCP squeue always polls TCP soft ring
15581  * but we still do the paranoid check) meant for local machine and we don't
15582  * have labels etc enabled. Packets that meet the criterion are returned to
15583  * the squeue and processed inline while the rest go via ip_input path.
15584  */
15585 /*ARGSUSED*/
15586 mblk_t *
15587 ip_accept_tcp(ill_t *ill, ill_rx_ring_t *ip_ring, squeue_t *target_sqp,
15588     mblk_t *mp_chain, mblk_t **last, uint_t *cnt)
15589 {
15590 	mblk_t 		*mp;
15591 	ipaddr_t	dst = NULL;
15592 	ipaddr_t	prev_dst;
15593 	ire_t		*ire = NULL;
15594 	ipha_t		*ipha;
15595 	uint_t		pkt_len;
15596 	ssize_t		len;
15597 	uint_t		opt_len;
15598 	queue_t		*q = ill->ill_rq;
15599 	squeue_t	*curr_sqp;
15600 	mblk_t 		*ahead = NULL;	/* Accepted head */
15601 	mblk_t		*atail = NULL;	/* Accepted tail */
15602 	uint_t		acnt = 0;	/* Accepted count */
15603 	mblk_t		*utail = NULL;	/* Unaccepted head */
15604 	mblk_t		*uhead = NULL;	/* Unaccepted tail */
15605 	uint_t		ucnt = 0;	/* Unaccepted cnt */
15606 	ip_stack_t	*ipst = ill->ill_ipst;
15607 
15608 	*cnt = 0;
15609 
15610 	ASSERT(ill != NULL);
15611 	ASSERT(ip_ring != NULL);
15612 
15613 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_accept_tcp: q %p", q);
15614 
15615 #define	rptr	((uchar_t *)ipha)
15616 
15617 	while (mp_chain != NULL) {
15618 		mp = mp_chain;
15619 		mp_chain = mp_chain->b_next;
15620 		mp->b_next = NULL;
15621 
15622 		/*
15623 		 * We do ire caching from one iteration to
15624 		 * another. In the event the packet chain contains
15625 		 * all packets from the same dst, this caching saves
15626 		 * an ire_cache_lookup for each of the succeeding
15627 		 * packets in a packet chain.
15628 		 */
15629 		prev_dst = dst;
15630 
15631 		ipha = (ipha_t *)mp->b_rptr;
15632 		len = mp->b_wptr - rptr;
15633 
15634 		ASSERT(!MBLK_RX_FANOUT_SLOWPATH(mp, ipha));
15635 
15636 		/*
15637 		 * If it is a non TCP packet, or doesn't have H/W cksum,
15638 		 * or doesn't have min len, reject.
15639 		 */
15640 		if ((ipha->ipha_protocol != IPPROTO_TCP) || (len <
15641 		    (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH))) {
15642 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15643 			continue;
15644 		}
15645 
15646 		pkt_len = ntohs(ipha->ipha_length);
15647 		if (len != pkt_len) {
15648 			if (len > pkt_len) {
15649 				mp->b_wptr = rptr + pkt_len;
15650 			} else {
15651 				ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15652 				continue;
15653 			}
15654 		}
15655 
15656 		opt_len = ipha->ipha_version_and_hdr_length -
15657 		    IP_SIMPLE_HDR_VERSION;
15658 		dst = ipha->ipha_dst;
15659 
15660 		/* IP version bad or there are IP options */
15661 		if (opt_len && (!ip_rput_multimblk_ipoptions(q, ill,
15662 		    mp, &ipha, &dst, ipst)))
15663 			continue;
15664 
15665 		if (is_system_labeled() || (ill->ill_dhcpinit != 0) ||
15666 		    (ipst->ips_ip_cgtp_filter &&
15667 		    ipst->ips_ip_cgtp_filter_ops != NULL)) {
15668 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15669 			continue;
15670 		}
15671 
15672 		/*
15673 		 * Reuse the cached ire only if the ipha_dst of the previous
15674 		 * packet is the same as the current packet AND it is not
15675 		 * INADDR_ANY.
15676 		 */
15677 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15678 		    (ire != NULL)) {
15679 			ire_refrele(ire);
15680 			ire = NULL;
15681 		}
15682 
15683 		if (ire == NULL)
15684 			ire = ire_cache_lookup_simple(dst, ipst);
15685 
15686 		/*
15687 		 * Unless forwarding is enabled, dont call
15688 		 * ip_fast_forward(). Incoming packet is for forwarding
15689 		 */
15690 		if ((ill->ill_flags & ILLF_ROUTER) &&
15691 		    (ire == NULL || (ire->ire_type & IRE_CACHE))) {
15692 
15693 			DTRACE_PROBE4(ip4__physical__in__start,
15694 			    ill_t *, ill, ill_t *, NULL,
15695 			    ipha_t *, ipha, mblk_t *, mp);
15696 
15697 			FW_HOOKS(ipst->ips_ip4_physical_in_event,
15698 			    ipst->ips_ipv4firewall_physical_in,
15699 			    ill, NULL, ipha, mp, mp, 0, ipst);
15700 
15701 			DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, mp);
15702 
15703 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15704 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets,
15705 			    pkt_len);
15706 
15707 			ire = ip_fast_forward(ire, dst, ill, mp);
15708 			continue;
15709 		}
15710 
15711 		/* incoming packet is for local consumption */
15712 		if ((ire != NULL) && (ire->ire_type & IRE_LOCAL))
15713 			goto local_accept;
15714 
15715 		/*
15716 		 * Disable ire caching for anything more complex
15717 		 * than the simple fast path case we checked for above.
15718 		 */
15719 		if (ire != NULL) {
15720 			ire_refrele(ire);
15721 			ire = NULL;
15722 		}
15723 
15724 		ire = ire_cache_lookup(dst, ALL_ZONES, MBLK_GETLABEL(mp),
15725 		    ipst);
15726 		if (ire == NULL || ire->ire_type == IRE_BROADCAST ||
15727 		    ire->ire_stq != NULL) {
15728 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15729 			if (ire != NULL) {
15730 				ire_refrele(ire);
15731 				ire = NULL;
15732 			}
15733 			continue;
15734 		}
15735 
15736 local_accept:
15737 
15738 		if (ire->ire_rfq != q) {
15739 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15740 			if (ire != NULL) {
15741 				ire_refrele(ire);
15742 				ire = NULL;
15743 			}
15744 			continue;
15745 		}
15746 
15747 		/*
15748 		 * The event for packets being received from a 'physical'
15749 		 * interface is placed after validation of the source and/or
15750 		 * destination address as being local so that packets can be
15751 		 * redirected to loopback addresses using ipnat.
15752 		 */
15753 		DTRACE_PROBE4(ip4__physical__in__start,
15754 		    ill_t *, ill, ill_t *, NULL,
15755 		    ipha_t *, ipha, mblk_t *, mp);
15756 
15757 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15758 		    ipst->ips_ipv4firewall_physical_in,
15759 		    ill, NULL, ipha, mp, mp, 0, ipst);
15760 
15761 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, mp);
15762 
15763 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15764 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15765 
15766 		if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire, mp,
15767 		    0, q, ip_ring)) != NULL) {
15768 			if ((curr_sqp = GET_SQUEUE(mp)) == target_sqp) {
15769 				ADD_TO_CHAIN(ahead, atail, acnt, mp);
15770 			} else {
15771 				SQUEUE_ENTER(curr_sqp, mp, mp, 1,
15772 				    SQ_FILL, SQTAG_IP_INPUT);
15773 			}
15774 		}
15775 	}
15776 
15777 	if (ire != NULL)
15778 		ire_refrele(ire);
15779 
15780 	if (uhead != NULL)
15781 		ip_input(ill, ip_ring, uhead, NULL);
15782 
15783 	if (ahead != NULL) {
15784 		*last = atail;
15785 		*cnt = acnt;
15786 		return (ahead);
15787 	}
15788 
15789 	return (NULL);
15790 #undef  rptr
15791 }
15792 
15793 static void
15794 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15795     t_uscalar_t err)
15796 {
15797 	if (dl_err == DL_SYSERR) {
15798 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15799 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15800 		    ill->ill_name, dl_primstr(prim), err);
15801 		return;
15802 	}
15803 
15804 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15805 	    "%s: %s failed: %s\n", ill->ill_name, dl_primstr(prim),
15806 	    dl_errstr(dl_err));
15807 }
15808 
15809 /*
15810  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15811  * than DL_UNITDATA_IND messages. If we need to process this message
15812  * exclusively, we call qwriter_ip, in which case we also need to call
15813  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15814  */
15815 void
15816 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15817 {
15818 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15819 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15820 	ill_t		*ill = q->q_ptr;
15821 	t_uscalar_t	prim = dloa->dl_primitive;
15822 	t_uscalar_t	reqprim = DL_PRIM_INVAL;
15823 
15824 	ip1dbg(("ip_rput_dlpi"));
15825 
15826 	/*
15827 	 * If we received an ACK but didn't send a request for it, then it
15828 	 * can't be part of any pending operation; discard up-front.
15829 	 */
15830 	switch (prim) {
15831 	case DL_ERROR_ACK:
15832 		reqprim = dlea->dl_error_primitive;
15833 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK for %s (0x%x): %s "
15834 		    "(0x%x), unix %u\n", ill->ill_name, dl_primstr(reqprim),
15835 		    reqprim, dl_errstr(dlea->dl_errno), dlea->dl_errno,
15836 		    dlea->dl_unix_errno));
15837 		break;
15838 	case DL_OK_ACK:
15839 		reqprim = dloa->dl_correct_primitive;
15840 		break;
15841 	case DL_INFO_ACK:
15842 		reqprim = DL_INFO_REQ;
15843 		break;
15844 	case DL_BIND_ACK:
15845 		reqprim = DL_BIND_REQ;
15846 		break;
15847 	case DL_PHYS_ADDR_ACK:
15848 		reqprim = DL_PHYS_ADDR_REQ;
15849 		break;
15850 	case DL_NOTIFY_ACK:
15851 		reqprim = DL_NOTIFY_REQ;
15852 		break;
15853 	case DL_CONTROL_ACK:
15854 		reqprim = DL_CONTROL_REQ;
15855 		break;
15856 	case DL_CAPABILITY_ACK:
15857 		reqprim = DL_CAPABILITY_REQ;
15858 		break;
15859 	}
15860 
15861 	if (prim != DL_NOTIFY_IND) {
15862 		if (reqprim == DL_PRIM_INVAL ||
15863 		    !ill_dlpi_pending(ill, reqprim)) {
15864 			/* Not a DLPI message we support or expected */
15865 			freemsg(mp);
15866 			return;
15867 		}
15868 		ip1dbg(("ip_rput: received %s for %s\n", dl_primstr(prim),
15869 		    dl_primstr(reqprim)));
15870 	}
15871 
15872 	switch (reqprim) {
15873 	case DL_UNBIND_REQ:
15874 		/*
15875 		 * NOTE: we mark the unbind as complete even if we got a
15876 		 * DL_ERROR_ACK, since there's not much else we can do.
15877 		 */
15878 		mutex_enter(&ill->ill_lock);
15879 		ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15880 		cv_signal(&ill->ill_cv);
15881 		mutex_exit(&ill->ill_lock);
15882 		break;
15883 
15884 	case DL_ENABMULTI_REQ:
15885 		if (prim == DL_OK_ACK) {
15886 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15887 				ill->ill_dlpi_multicast_state = IDS_OK;
15888 		}
15889 		break;
15890 	}
15891 
15892 	/*
15893 	 * The message is one we're waiting for (or DL_NOTIFY_IND), but we
15894 	 * need to become writer to continue to process it.  Because an
15895 	 * exclusive operation doesn't complete until replies to all queued
15896 	 * DLPI messages have been received, we know we're in the middle of an
15897 	 * exclusive operation and pass CUR_OP (except for DL_NOTIFY_IND).
15898 	 *
15899 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
15900 	 * Since this is on the ill stream we unconditionally bump up the
15901 	 * refcount without doing ILL_CAN_LOOKUP().
15902 	 */
15903 	ill_refhold(ill);
15904 	if (prim == DL_NOTIFY_IND)
15905 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
15906 	else
15907 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
15908 }
15909 
15910 /*
15911  * Handling of DLPI messages that require exclusive access to the ipsq.
15912  *
15913  * Need to do ill_pending_mp_release on ioctl completion, which could
15914  * happen here. (along with mi_copy_done)
15915  */
15916 /* ARGSUSED */
15917 static void
15918 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15919 {
15920 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15921 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15922 	int		err = 0;
15923 	ill_t		*ill;
15924 	ipif_t		*ipif = NULL;
15925 	mblk_t		*mp1 = NULL;
15926 	conn_t		*connp = NULL;
15927 	t_uscalar_t	paddrreq;
15928 	mblk_t		*mp_hw;
15929 	boolean_t	success;
15930 	boolean_t	ioctl_aborted = B_FALSE;
15931 	boolean_t	log = B_TRUE;
15932 	ip_stack_t		*ipst;
15933 
15934 	ip1dbg(("ip_rput_dlpi_writer .."));
15935 	ill = (ill_t *)q->q_ptr;
15936 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15937 
15938 	ASSERT(IAM_WRITER_ILL(ill));
15939 
15940 	ipst = ill->ill_ipst;
15941 
15942 	/*
15943 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
15944 	 * both are null or non-null. However we can assert that only
15945 	 * after grabbing the ipsq_lock. So we don't make any assertion
15946 	 * here and in other places in the code.
15947 	 */
15948 	ipif = ipsq->ipsq_pending_ipif;
15949 	/*
15950 	 * The current ioctl could have been aborted by the user and a new
15951 	 * ioctl to bring up another ill could have started. We could still
15952 	 * get a response from the driver later.
15953 	 */
15954 	if (ipif != NULL && ipif->ipif_ill != ill)
15955 		ioctl_aborted = B_TRUE;
15956 
15957 	switch (dloa->dl_primitive) {
15958 	case DL_ERROR_ACK:
15959 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
15960 		    dl_primstr(dlea->dl_error_primitive)));
15961 
15962 		switch (dlea->dl_error_primitive) {
15963 		case DL_DISABMULTI_REQ:
15964 			if (!ill->ill_isv6)
15965 				ipsq_current_finish(ipsq);
15966 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15967 			break;
15968 		case DL_PROMISCON_REQ:
15969 		case DL_PROMISCOFF_REQ:
15970 		case DL_UNBIND_REQ:
15971 		case DL_ATTACH_REQ:
15972 		case DL_INFO_REQ:
15973 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15974 			break;
15975 		case DL_NOTIFY_REQ:
15976 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15977 			log = B_FALSE;
15978 			break;
15979 		case DL_PHYS_ADDR_REQ:
15980 			/*
15981 			 * For IPv6 only, there are two additional
15982 			 * phys_addr_req's sent to the driver to get the
15983 			 * IPv6 token and lla. This allows IP to acquire
15984 			 * the hardware address format for a given interface
15985 			 * without having built in knowledge of the hardware
15986 			 * address. ill_phys_addr_pend keeps track of the last
15987 			 * DL_PAR sent so we know which response we are
15988 			 * dealing with. ill_dlpi_done will update
15989 			 * ill_phys_addr_pend when it sends the next req.
15990 			 * We don't complete the IOCTL until all three DL_PARs
15991 			 * have been attempted, so set *_len to 0 and break.
15992 			 */
15993 			paddrreq = ill->ill_phys_addr_pend;
15994 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15995 			if (paddrreq == DL_IPV6_TOKEN) {
15996 				ill->ill_token_length = 0;
15997 				log = B_FALSE;
15998 				break;
15999 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16000 				ill->ill_nd_lla_len = 0;
16001 				log = B_FALSE;
16002 				break;
16003 			}
16004 			/*
16005 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
16006 			 * We presumably have an IOCTL hanging out waiting
16007 			 * for completion. Find it and complete the IOCTL
16008 			 * with the error noted.
16009 			 * However, ill_dl_phys was called on an ill queue
16010 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
16011 			 * set. But the ioctl is known to be pending on ill_wq.
16012 			 */
16013 			if (!ill->ill_ifname_pending)
16014 				break;
16015 			ill->ill_ifname_pending = 0;
16016 			if (!ioctl_aborted)
16017 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16018 			if (mp1 != NULL) {
16019 				/*
16020 				 * This operation (SIOCSLIFNAME) must have
16021 				 * happened on the ill. Assert there is no conn
16022 				 */
16023 				ASSERT(connp == NULL);
16024 				q = ill->ill_wq;
16025 			}
16026 			break;
16027 		case DL_BIND_REQ:
16028 			ill_dlpi_done(ill, DL_BIND_REQ);
16029 			if (ill->ill_ifname_pending)
16030 				break;
16031 			/*
16032 			 * Something went wrong with the bind.  We presumably
16033 			 * have an IOCTL hanging out waiting for completion.
16034 			 * Find it, take down the interface that was coming
16035 			 * up, and complete the IOCTL with the error noted.
16036 			 */
16037 			if (!ioctl_aborted)
16038 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16039 			if (mp1 != NULL) {
16040 				/*
16041 				 * This operation (SIOCSLIFFLAGS) must have
16042 				 * happened from a conn.
16043 				 */
16044 				ASSERT(connp != NULL);
16045 				q = CONNP_TO_WQ(connp);
16046 				if (ill->ill_move_in_progress) {
16047 					ILL_CLEAR_MOVE(ill);
16048 				}
16049 				(void) ipif_down(ipif, NULL, NULL);
16050 				/* error is set below the switch */
16051 			}
16052 			break;
16053 		case DL_ENABMULTI_REQ:
16054 			if (!ill->ill_isv6)
16055 				ipsq_current_finish(ipsq);
16056 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
16057 
16058 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
16059 				ill->ill_dlpi_multicast_state = IDS_FAILED;
16060 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
16061 				ipif_t *ipif;
16062 
16063 				printf("ip: joining multicasts failed (%d)"
16064 				    " on %s - will use link layer "
16065 				    "broadcasts for multicast\n",
16066 				    dlea->dl_errno, ill->ill_name);
16067 
16068 				/*
16069 				 * Set up the multicast mapping alone.
16070 				 * writer, so ok to access ill->ill_ipif
16071 				 * without any lock.
16072 				 */
16073 				ipif = ill->ill_ipif;
16074 				mutex_enter(&ill->ill_phyint->phyint_lock);
16075 				ill->ill_phyint->phyint_flags |=
16076 				    PHYI_MULTI_BCAST;
16077 				mutex_exit(&ill->ill_phyint->phyint_lock);
16078 
16079 				if (!ill->ill_isv6) {
16080 					(void) ipif_arp_setup_multicast(ipif,
16081 					    NULL);
16082 				} else {
16083 					(void) ipif_ndp_setup_multicast(ipif,
16084 					    NULL);
16085 				}
16086 			}
16087 			freemsg(mp);	/* Don't want to pass this up */
16088 			return;
16089 		case DL_CONTROL_REQ:
16090 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
16091 			    "DL_CONTROL_REQ\n"));
16092 			ill_dlpi_done(ill, dlea->dl_error_primitive);
16093 			freemsg(mp);
16094 			return;
16095 		case DL_CAPABILITY_REQ:
16096 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
16097 			    "DL_CAPABILITY REQ\n"));
16098 			if (ill->ill_dlpi_capab_state == IDCS_PROBE_SENT)
16099 				ill->ill_dlpi_capab_state = IDCS_FAILED;
16100 			ill_capability_done(ill);
16101 			freemsg(mp);
16102 			return;
16103 		}
16104 		/*
16105 		 * Note the error for IOCTL completion (mp1 is set when
16106 		 * ready to complete ioctl). If ill_ifname_pending_err is
16107 		 * set, an error occured during plumbing (ill_ifname_pending),
16108 		 * so we want to report that error.
16109 		 *
16110 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
16111 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
16112 		 * expected to get errack'd if the driver doesn't support
16113 		 * these flags (e.g. ethernet). log will be set to B_FALSE
16114 		 * if these error conditions are encountered.
16115 		 */
16116 		if (mp1 != NULL) {
16117 			if (ill->ill_ifname_pending_err != 0)  {
16118 				err = ill->ill_ifname_pending_err;
16119 				ill->ill_ifname_pending_err = 0;
16120 			} else {
16121 				err = dlea->dl_unix_errno ?
16122 				    dlea->dl_unix_errno : ENXIO;
16123 			}
16124 		/*
16125 		 * If we're plumbing an interface and an error hasn't already
16126 		 * been saved, set ill_ifname_pending_err to the error passed
16127 		 * up. Ignore the error if log is B_FALSE (see comment above).
16128 		 */
16129 		} else if (log && ill->ill_ifname_pending &&
16130 		    ill->ill_ifname_pending_err == 0) {
16131 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
16132 			    dlea->dl_unix_errno : ENXIO;
16133 		}
16134 
16135 		if (log)
16136 			ip_dlpi_error(ill, dlea->dl_error_primitive,
16137 			    dlea->dl_errno, dlea->dl_unix_errno);
16138 		break;
16139 	case DL_CAPABILITY_ACK:
16140 		ill_capability_ack(ill, mp);
16141 		/*
16142 		 * The message has been handed off to ill_capability_ack
16143 		 * and must not be freed below
16144 		 */
16145 		mp = NULL;
16146 		break;
16147 
16148 	case DL_CONTROL_ACK:
16149 		/* We treat all of these as "fire and forget" */
16150 		ill_dlpi_done(ill, DL_CONTROL_REQ);
16151 		break;
16152 	case DL_INFO_ACK:
16153 		/* Call a routine to handle this one. */
16154 		ill_dlpi_done(ill, DL_INFO_REQ);
16155 		ip_ll_subnet_defaults(ill, mp);
16156 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
16157 		return;
16158 	case DL_BIND_ACK:
16159 		/*
16160 		 * We should have an IOCTL waiting on this unless
16161 		 * sent by ill_dl_phys, in which case just return
16162 		 */
16163 		ill_dlpi_done(ill, DL_BIND_REQ);
16164 		if (ill->ill_ifname_pending)
16165 			break;
16166 
16167 		if (!ioctl_aborted)
16168 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16169 		if (mp1 == NULL)
16170 			break;
16171 		/*
16172 		 * Because mp1 was added by ill_dl_up(), and it always
16173 		 * passes a valid connp, connp must be valid here.
16174 		 */
16175 		ASSERT(connp != NULL);
16176 		q = CONNP_TO_WQ(connp);
16177 
16178 		/*
16179 		 * We are exclusive. So nothing can change even after
16180 		 * we get the pending mp. If need be we can put it back
16181 		 * and restart, as in calling ipif_arp_up()  below.
16182 		 */
16183 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
16184 
16185 		mutex_enter(&ill->ill_lock);
16186 		ill->ill_dl_up = 1;
16187 		ill_nic_event_dispatch(ill, 0, NE_UP, NULL, 0);
16188 		mutex_exit(&ill->ill_lock);
16189 
16190 		/*
16191 		 * Now bring up the resolver; when that is complete, we'll
16192 		 * create IREs.  Note that we intentionally mirror what
16193 		 * ipif_up() would have done, because we got here by way of
16194 		 * ill_dl_up(), which stopped ipif_up()'s processing.
16195 		 */
16196 		if (ill->ill_isv6) {
16197 			/*
16198 			 * v6 interfaces.
16199 			 * Unlike ARP which has to do another bind
16200 			 * and attach, once we get here we are
16201 			 * done with NDP. Except in the case of
16202 			 * ILLF_XRESOLV, in which case we send an
16203 			 * AR_INTERFACE_UP to the external resolver.
16204 			 * If all goes well, the ioctl will complete
16205 			 * in ip_rput(). If there's an error, we
16206 			 * complete it here.
16207 			 */
16208 			if ((err = ipif_ndp_up(ipif)) == 0) {
16209 				if (ill->ill_flags & ILLF_XRESOLV) {
16210 					mutex_enter(&connp->conn_lock);
16211 					mutex_enter(&ill->ill_lock);
16212 					success = ipsq_pending_mp_add(
16213 					    connp, ipif, q, mp1, 0);
16214 					mutex_exit(&ill->ill_lock);
16215 					mutex_exit(&connp->conn_lock);
16216 					if (success) {
16217 						err = ipif_resolver_up(ipif,
16218 						    Res_act_initial);
16219 						if (err == EINPROGRESS) {
16220 							freemsg(mp);
16221 							return;
16222 						}
16223 						ASSERT(err != 0);
16224 						mp1 = ipsq_pending_mp_get(ipsq,
16225 						    &connp);
16226 						ASSERT(mp1 != NULL);
16227 					} else {
16228 						/* conn has started closing */
16229 						err = EINTR;
16230 					}
16231 				} else { /* Non XRESOLV interface */
16232 					(void) ipif_resolver_up(ipif,
16233 					    Res_act_initial);
16234 					err = ipif_up_done_v6(ipif);
16235 				}
16236 			}
16237 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
16238 			/*
16239 			 * ARP and other v4 external resolvers.
16240 			 * Leave the pending mblk intact so that
16241 			 * the ioctl completes in ip_rput().
16242 			 */
16243 			mutex_enter(&connp->conn_lock);
16244 			mutex_enter(&ill->ill_lock);
16245 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
16246 			mutex_exit(&ill->ill_lock);
16247 			mutex_exit(&connp->conn_lock);
16248 			if (success) {
16249 				err = ipif_resolver_up(ipif, Res_act_initial);
16250 				if (err == EINPROGRESS) {
16251 					freemsg(mp);
16252 					return;
16253 				}
16254 				ASSERT(err != 0);
16255 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16256 			} else {
16257 				/* The conn has started closing */
16258 				err = EINTR;
16259 			}
16260 		} else {
16261 			/*
16262 			 * This one is complete. Reply to pending ioctl.
16263 			 */
16264 			(void) ipif_resolver_up(ipif, Res_act_initial);
16265 			err = ipif_up_done(ipif);
16266 		}
16267 
16268 		if ((err == 0) && (ill->ill_up_ipifs)) {
16269 			err = ill_up_ipifs(ill, q, mp1);
16270 			if (err == EINPROGRESS) {
16271 				freemsg(mp);
16272 				return;
16273 			}
16274 		}
16275 
16276 		if (ill->ill_up_ipifs) {
16277 			ill_group_cleanup(ill);
16278 		}
16279 
16280 		break;
16281 	case DL_NOTIFY_IND: {
16282 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
16283 		ire_t *ire;
16284 		boolean_t need_ire_walk_v4 = B_FALSE;
16285 		boolean_t need_ire_walk_v6 = B_FALSE;
16286 
16287 		switch (notify->dl_notification) {
16288 		case DL_NOTE_PHYS_ADDR:
16289 			err = ill_set_phys_addr(ill, mp);
16290 			break;
16291 
16292 		case DL_NOTE_FASTPATH_FLUSH:
16293 			ill_fastpath_flush(ill);
16294 			break;
16295 
16296 		case DL_NOTE_SDU_SIZE:
16297 			/*
16298 			 * Change the MTU size of the interface, of all
16299 			 * attached ipif's, and of all relevant ire's.  The
16300 			 * new value's a uint32_t at notify->dl_data.
16301 			 * Mtu change Vs. new ire creation - protocol below.
16302 			 *
16303 			 * a Mark the ipif as IPIF_CHANGING.
16304 			 * b Set the new mtu in the ipif.
16305 			 * c Change the ire_max_frag on all affected ires
16306 			 * d Unmark the IPIF_CHANGING
16307 			 *
16308 			 * To see how the protocol works, assume an interface
16309 			 * route is also being added simultaneously by
16310 			 * ip_rt_add and let 'ipif' be the ipif referenced by
16311 			 * the ire. If the ire is created before step a,
16312 			 * it will be cleaned up by step c. If the ire is
16313 			 * created after step d, it will see the new value of
16314 			 * ipif_mtu. Any attempt to create the ire between
16315 			 * steps a to d will fail because of the IPIF_CHANGING
16316 			 * flag. Note that ire_create() is passed a pointer to
16317 			 * the ipif_mtu, and not the value. During ire_add
16318 			 * under the bucket lock, the ire_max_frag of the
16319 			 * new ire being created is set from the ipif/ire from
16320 			 * which it is being derived.
16321 			 */
16322 			mutex_enter(&ill->ill_lock);
16323 			ill->ill_max_frag = (uint_t)notify->dl_data;
16324 
16325 			/*
16326 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
16327 			 * leave it alone
16328 			 */
16329 			if (ill->ill_mtu_userspecified) {
16330 				mutex_exit(&ill->ill_lock);
16331 				break;
16332 			}
16333 			ill->ill_max_mtu = ill->ill_max_frag;
16334 			if (ill->ill_isv6) {
16335 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
16336 					ill->ill_max_mtu = IPV6_MIN_MTU;
16337 			} else {
16338 				if (ill->ill_max_mtu < IP_MIN_MTU)
16339 					ill->ill_max_mtu = IP_MIN_MTU;
16340 			}
16341 			for (ipif = ill->ill_ipif; ipif != NULL;
16342 			    ipif = ipif->ipif_next) {
16343 				/*
16344 				 * Don't override the mtu if the user
16345 				 * has explicitly set it.
16346 				 */
16347 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
16348 					continue;
16349 				ipif->ipif_mtu = (uint_t)notify->dl_data;
16350 				if (ipif->ipif_isv6)
16351 					ire = ipif_to_ire_v6(ipif);
16352 				else
16353 					ire = ipif_to_ire(ipif);
16354 				if (ire != NULL) {
16355 					ire->ire_max_frag = ipif->ipif_mtu;
16356 					ire_refrele(ire);
16357 				}
16358 				if (ipif->ipif_flags & IPIF_UP) {
16359 					if (ill->ill_isv6)
16360 						need_ire_walk_v6 = B_TRUE;
16361 					else
16362 						need_ire_walk_v4 = B_TRUE;
16363 				}
16364 			}
16365 			mutex_exit(&ill->ill_lock);
16366 			if (need_ire_walk_v4)
16367 				ire_walk_v4(ill_mtu_change, (char *)ill,
16368 				    ALL_ZONES, ipst);
16369 			if (need_ire_walk_v6)
16370 				ire_walk_v6(ill_mtu_change, (char *)ill,
16371 				    ALL_ZONES, ipst);
16372 			break;
16373 		case DL_NOTE_LINK_UP:
16374 		case DL_NOTE_LINK_DOWN: {
16375 			/*
16376 			 * We are writer. ill / phyint / ipsq assocs stable.
16377 			 * The RUNNING flag reflects the state of the link.
16378 			 */
16379 			phyint_t *phyint = ill->ill_phyint;
16380 			uint64_t new_phyint_flags;
16381 			boolean_t changed = B_FALSE;
16382 			boolean_t went_up;
16383 
16384 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
16385 			mutex_enter(&phyint->phyint_lock);
16386 			new_phyint_flags = went_up ?
16387 			    phyint->phyint_flags | PHYI_RUNNING :
16388 			    phyint->phyint_flags & ~PHYI_RUNNING;
16389 			if (new_phyint_flags != phyint->phyint_flags) {
16390 				phyint->phyint_flags = new_phyint_flags;
16391 				changed = B_TRUE;
16392 			}
16393 			mutex_exit(&phyint->phyint_lock);
16394 			/*
16395 			 * ill_restart_dad handles the DAD restart and routing
16396 			 * socket notification logic.
16397 			 */
16398 			if (changed) {
16399 				ill_restart_dad(phyint->phyint_illv4, went_up);
16400 				ill_restart_dad(phyint->phyint_illv6, went_up);
16401 			}
16402 			break;
16403 		}
16404 		case DL_NOTE_PROMISC_ON_PHYS:
16405 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16406 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
16407 			mutex_enter(&ill->ill_lock);
16408 			ill->ill_promisc_on_phys = B_TRUE;
16409 			mutex_exit(&ill->ill_lock);
16410 			break;
16411 		case DL_NOTE_PROMISC_OFF_PHYS:
16412 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16413 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
16414 			mutex_enter(&ill->ill_lock);
16415 			ill->ill_promisc_on_phys = B_FALSE;
16416 			mutex_exit(&ill->ill_lock);
16417 			break;
16418 		case DL_NOTE_CAPAB_RENEG:
16419 			/*
16420 			 * Something changed on the driver side.
16421 			 * It wants us to renegotiate the capabilities
16422 			 * on this ill. One possible cause is the aggregation
16423 			 * interface under us where a port got added or
16424 			 * went away.
16425 			 *
16426 			 * If the capability negotiation is already done
16427 			 * or is in progress, reset the capabilities and
16428 			 * mark the ill's ill_capab_reneg to be B_TRUE,
16429 			 * so that when the ack comes back, we can start
16430 			 * the renegotiation process.
16431 			 *
16432 			 * Note that if ill_capab_reneg is already B_TRUE
16433 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
16434 			 * the capability resetting request has been sent
16435 			 * and the renegotiation has not been started yet;
16436 			 * nothing needs to be done in this case.
16437 			 */
16438 			ipsq_current_start(ipsq, ill->ill_ipif, 0);
16439 			ill_capability_reset(ill, B_TRUE);
16440 			ipsq_current_finish(ipsq);
16441 			break;
16442 		default:
16443 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
16444 			    "type 0x%x for DL_NOTIFY_IND\n",
16445 			    notify->dl_notification));
16446 			break;
16447 		}
16448 
16449 		/*
16450 		 * As this is an asynchronous operation, we
16451 		 * should not call ill_dlpi_done
16452 		 */
16453 		break;
16454 	}
16455 	case DL_NOTIFY_ACK: {
16456 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
16457 
16458 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
16459 			ill->ill_note_link = 1;
16460 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
16461 		break;
16462 	}
16463 	case DL_PHYS_ADDR_ACK: {
16464 		/*
16465 		 * As part of plumbing the interface via SIOCSLIFNAME,
16466 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
16467 		 * whose answers we receive here.  As each answer is received,
16468 		 * we call ill_dlpi_done() to dispatch the next request as
16469 		 * we're processing the current one.  Once all answers have
16470 		 * been received, we use ipsq_pending_mp_get() to dequeue the
16471 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
16472 		 * is invoked from an ill queue, conn_oper_pending_ill is not
16473 		 * available, but we know the ioctl is pending on ill_wq.)
16474 		 */
16475 		uint_t paddrlen, paddroff;
16476 
16477 		paddrreq = ill->ill_phys_addr_pend;
16478 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
16479 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
16480 
16481 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
16482 		if (paddrreq == DL_IPV6_TOKEN) {
16483 			/*
16484 			 * bcopy to low-order bits of ill_token
16485 			 *
16486 			 * XXX Temporary hack - currently, all known tokens
16487 			 * are 64 bits, so I'll cheat for the moment.
16488 			 */
16489 			bcopy(mp->b_rptr + paddroff,
16490 			    &ill->ill_token.s6_addr32[2], paddrlen);
16491 			ill->ill_token_length = paddrlen;
16492 			break;
16493 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16494 			ASSERT(ill->ill_nd_lla_mp == NULL);
16495 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
16496 			mp = NULL;
16497 			break;
16498 		}
16499 
16500 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
16501 		ASSERT(ill->ill_phys_addr_mp == NULL);
16502 		if (!ill->ill_ifname_pending)
16503 			break;
16504 		ill->ill_ifname_pending = 0;
16505 		if (!ioctl_aborted)
16506 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16507 		if (mp1 != NULL) {
16508 			ASSERT(connp == NULL);
16509 			q = ill->ill_wq;
16510 		}
16511 		/*
16512 		 * If any error acks received during the plumbing sequence,
16513 		 * ill_ifname_pending_err will be set. Break out and send up
16514 		 * the error to the pending ioctl.
16515 		 */
16516 		if (ill->ill_ifname_pending_err != 0) {
16517 			err = ill->ill_ifname_pending_err;
16518 			ill->ill_ifname_pending_err = 0;
16519 			break;
16520 		}
16521 
16522 		ill->ill_phys_addr_mp = mp;
16523 		ill->ill_phys_addr = mp->b_rptr + paddroff;
16524 		mp = NULL;
16525 
16526 		/*
16527 		 * If paddrlen is zero, the DLPI provider doesn't support
16528 		 * physical addresses.  The other two tests were historical
16529 		 * workarounds for bugs in our former PPP implementation, but
16530 		 * now other things have grown dependencies on them -- e.g.,
16531 		 * the tun module specifies a dl_addr_length of zero in its
16532 		 * DL_BIND_ACK, but then specifies an incorrect value in its
16533 		 * DL_PHYS_ADDR_ACK.  These bogus checks need to be removed,
16534 		 * but only after careful testing ensures that all dependent
16535 		 * broken DLPI providers have been fixed.
16536 		 */
16537 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0 ||
16538 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
16539 			ill->ill_phys_addr = NULL;
16540 		} else if (paddrlen != ill->ill_phys_addr_length) {
16541 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16542 			    paddrlen, ill->ill_phys_addr_length));
16543 			err = EINVAL;
16544 			break;
16545 		}
16546 
16547 		if (ill->ill_nd_lla_mp == NULL) {
16548 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16549 				err = ENOMEM;
16550 				break;
16551 			}
16552 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16553 		}
16554 
16555 		/*
16556 		 * Set the interface token.  If the zeroth interface address
16557 		 * is unspecified, then set it to the link local address.
16558 		 */
16559 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
16560 			(void) ill_setdefaulttoken(ill);
16561 
16562 		ASSERT(ill->ill_ipif->ipif_id == 0);
16563 		if (ipif != NULL &&
16564 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr)) {
16565 			(void) ipif_setlinklocal(ipif);
16566 		}
16567 		break;
16568 	}
16569 	case DL_OK_ACK:
16570 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16571 		    dl_primstr((int)dloa->dl_correct_primitive),
16572 		    dloa->dl_correct_primitive));
16573 		switch (dloa->dl_correct_primitive) {
16574 		case DL_ENABMULTI_REQ:
16575 		case DL_DISABMULTI_REQ:
16576 			if (!ill->ill_isv6)
16577 				ipsq_current_finish(ipsq);
16578 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16579 			break;
16580 		case DL_PROMISCON_REQ:
16581 		case DL_PROMISCOFF_REQ:
16582 		case DL_UNBIND_REQ:
16583 		case DL_ATTACH_REQ:
16584 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16585 			break;
16586 		}
16587 		break;
16588 	default:
16589 		break;
16590 	}
16591 
16592 	freemsg(mp);
16593 	if (mp1 != NULL) {
16594 		/*
16595 		 * The operation must complete without EINPROGRESS
16596 		 * since ipsq_pending_mp_get() has removed the mblk
16597 		 * from ipsq_pending_mp.  Otherwise, the operation
16598 		 * will be stuck forever in the ipsq.
16599 		 */
16600 		ASSERT(err != EINPROGRESS);
16601 
16602 		switch (ipsq->ipsq_current_ioctl) {
16603 		case 0:
16604 			ipsq_current_finish(ipsq);
16605 			break;
16606 
16607 		case SIOCLIFADDIF:
16608 		case SIOCSLIFNAME:
16609 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16610 			break;
16611 
16612 		default:
16613 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16614 			break;
16615 		}
16616 	}
16617 }
16618 
16619 /*
16620  * ip_rput_other is called by ip_rput to handle messages modifying the global
16621  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16622  */
16623 /* ARGSUSED */
16624 void
16625 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16626 {
16627 	ill_t		*ill;
16628 	struct iocblk	*iocp;
16629 	mblk_t		*mp1;
16630 	conn_t		*connp = NULL;
16631 
16632 	ip1dbg(("ip_rput_other "));
16633 	ill = (ill_t *)q->q_ptr;
16634 	/*
16635 	 * This routine is not a writer in the case of SIOCGTUNPARAM
16636 	 * in which case ipsq is NULL.
16637 	 */
16638 	if (ipsq != NULL) {
16639 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16640 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
16641 	}
16642 
16643 	switch (mp->b_datap->db_type) {
16644 	case M_ERROR:
16645 	case M_HANGUP:
16646 		/*
16647 		 * The device has a problem.  We force the ILL down.  It can
16648 		 * be brought up again manually using SIOCSIFFLAGS (via
16649 		 * ifconfig or equivalent).
16650 		 */
16651 		ASSERT(ipsq != NULL);
16652 		if (mp->b_rptr < mp->b_wptr)
16653 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16654 		if (ill->ill_error == 0)
16655 			ill->ill_error = ENXIO;
16656 		if (!ill_down_start(q, mp))
16657 			return;
16658 		ipif_all_down_tail(ipsq, q, mp, NULL);
16659 		break;
16660 	case M_IOCACK:
16661 		iocp = (struct iocblk *)mp->b_rptr;
16662 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16663 		switch (iocp->ioc_cmd) {
16664 		case SIOCSTUNPARAM:
16665 		case OSIOCSTUNPARAM:
16666 			ASSERT(ipsq != NULL);
16667 			/*
16668 			 * Finish socket ioctl passed through to tun.
16669 			 * We should have an IOCTL waiting on this.
16670 			 */
16671 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16672 			if (ill->ill_isv6) {
16673 				struct iftun_req *ta;
16674 
16675 				/*
16676 				 * if a source or destination is
16677 				 * being set, try and set the link
16678 				 * local address for the tunnel
16679 				 */
16680 				ta = (struct iftun_req *)mp->b_cont->
16681 				    b_cont->b_rptr;
16682 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16683 					ipif_set_tun_llink(ill, ta);
16684 				}
16685 
16686 			}
16687 			if (mp1 != NULL) {
16688 				/*
16689 				 * Now copy back the b_next/b_prev used by
16690 				 * mi code for the mi_copy* functions.
16691 				 * See ip_sioctl_tunparam() for the reason.
16692 				 * Also protect against missing b_cont.
16693 				 */
16694 				if (mp->b_cont != NULL) {
16695 					mp->b_cont->b_next =
16696 					    mp1->b_cont->b_next;
16697 					mp->b_cont->b_prev =
16698 					    mp1->b_cont->b_prev;
16699 				}
16700 				inet_freemsg(mp1);
16701 				ASSERT(connp != NULL);
16702 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16703 				    iocp->ioc_error, NO_COPYOUT, ipsq);
16704 			} else {
16705 				ASSERT(connp == NULL);
16706 				putnext(q, mp);
16707 			}
16708 			break;
16709 		case SIOCGTUNPARAM:
16710 		case OSIOCGTUNPARAM:
16711 			/*
16712 			 * This is really M_IOCDATA from the tunnel driver.
16713 			 * convert back and complete the ioctl.
16714 			 * We should have an IOCTL waiting on this.
16715 			 */
16716 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16717 			if (mp1) {
16718 				/*
16719 				 * Now copy back the b_next/b_prev used by
16720 				 * mi code for the mi_copy* functions.
16721 				 * See ip_sioctl_tunparam() for the reason.
16722 				 * Also protect against missing b_cont.
16723 				 */
16724 				if (mp->b_cont != NULL) {
16725 					mp->b_cont->b_next =
16726 					    mp1->b_cont->b_next;
16727 					mp->b_cont->b_prev =
16728 					    mp1->b_cont->b_prev;
16729 				}
16730 				inet_freemsg(mp1);
16731 				if (iocp->ioc_error == 0)
16732 					mp->b_datap->db_type = M_IOCDATA;
16733 				ASSERT(connp != NULL);
16734 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16735 				    iocp->ioc_error, COPYOUT, NULL);
16736 			} else {
16737 				ASSERT(connp == NULL);
16738 				putnext(q, mp);
16739 			}
16740 			break;
16741 		default:
16742 			break;
16743 		}
16744 		break;
16745 	case M_IOCNAK:
16746 		iocp = (struct iocblk *)mp->b_rptr;
16747 
16748 		switch (iocp->ioc_cmd) {
16749 			int mode;
16750 
16751 		case DL_IOC_HDR_INFO:
16752 			/*
16753 			 * If this was the first attempt turn of the
16754 			 * fastpath probing.
16755 			 */
16756 			mutex_enter(&ill->ill_lock);
16757 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16758 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16759 				mutex_exit(&ill->ill_lock);
16760 				ill_fastpath_nack(ill);
16761 				ip1dbg(("ip_rput: DLPI fastpath off on "
16762 				    "interface %s\n",
16763 				    ill->ill_name));
16764 			} else {
16765 				mutex_exit(&ill->ill_lock);
16766 			}
16767 			freemsg(mp);
16768 			break;
16769 		case SIOCSTUNPARAM:
16770 		case OSIOCSTUNPARAM:
16771 			ASSERT(ipsq != NULL);
16772 			/*
16773 			 * Finish socket ioctl passed through to tun
16774 			 * We should have an IOCTL waiting on this.
16775 			 */
16776 			/* FALLTHRU */
16777 		case SIOCGTUNPARAM:
16778 		case OSIOCGTUNPARAM:
16779 			/*
16780 			 * This is really M_IOCDATA from the tunnel driver.
16781 			 * convert back and complete the ioctl.
16782 			 * We should have an IOCTL waiting on this.
16783 			 */
16784 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16785 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16786 				mp1 = ill_pending_mp_get(ill, &connp,
16787 				    iocp->ioc_id);
16788 				mode = COPYOUT;
16789 				ipsq = NULL;
16790 			} else {
16791 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16792 				mode = NO_COPYOUT;
16793 			}
16794 			if (mp1 != NULL) {
16795 				/*
16796 				 * Now copy back the b_next/b_prev used by
16797 				 * mi code for the mi_copy* functions.
16798 				 * See ip_sioctl_tunparam() for the reason.
16799 				 * Also protect against missing b_cont.
16800 				 */
16801 				if (mp->b_cont != NULL) {
16802 					mp->b_cont->b_next =
16803 					    mp1->b_cont->b_next;
16804 					mp->b_cont->b_prev =
16805 					    mp1->b_cont->b_prev;
16806 				}
16807 				inet_freemsg(mp1);
16808 				if (iocp->ioc_error == 0)
16809 					iocp->ioc_error = EINVAL;
16810 				ASSERT(connp != NULL);
16811 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16812 				    iocp->ioc_error, mode, ipsq);
16813 			} else {
16814 				ASSERT(connp == NULL);
16815 				putnext(q, mp);
16816 			}
16817 			break;
16818 		default:
16819 			break;
16820 		}
16821 	default:
16822 		break;
16823 	}
16824 }
16825 
16826 /*
16827  * NOTE : This function does not ire_refrele the ire argument passed in.
16828  *
16829  * IPQoS notes
16830  * IP policy is invoked twice for a forwarded packet, once on the read side
16831  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16832  * enabled. An additional parameter, in_ill, has been added for this purpose.
16833  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16834  * because ip_mroute drops this information.
16835  *
16836  */
16837 void
16838 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16839 {
16840 	uint32_t	old_pkt_len;
16841 	uint32_t	pkt_len;
16842 	queue_t	*q;
16843 	uint32_t	sum;
16844 #define	rptr	((uchar_t *)ipha)
16845 	uint32_t	max_frag;
16846 	uint32_t	ill_index;
16847 	ill_t		*out_ill;
16848 	mib2_ipIfStatsEntry_t *mibptr;
16849 	ip_stack_t	*ipst = ((ill_t *)(ire->ire_stq->q_ptr))->ill_ipst;
16850 
16851 	/* Get the ill_index of the incoming ILL */
16852 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16853 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16854 
16855 	/* Initiate Read side IPPF processing */
16856 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16857 		ip_process(IPP_FWD_IN, &mp, ill_index);
16858 		if (mp == NULL) {
16859 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16860 			    "during IPPF processing\n"));
16861 			return;
16862 		}
16863 	}
16864 
16865 	/* Adjust the checksum to reflect the ttl decrement. */
16866 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16867 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16868 
16869 	if (ipha->ipha_ttl-- <= 1) {
16870 		if (ip_csum_hdr(ipha)) {
16871 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16872 			goto drop_pkt;
16873 		}
16874 		/*
16875 		 * Note: ire_stq this will be NULL for multicast
16876 		 * datagrams using the long path through arp (the IRE
16877 		 * is not an IRE_CACHE). This should not cause
16878 		 * problems since we don't generate ICMP errors for
16879 		 * multicast packets.
16880 		 */
16881 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16882 		q = ire->ire_stq;
16883 		if (q != NULL) {
16884 			/* Sent by forwarding path, and router is global zone */
16885 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16886 			    GLOBAL_ZONEID, ipst);
16887 		} else
16888 			freemsg(mp);
16889 		return;
16890 	}
16891 
16892 	/*
16893 	 * Don't forward if the interface is down
16894 	 */
16895 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16896 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16897 		ip2dbg(("ip_rput_forward:interface is down\n"));
16898 		goto drop_pkt;
16899 	}
16900 
16901 	/* Get the ill_index of the outgoing ILL */
16902 	out_ill = ire_to_ill(ire);
16903 	ill_index = out_ill->ill_phyint->phyint_ifindex;
16904 
16905 	DTRACE_PROBE4(ip4__forwarding__start,
16906 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16907 
16908 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16909 	    ipst->ips_ipv4firewall_forwarding,
16910 	    in_ill, out_ill, ipha, mp, mp, 0, ipst);
16911 
16912 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16913 
16914 	if (mp == NULL)
16915 		return;
16916 	old_pkt_len = pkt_len = ntohs(ipha->ipha_length);
16917 
16918 	if (is_system_labeled()) {
16919 		mblk_t *mp1;
16920 
16921 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16922 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16923 			goto drop_pkt;
16924 		}
16925 		/* Size may have changed */
16926 		mp = mp1;
16927 		ipha = (ipha_t *)mp->b_rptr;
16928 		pkt_len = ntohs(ipha->ipha_length);
16929 	}
16930 
16931 	/* Check if there are options to update */
16932 	if (!IS_SIMPLE_IPH(ipha)) {
16933 		if (ip_csum_hdr(ipha)) {
16934 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16935 			goto drop_pkt;
16936 		}
16937 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16938 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16939 			return;
16940 		}
16941 
16942 		ipha->ipha_hdr_checksum = 0;
16943 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16944 	}
16945 	max_frag = ire->ire_max_frag;
16946 	if (pkt_len > max_frag) {
16947 		/*
16948 		 * It needs fragging on its way out.  We haven't
16949 		 * verified the header checksum yet.  Since we
16950 		 * are going to put a surely good checksum in the
16951 		 * outgoing header, we have to make sure that it
16952 		 * was good coming in.
16953 		 */
16954 		if (ip_csum_hdr(ipha)) {
16955 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16956 			goto drop_pkt;
16957 		}
16958 		/* Initiate Write side IPPF processing */
16959 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16960 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16961 			if (mp == NULL) {
16962 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16963 				    " during IPPF processing\n"));
16964 				return;
16965 			}
16966 		}
16967 		/*
16968 		 * Handle labeled packet resizing.
16969 		 *
16970 		 * If we have added a label, inform ip_wput_frag() of its
16971 		 * effect on the MTU for ICMP messages.
16972 		 */
16973 		if (pkt_len > old_pkt_len) {
16974 			uint32_t secopt_size;
16975 
16976 			secopt_size = pkt_len - old_pkt_len;
16977 			if (secopt_size < max_frag)
16978 				max_frag -= secopt_size;
16979 		}
16980 
16981 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0,
16982 		    GLOBAL_ZONEID, ipst, NULL);
16983 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16984 		return;
16985 	}
16986 
16987 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16988 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16989 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16990 	    ipst->ips_ipv4firewall_physical_out,
16991 	    NULL, out_ill, ipha, mp, mp, 0, ipst);
16992 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16993 	if (mp == NULL)
16994 		return;
16995 
16996 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16997 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16998 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE, NULL);
16999 	/* ip_xmit_v4 always consumes the packet */
17000 	return;
17001 
17002 drop_pkt:;
17003 	ip1dbg(("ip_rput_forward: drop pkt\n"));
17004 	freemsg(mp);
17005 #undef	rptr
17006 }
17007 
17008 void
17009 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
17010 {
17011 	ire_t	*ire;
17012 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
17013 
17014 	ASSERT(!ipif->ipif_isv6);
17015 	/*
17016 	 * Find an IRE which matches the destination and the outgoing
17017 	 * queue in the cache table. All we need is an IRE_CACHE which
17018 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
17019 	 * then it is enough to have some IRE_CACHE in the group.
17020 	 */
17021 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
17022 		dst = ipif->ipif_pp_dst_addr;
17023 
17024 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
17025 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR, ipst);
17026 	if (ire == NULL) {
17027 		/*
17028 		 * Mark this packet to make it be delivered to
17029 		 * ip_rput_forward after the new ire has been
17030 		 * created.
17031 		 */
17032 		mp->b_prev = NULL;
17033 		mp->b_next = mp;
17034 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
17035 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
17036 	} else {
17037 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
17038 		IRE_REFRELE(ire);
17039 	}
17040 }
17041 
17042 /* Update any source route, record route or timestamp options */
17043 static int
17044 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
17045 {
17046 	ipoptp_t	opts;
17047 	uchar_t		*opt;
17048 	uint8_t		optval;
17049 	uint8_t		optlen;
17050 	ipaddr_t	dst;
17051 	uint32_t	ts;
17052 	ire_t		*dst_ire = NULL;
17053 	ire_t		*tmp_ire = NULL;
17054 	timestruc_t	now;
17055 
17056 	ip2dbg(("ip_rput_forward_options\n"));
17057 	dst = ipha->ipha_dst;
17058 	for (optval = ipoptp_first(&opts, ipha);
17059 	    optval != IPOPT_EOL;
17060 	    optval = ipoptp_next(&opts)) {
17061 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17062 		opt = opts.ipoptp_cur;
17063 		optlen = opts.ipoptp_len;
17064 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
17065 		    optval, opts.ipoptp_len));
17066 		switch (optval) {
17067 			uint32_t off;
17068 		case IPOPT_SSRR:
17069 		case IPOPT_LSRR:
17070 			/* Check if adminstratively disabled */
17071 			if (!ipst->ips_ip_forward_src_routed) {
17072 				if (ire->ire_stq != NULL) {
17073 					/*
17074 					 * Sent by forwarding path, and router
17075 					 * is global zone
17076 					 */
17077 					icmp_unreachable(ire->ire_stq, mp,
17078 					    ICMP_SOURCE_ROUTE_FAILED,
17079 					    GLOBAL_ZONEID, ipst);
17080 				} else {
17081 					ip0dbg(("ip_rput_forward_options: "
17082 					    "unable to send unreach\n"));
17083 					freemsg(mp);
17084 				}
17085 				return (-1);
17086 			}
17087 
17088 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17089 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17090 			if (dst_ire == NULL) {
17091 				/*
17092 				 * Must be partial since ip_rput_options
17093 				 * checked for strict.
17094 				 */
17095 				break;
17096 			}
17097 			off = opt[IPOPT_OFFSET];
17098 			off--;
17099 		redo_srr:
17100 			if (optlen < IP_ADDR_LEN ||
17101 			    off > optlen - IP_ADDR_LEN) {
17102 				/* End of source route */
17103 				ip1dbg((
17104 				    "ip_rput_forward_options: end of SR\n"));
17105 				ire_refrele(dst_ire);
17106 				break;
17107 			}
17108 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17109 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17110 			    IP_ADDR_LEN);
17111 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
17112 			    ntohl(dst)));
17113 
17114 			/*
17115 			 * Check if our address is present more than
17116 			 * once as consecutive hops in source route.
17117 			 */
17118 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17119 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17120 			if (tmp_ire != NULL) {
17121 				ire_refrele(tmp_ire);
17122 				off += IP_ADDR_LEN;
17123 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17124 				goto redo_srr;
17125 			}
17126 			ipha->ipha_dst = dst;
17127 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17128 			ire_refrele(dst_ire);
17129 			break;
17130 		case IPOPT_RR:
17131 			off = opt[IPOPT_OFFSET];
17132 			off--;
17133 			if (optlen < IP_ADDR_LEN ||
17134 			    off > optlen - IP_ADDR_LEN) {
17135 				/* No more room - ignore */
17136 				ip1dbg((
17137 				    "ip_rput_forward_options: end of RR\n"));
17138 				break;
17139 			}
17140 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17141 			    IP_ADDR_LEN);
17142 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17143 			break;
17144 		case IPOPT_TS:
17145 			/* Insert timestamp if there is room */
17146 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17147 			case IPOPT_TS_TSONLY:
17148 				off = IPOPT_TS_TIMELEN;
17149 				break;
17150 			case IPOPT_TS_PRESPEC:
17151 			case IPOPT_TS_PRESPEC_RFC791:
17152 				/* Verify that the address matched */
17153 				off = opt[IPOPT_OFFSET] - 1;
17154 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17155 				dst_ire = ire_ctable_lookup(dst, 0,
17156 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
17157 				    MATCH_IRE_TYPE, ipst);
17158 				if (dst_ire == NULL) {
17159 					/* Not for us */
17160 					break;
17161 				}
17162 				ire_refrele(dst_ire);
17163 				/* FALLTHRU */
17164 			case IPOPT_TS_TSANDADDR:
17165 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17166 				break;
17167 			default:
17168 				/*
17169 				 * ip_*put_options should have already
17170 				 * dropped this packet.
17171 				 */
17172 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
17173 				    "unknown IT - bug in ip_rput_options?\n");
17174 				return (0);	/* Keep "lint" happy */
17175 			}
17176 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17177 				/* Increase overflow counter */
17178 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17179 				opt[IPOPT_POS_OV_FLG] =
17180 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17181 				    (off << 4));
17182 				break;
17183 			}
17184 			off = opt[IPOPT_OFFSET] - 1;
17185 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17186 			case IPOPT_TS_PRESPEC:
17187 			case IPOPT_TS_PRESPEC_RFC791:
17188 			case IPOPT_TS_TSANDADDR:
17189 				bcopy(&ire->ire_src_addr,
17190 				    (char *)opt + off, IP_ADDR_LEN);
17191 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17192 				/* FALLTHRU */
17193 			case IPOPT_TS_TSONLY:
17194 				off = opt[IPOPT_OFFSET] - 1;
17195 				/* Compute # of milliseconds since midnight */
17196 				gethrestime(&now);
17197 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17198 				    now.tv_nsec / (NANOSEC / MILLISEC);
17199 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17200 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17201 				break;
17202 			}
17203 			break;
17204 		}
17205 	}
17206 	return (0);
17207 }
17208 
17209 /*
17210  * This is called after processing at least one of AH/ESP headers.
17211  *
17212  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
17213  * the actual, physical interface on which the packet was received,
17214  * but, when ip_strict_dst_multihoming is set to 1, could be the
17215  * interface which had the ipha_dst configured when the packet went
17216  * through ip_rput. The ill_index corresponding to the recv_ill
17217  * is saved in ipsec_in_rill_index
17218  *
17219  * NOTE2: The "ire" argument is only used in IPv4 cases.  This function
17220  * cannot assume "ire" points to valid data for any IPv6 cases.
17221  */
17222 void
17223 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
17224 {
17225 	mblk_t *mp;
17226 	ipaddr_t dst;
17227 	in6_addr_t *v6dstp;
17228 	ipha_t *ipha;
17229 	ip6_t *ip6h;
17230 	ipsec_in_t *ii;
17231 	boolean_t ill_need_rele = B_FALSE;
17232 	boolean_t rill_need_rele = B_FALSE;
17233 	boolean_t ire_need_rele = B_FALSE;
17234 	netstack_t	*ns;
17235 	ip_stack_t	*ipst;
17236 
17237 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
17238 	ASSERT(ii->ipsec_in_ill_index != 0);
17239 	ns = ii->ipsec_in_ns;
17240 	ASSERT(ii->ipsec_in_ns != NULL);
17241 	ipst = ns->netstack_ip;
17242 
17243 	mp = ipsec_mp->b_cont;
17244 	ASSERT(mp != NULL);
17245 
17246 
17247 	if (ill == NULL) {
17248 		ASSERT(recv_ill == NULL);
17249 		/*
17250 		 * We need to get the original queue on which ip_rput_local
17251 		 * or ip_rput_data_v6 was called.
17252 		 */
17253 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
17254 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
17255 		ill_need_rele = B_TRUE;
17256 
17257 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
17258 			recv_ill = ill_lookup_on_ifindex(
17259 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
17260 			    NULL, NULL, NULL, NULL, ipst);
17261 			rill_need_rele = B_TRUE;
17262 		} else {
17263 			recv_ill = ill;
17264 		}
17265 
17266 		if ((ill == NULL) || (recv_ill == NULL)) {
17267 			ip0dbg(("ip_fanout_proto_again: interface "
17268 			    "disappeared\n"));
17269 			if (ill != NULL)
17270 				ill_refrele(ill);
17271 			if (recv_ill != NULL)
17272 				ill_refrele(recv_ill);
17273 			freemsg(ipsec_mp);
17274 			return;
17275 		}
17276 	}
17277 
17278 	ASSERT(ill != NULL && recv_ill != NULL);
17279 
17280 	if (mp->b_datap->db_type == M_CTL) {
17281 		/*
17282 		 * AH/ESP is returning the ICMP message after
17283 		 * removing their headers. Fanout again till
17284 		 * it gets to the right protocol.
17285 		 */
17286 		if (ii->ipsec_in_v4) {
17287 			icmph_t *icmph;
17288 			int iph_hdr_length;
17289 			int hdr_length;
17290 
17291 			ipha = (ipha_t *)mp->b_rptr;
17292 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
17293 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
17294 			ipha = (ipha_t *)&icmph[1];
17295 			hdr_length = IPH_HDR_LENGTH(ipha);
17296 			/*
17297 			 * icmp_inbound_error_fanout may need to do pullupmsg.
17298 			 * Reset the type to M_DATA.
17299 			 */
17300 			mp->b_datap->db_type = M_DATA;
17301 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
17302 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
17303 			    B_FALSE, ill, ii->ipsec_in_zoneid);
17304 		} else {
17305 			icmp6_t *icmp6;
17306 			int hdr_length;
17307 
17308 			ip6h = (ip6_t *)mp->b_rptr;
17309 			/* Don't call hdr_length_v6() unless you have to. */
17310 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
17311 				hdr_length = ip_hdr_length_v6(mp, ip6h);
17312 			else
17313 				hdr_length = IPV6_HDR_LEN;
17314 
17315 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
17316 			/*
17317 			 * icmp_inbound_error_fanout_v6 may need to do
17318 			 * pullupmsg.  Reset the type to M_DATA.
17319 			 */
17320 			mp->b_datap->db_type = M_DATA;
17321 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
17322 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
17323 		}
17324 		if (ill_need_rele)
17325 			ill_refrele(ill);
17326 		if (rill_need_rele)
17327 			ill_refrele(recv_ill);
17328 		return;
17329 	}
17330 
17331 	if (ii->ipsec_in_v4) {
17332 		ipha = (ipha_t *)mp->b_rptr;
17333 		dst = ipha->ipha_dst;
17334 		if (CLASSD(dst)) {
17335 			/*
17336 			 * Multicast has to be delivered to all streams.
17337 			 */
17338 			dst = INADDR_BROADCAST;
17339 		}
17340 
17341 		if (ire == NULL) {
17342 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
17343 			    MBLK_GETLABEL(mp), ipst);
17344 			if (ire == NULL) {
17345 				if (ill_need_rele)
17346 					ill_refrele(ill);
17347 				if (rill_need_rele)
17348 					ill_refrele(recv_ill);
17349 				ip1dbg(("ip_fanout_proto_again: "
17350 				    "IRE not found"));
17351 				freemsg(ipsec_mp);
17352 				return;
17353 			}
17354 			ire_need_rele = B_TRUE;
17355 		}
17356 
17357 		switch (ipha->ipha_protocol) {
17358 			case IPPROTO_UDP:
17359 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
17360 				    recv_ill);
17361 				if (ire_need_rele)
17362 					ire_refrele(ire);
17363 				break;
17364 			case IPPROTO_TCP:
17365 				if (!ire_need_rele)
17366 					IRE_REFHOLD(ire);
17367 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
17368 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
17369 				IRE_REFRELE(ire);
17370 				if (mp != NULL) {
17371 
17372 					SQUEUE_ENTER(GET_SQUEUE(mp), mp,
17373 					    mp, 1, SQ_PROCESS,
17374 					    SQTAG_IP_PROTO_AGAIN);
17375 				}
17376 				break;
17377 			case IPPROTO_SCTP:
17378 				if (!ire_need_rele)
17379 					IRE_REFHOLD(ire);
17380 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
17381 				    ipsec_mp, 0, ill->ill_rq, dst);
17382 				break;
17383 			default:
17384 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
17385 				    recv_ill, 0);
17386 				if (ire_need_rele)
17387 					ire_refrele(ire);
17388 				break;
17389 		}
17390 	} else {
17391 		uint32_t rput_flags = 0;
17392 
17393 		ip6h = (ip6_t *)mp->b_rptr;
17394 		v6dstp = &ip6h->ip6_dst;
17395 		/*
17396 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
17397 		 * address.
17398 		 *
17399 		 * Currently, we don't store that state in the IPSEC_IN
17400 		 * message, and we may need to.
17401 		 */
17402 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
17403 		    IP6_IN_LLMCAST : 0);
17404 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
17405 		    NULL, NULL);
17406 	}
17407 	if (ill_need_rele)
17408 		ill_refrele(ill);
17409 	if (rill_need_rele)
17410 		ill_refrele(recv_ill);
17411 }
17412 
17413 /*
17414  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
17415  * returns 'true' if there are still fragments left on the queue, in
17416  * which case we restart the timer.
17417  */
17418 void
17419 ill_frag_timer(void *arg)
17420 {
17421 	ill_t	*ill = (ill_t *)arg;
17422 	boolean_t frag_pending;
17423 	ip_stack_t	*ipst = ill->ill_ipst;
17424 
17425 	mutex_enter(&ill->ill_lock);
17426 	ASSERT(!ill->ill_fragtimer_executing);
17427 	if (ill->ill_state_flags & ILL_CONDEMNED) {
17428 		ill->ill_frag_timer_id = 0;
17429 		mutex_exit(&ill->ill_lock);
17430 		return;
17431 	}
17432 	ill->ill_fragtimer_executing = 1;
17433 	mutex_exit(&ill->ill_lock);
17434 
17435 	frag_pending = ill_frag_timeout(ill, ipst->ips_ip_g_frag_timeout);
17436 
17437 	/*
17438 	 * Restart the timer, if we have fragments pending or if someone
17439 	 * wanted us to be scheduled again.
17440 	 */
17441 	mutex_enter(&ill->ill_lock);
17442 	ill->ill_fragtimer_executing = 0;
17443 	ill->ill_frag_timer_id = 0;
17444 	if (frag_pending || ill->ill_fragtimer_needrestart)
17445 		ill_frag_timer_start(ill);
17446 	mutex_exit(&ill->ill_lock);
17447 }
17448 
17449 void
17450 ill_frag_timer_start(ill_t *ill)
17451 {
17452 	ip_stack_t	*ipst = ill->ill_ipst;
17453 
17454 	ASSERT(MUTEX_HELD(&ill->ill_lock));
17455 
17456 	/* If the ill is closing or opening don't proceed */
17457 	if (ill->ill_state_flags & ILL_CONDEMNED)
17458 		return;
17459 
17460 	if (ill->ill_fragtimer_executing) {
17461 		/*
17462 		 * ill_frag_timer is currently executing. Just record the
17463 		 * the fact that we want the timer to be restarted.
17464 		 * ill_frag_timer will post a timeout before it returns,
17465 		 * ensuring it will be called again.
17466 		 */
17467 		ill->ill_fragtimer_needrestart = 1;
17468 		return;
17469 	}
17470 
17471 	if (ill->ill_frag_timer_id == 0) {
17472 		/*
17473 		 * The timer is neither running nor is the timeout handler
17474 		 * executing. Post a timeout so that ill_frag_timer will be
17475 		 * called
17476 		 */
17477 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
17478 		    MSEC_TO_TICK(ipst->ips_ip_g_frag_timo_ms >> 1));
17479 		ill->ill_fragtimer_needrestart = 0;
17480 	}
17481 }
17482 
17483 /*
17484  * This routine is needed for loopback when forwarding multicasts.
17485  *
17486  * IPQoS Notes:
17487  * IPPF processing is done in fanout routines.
17488  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
17489  * processing for IPsec packets is done when it comes back in clear.
17490  * NOTE : The callers of this function need to do the ire_refrele for the
17491  *	  ire that is being passed in.
17492  */
17493 void
17494 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17495     ill_t *recv_ill, uint32_t esp_udp_ports)
17496 {
17497 	boolean_t esp_in_udp_packet = (esp_udp_ports != 0);
17498 	ill_t	*ill = (ill_t *)q->q_ptr;
17499 	uint32_t	sum;
17500 	uint32_t	u1;
17501 	uint32_t	u2;
17502 	int		hdr_length;
17503 	boolean_t	mctl_present;
17504 	mblk_t		*first_mp = mp;
17505 	mblk_t		*hada_mp = NULL;
17506 	ipha_t		*inner_ipha;
17507 	ip_stack_t	*ipst;
17508 
17509 	ASSERT(recv_ill != NULL);
17510 	ipst = recv_ill->ill_ipst;
17511 
17512 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17513 	    "ip_rput_locl_start: q %p", q);
17514 
17515 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17516 	ASSERT(ill != NULL);
17517 
17518 
17519 #define	rptr	((uchar_t *)ipha)
17520 #define	iphs	((uint16_t *)ipha)
17521 
17522 	/*
17523 	 * no UDP or TCP packet should come here anymore.
17524 	 */
17525 	ASSERT(ipha->ipha_protocol != IPPROTO_TCP &&
17526 	    ipha->ipha_protocol != IPPROTO_UDP);
17527 
17528 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17529 	if (mctl_present &&
17530 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17531 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17532 
17533 		/*
17534 		 * It's an IPsec accelerated packet.
17535 		 * Keep a pointer to the data attributes around until
17536 		 * we allocate the ipsec_info_t.
17537 		 */
17538 		IPSECHW_DEBUG(IPSECHW_PKT,
17539 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17540 		hada_mp = first_mp;
17541 		hada_mp->b_cont = NULL;
17542 		/*
17543 		 * Since it is accelerated, it comes directly from
17544 		 * the ill and the data attributes is followed by
17545 		 * the packet data.
17546 		 */
17547 		ASSERT(mp->b_datap->db_type != M_CTL);
17548 		first_mp = mp;
17549 		mctl_present = B_FALSE;
17550 	}
17551 
17552 	/*
17553 	 * IF M_CTL is not present, then ipsec_in_is_secure
17554 	 * should return B_TRUE. There is a case where loopback
17555 	 * packets has an M_CTL in the front with all the
17556 	 * IPsec options set to IPSEC_PREF_NEVER - which means
17557 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17558 	 * packets never comes here, it is safe to ASSERT the
17559 	 * following.
17560 	 */
17561 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17562 
17563 	/*
17564 	 * Also, we should never have an mctl_present if this is an
17565 	 * ESP-in-UDP packet.
17566 	 */
17567 	ASSERT(!mctl_present || !esp_in_udp_packet);
17568 
17569 
17570 	/* u1 is # words of IP options */
17571 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
17572 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17573 
17574 	/*
17575 	 * Don't verify header checksum if we just removed UDP header or
17576 	 * packet is coming back from AH/ESP.
17577 	 */
17578 	if (!esp_in_udp_packet && !mctl_present) {
17579 		if (u1) {
17580 			if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17581 				if (hada_mp != NULL)
17582 					freemsg(hada_mp);
17583 				return;
17584 			}
17585 		} else {
17586 			/* Check the IP header checksum.  */
17587 #define	uph	((uint16_t *)ipha)
17588 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
17589 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
17590 #undef  uph
17591 			/* finish doing IP checksum */
17592 			sum = (sum & 0xFFFF) + (sum >> 16);
17593 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
17594 			if (sum && sum != 0xFFFF) {
17595 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17596 				goto drop_pkt;
17597 			}
17598 		}
17599 	}
17600 
17601 	/*
17602 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17603 	 * might be called more than once for secure packets, count only
17604 	 * the first time.
17605 	 */
17606 	if (!mctl_present) {
17607 		UPDATE_IB_PKT_COUNT(ire);
17608 		ire->ire_last_used_time = lbolt;
17609 	}
17610 
17611 	/* Check for fragmentation offset. */
17612 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17613 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17614 	if (u1) {
17615 		/*
17616 		 * We re-assemble fragments before we do the AH/ESP
17617 		 * processing. Thus, M_CTL should not be present
17618 		 * while we are re-assembling.
17619 		 */
17620 		ASSERT(!mctl_present);
17621 		ASSERT(first_mp == mp);
17622 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
17623 			return;
17624 		}
17625 		/*
17626 		 * Make sure that first_mp points back to mp as
17627 		 * the mp we came in with could have changed in
17628 		 * ip_rput_fragment().
17629 		 */
17630 		ipha = (ipha_t *)mp->b_rptr;
17631 		first_mp = mp;
17632 	}
17633 
17634 	/*
17635 	 * Clear hardware checksumming flag as it is currently only
17636 	 * used by TCP and UDP.
17637 	 */
17638 	DB_CKSUMFLAGS(mp) = 0;
17639 
17640 	/* Now we have a complete datagram, destined for this machine. */
17641 	u1 = IPH_HDR_LENGTH(ipha);
17642 	switch (ipha->ipha_protocol) {
17643 	case IPPROTO_ICMP: {
17644 		ire_t		*ire_zone;
17645 		ilm_t		*ilm;
17646 		mblk_t		*mp1;
17647 		zoneid_t	last_zoneid;
17648 
17649 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(recv_ill)) {
17650 			ASSERT(ire->ire_type == IRE_BROADCAST);
17651 			/*
17652 			 * Inactive/Failed interfaces are not supposed to
17653 			 * respond to the multicast packets.
17654 			 */
17655 			if (ill_is_probeonly(ill)) {
17656 				freemsg(first_mp);
17657 				return;
17658 			}
17659 
17660 			/*
17661 			 * In the multicast case, applications may have joined
17662 			 * the group from different zones, so we need to deliver
17663 			 * the packet to each of them. Loop through the
17664 			 * multicast memberships structures (ilm) on the receive
17665 			 * ill and send a copy of the packet up each matching
17666 			 * one. However, we don't do this for multicasts sent on
17667 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17668 			 * they must stay in the sender's zone.
17669 			 *
17670 			 * ilm_add_v6() ensures that ilms in the same zone are
17671 			 * contiguous in the ill_ilm list. We use this property
17672 			 * to avoid sending duplicates needed when two
17673 			 * applications in the same zone join the same group on
17674 			 * different logical interfaces: we ignore the ilm if
17675 			 * its zoneid is the same as the last matching one.
17676 			 * In addition, the sending of the packet for
17677 			 * ire_zoneid is delayed until all of the other ilms
17678 			 * have been exhausted.
17679 			 */
17680 			last_zoneid = -1;
17681 			ILM_WALKER_HOLD(recv_ill);
17682 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
17683 			    ilm = ilm->ilm_next) {
17684 				if ((ilm->ilm_flags & ILM_DELETED) ||
17685 				    ipha->ipha_dst != ilm->ilm_addr ||
17686 				    ilm->ilm_zoneid == last_zoneid ||
17687 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17688 				    ilm->ilm_zoneid == ALL_ZONES ||
17689 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17690 					continue;
17691 				mp1 = ip_copymsg(first_mp);
17692 				if (mp1 == NULL)
17693 					continue;
17694 				icmp_inbound(q, mp1, B_TRUE, ill,
17695 				    0, sum, mctl_present, B_TRUE,
17696 				    recv_ill, ilm->ilm_zoneid);
17697 				last_zoneid = ilm->ilm_zoneid;
17698 			}
17699 			ILM_WALKER_RELE(recv_ill);
17700 		} else if (ire->ire_type == IRE_BROADCAST) {
17701 			/*
17702 			 * In the broadcast case, there may be many zones
17703 			 * which need a copy of the packet delivered to them.
17704 			 * There is one IRE_BROADCAST per broadcast address
17705 			 * and per zone; we walk those using a helper function.
17706 			 * In addition, the sending of the packet for ire is
17707 			 * delayed until all of the other ires have been
17708 			 * processed.
17709 			 */
17710 			IRB_REFHOLD(ire->ire_bucket);
17711 			ire_zone = NULL;
17712 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17713 			    ire)) != NULL) {
17714 				mp1 = ip_copymsg(first_mp);
17715 				if (mp1 == NULL)
17716 					continue;
17717 
17718 				UPDATE_IB_PKT_COUNT(ire_zone);
17719 				ire_zone->ire_last_used_time = lbolt;
17720 				icmp_inbound(q, mp1, B_TRUE, ill,
17721 				    0, sum, mctl_present, B_TRUE,
17722 				    recv_ill, ire_zone->ire_zoneid);
17723 			}
17724 			IRB_REFRELE(ire->ire_bucket);
17725 		}
17726 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17727 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17728 		    ire->ire_zoneid);
17729 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17730 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17731 		return;
17732 	}
17733 	case IPPROTO_IGMP:
17734 		/*
17735 		 * If we are not willing to accept IGMP packets in clear,
17736 		 * then check with global policy.
17737 		 */
17738 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17739 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17740 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17741 			if (first_mp == NULL)
17742 				return;
17743 		}
17744 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17745 			freemsg(first_mp);
17746 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17747 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17748 			return;
17749 		}
17750 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17751 			/* Bad packet - discarded by igmp_input */
17752 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17753 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17754 			if (mctl_present)
17755 				freeb(first_mp);
17756 			return;
17757 		}
17758 		/*
17759 		 * igmp_input() may have returned the pulled up message.
17760 		 * So first_mp and ipha need to be reinitialized.
17761 		 */
17762 		ipha = (ipha_t *)mp->b_rptr;
17763 		if (mctl_present)
17764 			first_mp->b_cont = mp;
17765 		else
17766 			first_mp = mp;
17767 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17768 		    connf_head != NULL) {
17769 			/* No user-level listener for IGMP packets */
17770 			goto drop_pkt;
17771 		}
17772 		/* deliver to local raw users */
17773 		break;
17774 	case IPPROTO_PIM:
17775 		/*
17776 		 * If we are not willing to accept PIM packets in clear,
17777 		 * then check with global policy.
17778 		 */
17779 		if (ipst->ips_pim_accept_clear_messages == 0) {
17780 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17781 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17782 			if (first_mp == NULL)
17783 				return;
17784 		}
17785 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17786 			freemsg(first_mp);
17787 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17788 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17789 			return;
17790 		}
17791 		if (pim_input(q, mp, ill) != 0) {
17792 			/* Bad packet - discarded by pim_input */
17793 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17794 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17795 			if (mctl_present)
17796 				freeb(first_mp);
17797 			return;
17798 		}
17799 
17800 		/*
17801 		 * pim_input() may have pulled up the message so ipha needs to
17802 		 * be reinitialized.
17803 		 */
17804 		ipha = (ipha_t *)mp->b_rptr;
17805 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17806 		    connf_head != NULL) {
17807 			/* No user-level listener for PIM packets */
17808 			goto drop_pkt;
17809 		}
17810 		/* deliver to local raw users */
17811 		break;
17812 	case IPPROTO_ENCAP:
17813 		/*
17814 		 * Handle self-encapsulated packets (IP-in-IP where
17815 		 * the inner addresses == the outer addresses).
17816 		 */
17817 		hdr_length = IPH_HDR_LENGTH(ipha);
17818 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17819 		    mp->b_wptr) {
17820 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17821 			    sizeof (ipha_t) - mp->b_rptr)) {
17822 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17823 				freemsg(first_mp);
17824 				return;
17825 			}
17826 			ipha = (ipha_t *)mp->b_rptr;
17827 		}
17828 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17829 		/*
17830 		 * Check the sanity of the inner IP header.
17831 		 */
17832 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17833 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17834 			freemsg(first_mp);
17835 			return;
17836 		}
17837 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17838 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17839 			freemsg(first_mp);
17840 			return;
17841 		}
17842 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17843 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17844 			ipsec_in_t *ii;
17845 
17846 			/*
17847 			 * Self-encapsulated tunnel packet. Remove
17848 			 * the outer IP header and fanout again.
17849 			 * We also need to make sure that the inner
17850 			 * header is pulled up until options.
17851 			 */
17852 			mp->b_rptr = (uchar_t *)inner_ipha;
17853 			ipha = inner_ipha;
17854 			hdr_length = IPH_HDR_LENGTH(ipha);
17855 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17856 				if (!pullupmsg(mp, (uchar_t *)ipha +
17857 				    + hdr_length - mp->b_rptr)) {
17858 					freemsg(first_mp);
17859 					return;
17860 				}
17861 				ipha = (ipha_t *)mp->b_rptr;
17862 			}
17863 			if (hdr_length > sizeof (ipha_t)) {
17864 				/* We got options on the inner packet. */
17865 				ipaddr_t dst = ipha->ipha_dst;
17866 
17867 				if (ip_rput_options(q, mp, ipha, &dst, ipst) ==
17868 				    -1) {
17869 					/* Bad options! */
17870 					return;
17871 				}
17872 				if (dst != ipha->ipha_dst) {
17873 					/*
17874 					 * Someone put a source-route in
17875 					 * the inside header of a self-
17876 					 * encapsulated packet.  Drop it
17877 					 * with extreme prejudice and let
17878 					 * the sender know.
17879 					 */
17880 					icmp_unreachable(q, first_mp,
17881 					    ICMP_SOURCE_ROUTE_FAILED,
17882 					    recv_ill->ill_zoneid, ipst);
17883 					return;
17884 				}
17885 			}
17886 			if (!mctl_present) {
17887 				ASSERT(first_mp == mp);
17888 				/*
17889 				 * This means that somebody is sending
17890 				 * Self-encapsualted packets without AH/ESP.
17891 				 * If AH/ESP was present, we would have already
17892 				 * allocated the first_mp.
17893 				 *
17894 				 * Send this packet to find a tunnel endpoint.
17895 				 * if I can't find one, an ICMP
17896 				 * PROTOCOL_UNREACHABLE will get sent.
17897 				 */
17898 				goto fanout;
17899 			}
17900 			/*
17901 			 * We generally store the ill_index if we need to
17902 			 * do IPsec processing as we lose the ill queue when
17903 			 * we come back. But in this case, we never should
17904 			 * have to store the ill_index here as it should have
17905 			 * been stored previously when we processed the
17906 			 * AH/ESP header in this routine or for non-ipsec
17907 			 * cases, we still have the queue. But for some bad
17908 			 * packets from the wire, we can get to IPsec after
17909 			 * this and we better store the index for that case.
17910 			 */
17911 			ill = (ill_t *)q->q_ptr;
17912 			ii = (ipsec_in_t *)first_mp->b_rptr;
17913 			ii->ipsec_in_ill_index =
17914 			    ill->ill_phyint->phyint_ifindex;
17915 			ii->ipsec_in_rill_index =
17916 			    recv_ill->ill_phyint->phyint_ifindex;
17917 			if (ii->ipsec_in_decaps) {
17918 				/*
17919 				 * This packet is self-encapsulated multiple
17920 				 * times. We don't want to recurse infinitely.
17921 				 * To keep it simple, drop the packet.
17922 				 */
17923 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17924 				freemsg(first_mp);
17925 				return;
17926 			}
17927 			ii->ipsec_in_decaps = B_TRUE;
17928 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17929 			    ire);
17930 			return;
17931 		}
17932 		break;
17933 	case IPPROTO_AH:
17934 	case IPPROTO_ESP: {
17935 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17936 
17937 		/*
17938 		 * Fast path for AH/ESP. If this is the first time
17939 		 * we are sending a datagram to AH/ESP, allocate
17940 		 * a IPSEC_IN message and prepend it. Otherwise,
17941 		 * just fanout.
17942 		 */
17943 
17944 		int ipsec_rc;
17945 		ipsec_in_t *ii;
17946 		netstack_t *ns = ipst->ips_netstack;
17947 
17948 		IP_STAT(ipst, ipsec_proto_ahesp);
17949 		if (!mctl_present) {
17950 			ASSERT(first_mp == mp);
17951 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17952 			if (first_mp == NULL) {
17953 				ip1dbg(("ip_proto_input: IPSEC_IN "
17954 				    "allocation failure.\n"));
17955 				freemsg(hada_mp); /* okay ifnull */
17956 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17957 				freemsg(mp);
17958 				return;
17959 			}
17960 			/*
17961 			 * Store the ill_index so that when we come back
17962 			 * from IPsec we ride on the same queue.
17963 			 */
17964 			ill = (ill_t *)q->q_ptr;
17965 			ii = (ipsec_in_t *)first_mp->b_rptr;
17966 			ii->ipsec_in_ill_index =
17967 			    ill->ill_phyint->phyint_ifindex;
17968 			ii->ipsec_in_rill_index =
17969 			    recv_ill->ill_phyint->phyint_ifindex;
17970 			first_mp->b_cont = mp;
17971 			/*
17972 			 * Cache hardware acceleration info.
17973 			 */
17974 			if (hada_mp != NULL) {
17975 				IPSECHW_DEBUG(IPSECHW_PKT,
17976 				    ("ip_rput_local: caching data attr.\n"));
17977 				ii->ipsec_in_accelerated = B_TRUE;
17978 				ii->ipsec_in_da = hada_mp;
17979 				hada_mp = NULL;
17980 			}
17981 		} else {
17982 			ii = (ipsec_in_t *)first_mp->b_rptr;
17983 		}
17984 
17985 		ii->ipsec_in_esp_udp_ports = esp_udp_ports;
17986 
17987 		if (!ipsec_loaded(ipss)) {
17988 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17989 			    ire->ire_zoneid, ipst);
17990 			return;
17991 		}
17992 
17993 		ns = ipst->ips_netstack;
17994 		/* select inbound SA and have IPsec process the pkt */
17995 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17996 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17997 			boolean_t esp_in_udp_sa;
17998 			if (esph == NULL)
17999 				return;
18000 			ASSERT(ii->ipsec_in_esp_sa != NULL);
18001 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
18002 			esp_in_udp_sa = ((ii->ipsec_in_esp_sa->ipsa_flags &
18003 			    IPSA_F_NATT) != 0);
18004 			/*
18005 			 * The following is a fancy, but quick, way of saying:
18006 			 * ESP-in-UDP SA and Raw ESP packet --> drop
18007 			 *    OR
18008 			 * ESP SA and ESP-in-UDP packet --> drop
18009 			 */
18010 			if (esp_in_udp_sa != esp_in_udp_packet) {
18011 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
18012 				ip_drop_packet(first_mp, B_TRUE, ill, NULL,
18013 				    DROPPER(ns->netstack_ipsec, ipds_esp_no_sa),
18014 				    &ns->netstack_ipsec->ipsec_dropper);
18015 				return;
18016 			}
18017 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
18018 			    first_mp, esph);
18019 		} else {
18020 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
18021 			if (ah == NULL)
18022 				return;
18023 			ASSERT(ii->ipsec_in_ah_sa != NULL);
18024 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
18025 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
18026 			    first_mp, ah);
18027 		}
18028 
18029 		switch (ipsec_rc) {
18030 		case IPSEC_STATUS_SUCCESS:
18031 			break;
18032 		case IPSEC_STATUS_FAILED:
18033 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
18034 			/* FALLTHRU */
18035 		case IPSEC_STATUS_PENDING:
18036 			return;
18037 		}
18038 		/* we're done with IPsec processing, send it up */
18039 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
18040 		return;
18041 	}
18042 	default:
18043 		break;
18044 	}
18045 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
18046 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
18047 		    ire->ire_zoneid));
18048 		goto drop_pkt;
18049 	}
18050 	/*
18051 	 * Handle protocols with which IP is less intimate.  There
18052 	 * can be more than one stream bound to a particular
18053 	 * protocol.  When this is the case, each one gets a copy
18054 	 * of any incoming packets.
18055 	 */
18056 fanout:
18057 	ip_fanout_proto(q, first_mp, ill, ipha,
18058 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
18059 	    B_TRUE, recv_ill, ire->ire_zoneid);
18060 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
18061 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
18062 	return;
18063 
18064 drop_pkt:
18065 	freemsg(first_mp);
18066 	if (hada_mp != NULL)
18067 		freeb(hada_mp);
18068 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
18069 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
18070 #undef	rptr
18071 #undef  iphs
18072 
18073 }
18074 
18075 /*
18076  * Update any source route, record route or timestamp options.
18077  * Check that we are at end of strict source route.
18078  * The options have already been checked for sanity in ip_rput_options().
18079  */
18080 static boolean_t
18081 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
18082     ip_stack_t *ipst)
18083 {
18084 	ipoptp_t	opts;
18085 	uchar_t		*opt;
18086 	uint8_t		optval;
18087 	uint8_t		optlen;
18088 	ipaddr_t	dst;
18089 	uint32_t	ts;
18090 	ire_t		*dst_ire;
18091 	timestruc_t	now;
18092 	zoneid_t	zoneid;
18093 	ill_t		*ill;
18094 
18095 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
18096 
18097 	ip2dbg(("ip_rput_local_options\n"));
18098 
18099 	for (optval = ipoptp_first(&opts, ipha);
18100 	    optval != IPOPT_EOL;
18101 	    optval = ipoptp_next(&opts)) {
18102 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
18103 		opt = opts.ipoptp_cur;
18104 		optlen = opts.ipoptp_len;
18105 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
18106 		    optval, optlen));
18107 		switch (optval) {
18108 			uint32_t off;
18109 		case IPOPT_SSRR:
18110 		case IPOPT_LSRR:
18111 			off = opt[IPOPT_OFFSET];
18112 			off--;
18113 			if (optlen < IP_ADDR_LEN ||
18114 			    off > optlen - IP_ADDR_LEN) {
18115 				/* End of source route */
18116 				ip1dbg(("ip_rput_local_options: end of SR\n"));
18117 				break;
18118 			}
18119 			/*
18120 			 * This will only happen if two consecutive entries
18121 			 * in the source route contains our address or if
18122 			 * it is a packet with a loose source route which
18123 			 * reaches us before consuming the whole source route
18124 			 */
18125 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
18126 			if (optval == IPOPT_SSRR) {
18127 				goto bad_src_route;
18128 			}
18129 			/*
18130 			 * Hack: instead of dropping the packet truncate the
18131 			 * source route to what has been used by filling the
18132 			 * rest with IPOPT_NOP.
18133 			 */
18134 			opt[IPOPT_OLEN] = (uint8_t)off;
18135 			while (off < optlen) {
18136 				opt[off++] = IPOPT_NOP;
18137 			}
18138 			break;
18139 		case IPOPT_RR:
18140 			off = opt[IPOPT_OFFSET];
18141 			off--;
18142 			if (optlen < IP_ADDR_LEN ||
18143 			    off > optlen - IP_ADDR_LEN) {
18144 				/* No more room - ignore */
18145 				ip1dbg((
18146 				    "ip_rput_local_options: end of RR\n"));
18147 				break;
18148 			}
18149 			bcopy(&ire->ire_src_addr, (char *)opt + off,
18150 			    IP_ADDR_LEN);
18151 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
18152 			break;
18153 		case IPOPT_TS:
18154 			/* Insert timestamp if there is romm */
18155 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18156 			case IPOPT_TS_TSONLY:
18157 				off = IPOPT_TS_TIMELEN;
18158 				break;
18159 			case IPOPT_TS_PRESPEC:
18160 			case IPOPT_TS_PRESPEC_RFC791:
18161 				/* Verify that the address matched */
18162 				off = opt[IPOPT_OFFSET] - 1;
18163 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
18164 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
18165 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
18166 				    ipst);
18167 				if (dst_ire == NULL) {
18168 					/* Not for us */
18169 					break;
18170 				}
18171 				ire_refrele(dst_ire);
18172 				/* FALLTHRU */
18173 			case IPOPT_TS_TSANDADDR:
18174 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18175 				break;
18176 			default:
18177 				/*
18178 				 * ip_*put_options should have already
18179 				 * dropped this packet.
18180 				 */
18181 				cmn_err(CE_PANIC, "ip_rput_local_options: "
18182 				    "unknown IT - bug in ip_rput_options?\n");
18183 				return (B_TRUE);	/* Keep "lint" happy */
18184 			}
18185 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
18186 				/* Increase overflow counter */
18187 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
18188 				opt[IPOPT_POS_OV_FLG] =
18189 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
18190 				    (off << 4));
18191 				break;
18192 			}
18193 			off = opt[IPOPT_OFFSET] - 1;
18194 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18195 			case IPOPT_TS_PRESPEC:
18196 			case IPOPT_TS_PRESPEC_RFC791:
18197 			case IPOPT_TS_TSANDADDR:
18198 				bcopy(&ire->ire_src_addr, (char *)opt + off,
18199 				    IP_ADDR_LEN);
18200 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
18201 				/* FALLTHRU */
18202 			case IPOPT_TS_TSONLY:
18203 				off = opt[IPOPT_OFFSET] - 1;
18204 				/* Compute # of milliseconds since midnight */
18205 				gethrestime(&now);
18206 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
18207 				    now.tv_nsec / (NANOSEC / MILLISEC);
18208 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
18209 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
18210 				break;
18211 			}
18212 			break;
18213 		}
18214 	}
18215 	return (B_TRUE);
18216 
18217 bad_src_route:
18218 	q = WR(q);
18219 	if (q->q_next != NULL)
18220 		ill = q->q_ptr;
18221 	else
18222 		ill = NULL;
18223 
18224 	/* make sure we clear any indication of a hardware checksum */
18225 	DB_CKSUMFLAGS(mp) = 0;
18226 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
18227 	if (zoneid == ALL_ZONES)
18228 		freemsg(mp);
18229 	else
18230 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18231 	return (B_FALSE);
18232 
18233 }
18234 
18235 /*
18236  * Process IP options in an inbound packet.  If an option affects the
18237  * effective destination address, return the next hop address via dstp.
18238  * Returns -1 if something fails in which case an ICMP error has been sent
18239  * and mp freed.
18240  */
18241 static int
18242 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
18243     ip_stack_t *ipst)
18244 {
18245 	ipoptp_t	opts;
18246 	uchar_t		*opt;
18247 	uint8_t		optval;
18248 	uint8_t		optlen;
18249 	ipaddr_t	dst;
18250 	intptr_t	code = 0;
18251 	ire_t		*ire = NULL;
18252 	zoneid_t	zoneid;
18253 	ill_t		*ill;
18254 
18255 	ip2dbg(("ip_rput_options\n"));
18256 	dst = ipha->ipha_dst;
18257 	for (optval = ipoptp_first(&opts, ipha);
18258 	    optval != IPOPT_EOL;
18259 	    optval = ipoptp_next(&opts)) {
18260 		opt = opts.ipoptp_cur;
18261 		optlen = opts.ipoptp_len;
18262 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
18263 		    optval, optlen));
18264 		/*
18265 		 * Note: we need to verify the checksum before we
18266 		 * modify anything thus this routine only extracts the next
18267 		 * hop dst from any source route.
18268 		 */
18269 		switch (optval) {
18270 			uint32_t off;
18271 		case IPOPT_SSRR:
18272 		case IPOPT_LSRR:
18273 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18274 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
18275 			if (ire == NULL) {
18276 				if (optval == IPOPT_SSRR) {
18277 					ip1dbg(("ip_rput_options: not next"
18278 					    " strict source route 0x%x\n",
18279 					    ntohl(dst)));
18280 					code = (char *)&ipha->ipha_dst -
18281 					    (char *)ipha;
18282 					goto param_prob; /* RouterReq's */
18283 				}
18284 				ip2dbg(("ip_rput_options: "
18285 				    "not next source route 0x%x\n",
18286 				    ntohl(dst)));
18287 				break;
18288 			}
18289 			ire_refrele(ire);
18290 
18291 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18292 				ip1dbg((
18293 				    "ip_rput_options: bad option offset\n"));
18294 				code = (char *)&opt[IPOPT_OLEN] -
18295 				    (char *)ipha;
18296 				goto param_prob;
18297 			}
18298 			off = opt[IPOPT_OFFSET];
18299 			off--;
18300 		redo_srr:
18301 			if (optlen < IP_ADDR_LEN ||
18302 			    off > optlen - IP_ADDR_LEN) {
18303 				/* End of source route */
18304 				ip1dbg(("ip_rput_options: end of SR\n"));
18305 				break;
18306 			}
18307 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
18308 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
18309 			    ntohl(dst)));
18310 
18311 			/*
18312 			 * Check if our address is present more than
18313 			 * once as consecutive hops in source route.
18314 			 * XXX verify per-interface ip_forwarding
18315 			 * for source route?
18316 			 */
18317 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18318 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
18319 
18320 			if (ire != NULL) {
18321 				ire_refrele(ire);
18322 				off += IP_ADDR_LEN;
18323 				goto redo_srr;
18324 			}
18325 
18326 			if (dst == htonl(INADDR_LOOPBACK)) {
18327 				ip1dbg(("ip_rput_options: loopback addr in "
18328 				    "source route!\n"));
18329 				goto bad_src_route;
18330 			}
18331 			/*
18332 			 * For strict: verify that dst is directly
18333 			 * reachable.
18334 			 */
18335 			if (optval == IPOPT_SSRR) {
18336 				ire = ire_ftable_lookup(dst, 0, 0,
18337 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
18338 				    MBLK_GETLABEL(mp),
18339 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
18340 				if (ire == NULL) {
18341 					ip1dbg(("ip_rput_options: SSRR not "
18342 					    "directly reachable: 0x%x\n",
18343 					    ntohl(dst)));
18344 					goto bad_src_route;
18345 				}
18346 				ire_refrele(ire);
18347 			}
18348 			/*
18349 			 * Defer update of the offset and the record route
18350 			 * until the packet is forwarded.
18351 			 */
18352 			break;
18353 		case IPOPT_RR:
18354 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18355 				ip1dbg((
18356 				    "ip_rput_options: bad option offset\n"));
18357 				code = (char *)&opt[IPOPT_OLEN] -
18358 				    (char *)ipha;
18359 				goto param_prob;
18360 			}
18361 			break;
18362 		case IPOPT_TS:
18363 			/*
18364 			 * Verify that length >= 5 and that there is either
18365 			 * room for another timestamp or that the overflow
18366 			 * counter is not maxed out.
18367 			 */
18368 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
18369 			if (optlen < IPOPT_MINLEN_IT) {
18370 				goto param_prob;
18371 			}
18372 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18373 				ip1dbg((
18374 				    "ip_rput_options: bad option offset\n"));
18375 				code = (char *)&opt[IPOPT_OFFSET] -
18376 				    (char *)ipha;
18377 				goto param_prob;
18378 			}
18379 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18380 			case IPOPT_TS_TSONLY:
18381 				off = IPOPT_TS_TIMELEN;
18382 				break;
18383 			case IPOPT_TS_TSANDADDR:
18384 			case IPOPT_TS_PRESPEC:
18385 			case IPOPT_TS_PRESPEC_RFC791:
18386 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18387 				break;
18388 			default:
18389 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
18390 				    (char *)ipha;
18391 				goto param_prob;
18392 			}
18393 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
18394 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
18395 				/*
18396 				 * No room and the overflow counter is 15
18397 				 * already.
18398 				 */
18399 				goto param_prob;
18400 			}
18401 			break;
18402 		}
18403 	}
18404 
18405 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
18406 		*dstp = dst;
18407 		return (0);
18408 	}
18409 
18410 	ip1dbg(("ip_rput_options: error processing IP options."));
18411 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
18412 
18413 param_prob:
18414 	q = WR(q);
18415 	if (q->q_next != NULL)
18416 		ill = q->q_ptr;
18417 	else
18418 		ill = NULL;
18419 
18420 	/* make sure we clear any indication of a hardware checksum */
18421 	DB_CKSUMFLAGS(mp) = 0;
18422 	/* Don't know whether this is for non-global or global/forwarding */
18423 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18424 	if (zoneid == ALL_ZONES)
18425 		freemsg(mp);
18426 	else
18427 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
18428 	return (-1);
18429 
18430 bad_src_route:
18431 	q = WR(q);
18432 	if (q->q_next != NULL)
18433 		ill = q->q_ptr;
18434 	else
18435 		ill = NULL;
18436 
18437 	/* make sure we clear any indication of a hardware checksum */
18438 	DB_CKSUMFLAGS(mp) = 0;
18439 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18440 	if (zoneid == ALL_ZONES)
18441 		freemsg(mp);
18442 	else
18443 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18444 	return (-1);
18445 }
18446 
18447 /*
18448  * IP & ICMP info in >=14 msg's ...
18449  *  - ip fixed part (mib2_ip_t)
18450  *  - icmp fixed part (mib2_icmp_t)
18451  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
18452  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
18453  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
18454  *  - ipRouteAttributeTable (ip 102)	labeled routes
18455  *  - ip multicast membership (ip_member_t)
18456  *  - ip multicast source filtering (ip_grpsrc_t)
18457  *  - igmp fixed part (struct igmpstat)
18458  *  - multicast routing stats (struct mrtstat)
18459  *  - multicast routing vifs (array of struct vifctl)
18460  *  - multicast routing routes (array of struct mfcctl)
18461  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
18462  *					One per ill plus one generic
18463  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
18464  *					One per ill plus one generic
18465  *  - ipv6RouteEntry			all IPv6 IREs
18466  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
18467  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
18468  *  - ipv6AddrEntry			all IPv6 ipifs
18469  *  - ipv6 multicast membership (ipv6_member_t)
18470  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
18471  *
18472  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
18473  *
18474  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
18475  * already filled in by the caller.
18476  * Return value of 0 indicates that no messages were sent and caller
18477  * should free mpctl.
18478  */
18479 int
18480 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level)
18481 {
18482 	ip_stack_t *ipst;
18483 	sctp_stack_t *sctps;
18484 
18485 	if (q->q_next != NULL) {
18486 		ipst = ILLQ_TO_IPST(q);
18487 	} else {
18488 		ipst = CONNQ_TO_IPST(q);
18489 	}
18490 	ASSERT(ipst != NULL);
18491 	sctps = ipst->ips_netstack->netstack_sctp;
18492 
18493 	if (mpctl == NULL || mpctl->b_cont == NULL) {
18494 		return (0);
18495 	}
18496 
18497 	/*
18498 	 * For the purposes of the (broken) packet shell use
18499 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
18500 	 * to make TCP and UDP appear first in the list of mib items.
18501 	 * TBD: We could expand this and use it in netstat so that
18502 	 * the kernel doesn't have to produce large tables (connections,
18503 	 * routes, etc) when netstat only wants the statistics or a particular
18504 	 * table.
18505 	 */
18506 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
18507 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
18508 			return (1);
18509 		}
18510 	}
18511 
18512 	if (level != MIB2_TCP) {
18513 		if ((mpctl = udp_snmp_get(q, mpctl)) == NULL) {
18514 			return (1);
18515 		}
18516 	}
18517 
18518 	if (level != MIB2_UDP) {
18519 		if ((mpctl = tcp_snmp_get(q, mpctl)) == NULL) {
18520 			return (1);
18521 		}
18522 	}
18523 
18524 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
18525 	    ipst)) == NULL) {
18526 		return (1);
18527 	}
18528 
18529 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
18530 		return (1);
18531 	}
18532 
18533 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
18534 		return (1);
18535 	}
18536 
18537 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
18538 		return (1);
18539 	}
18540 
18541 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
18542 		return (1);
18543 	}
18544 
18545 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
18546 		return (1);
18547 	}
18548 
18549 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
18550 		return (1);
18551 	}
18552 
18553 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
18554 		return (1);
18555 	}
18556 
18557 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
18558 		return (1);
18559 	}
18560 
18561 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18562 		return (1);
18563 	}
18564 
18565 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18566 		return (1);
18567 	}
18568 
18569 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18570 		return (1);
18571 	}
18572 
18573 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18574 		return (1);
18575 	}
18576 
18577 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18578 		return (1);
18579 	}
18580 
18581 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, ipst)) == NULL) {
18582 		return (1);
18583 	}
18584 
18585 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, ipst);
18586 	if (mpctl == NULL) {
18587 		return (1);
18588 	}
18589 
18590 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18591 		return (1);
18592 	}
18593 	freemsg(mpctl);
18594 	return (1);
18595 }
18596 
18597 
18598 /* Get global (legacy) IPv4 statistics */
18599 static mblk_t *
18600 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18601     ip_stack_t *ipst)
18602 {
18603 	mib2_ip_t		old_ip_mib;
18604 	struct opthdr		*optp;
18605 	mblk_t			*mp2ctl;
18606 
18607 	/*
18608 	 * make a copy of the original message
18609 	 */
18610 	mp2ctl = copymsg(mpctl);
18611 
18612 	/* fixed length IP structure... */
18613 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18614 	optp->level = MIB2_IP;
18615 	optp->name = 0;
18616 	SET_MIB(old_ip_mib.ipForwarding,
18617 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18618 	SET_MIB(old_ip_mib.ipDefaultTTL,
18619 	    (uint32_t)ipst->ips_ip_def_ttl);
18620 	SET_MIB(old_ip_mib.ipReasmTimeout,
18621 	    ipst->ips_ip_g_frag_timeout);
18622 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18623 	    sizeof (mib2_ipAddrEntry_t));
18624 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18625 	    sizeof (mib2_ipRouteEntry_t));
18626 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18627 	    sizeof (mib2_ipNetToMediaEntry_t));
18628 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18629 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18630 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18631 	    sizeof (mib2_ipAttributeEntry_t));
18632 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18633 
18634 	/*
18635 	 * Grab the statistics from the new IP MIB
18636 	 */
18637 	SET_MIB(old_ip_mib.ipInReceives,
18638 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18639 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18640 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18641 	SET_MIB(old_ip_mib.ipForwDatagrams,
18642 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18643 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18644 	    ipmib->ipIfStatsInUnknownProtos);
18645 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18646 	SET_MIB(old_ip_mib.ipInDelivers,
18647 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18648 	SET_MIB(old_ip_mib.ipOutRequests,
18649 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18650 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18651 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18652 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18653 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18654 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18655 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18656 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18657 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18658 
18659 	/* ipRoutingDiscards is not being used */
18660 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18661 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18662 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18663 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18664 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18665 	    ipmib->ipIfStatsReasmDuplicates);
18666 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18667 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18668 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18669 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18670 	SET_MIB(old_ip_mib.rawipInOverflows,
18671 	    ipmib->rawipIfStatsInOverflows);
18672 
18673 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18674 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18675 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18676 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18677 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18678 	    ipmib->ipIfStatsOutSwitchIPVersion);
18679 
18680 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18681 	    (int)sizeof (old_ip_mib))) {
18682 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18683 		    (uint_t)sizeof (old_ip_mib)));
18684 	}
18685 
18686 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18687 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18688 	    (int)optp->level, (int)optp->name, (int)optp->len));
18689 	qreply(q, mpctl);
18690 	return (mp2ctl);
18691 }
18692 
18693 /* Per interface IPv4 statistics */
18694 static mblk_t *
18695 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18696 {
18697 	struct opthdr		*optp;
18698 	mblk_t			*mp2ctl;
18699 	ill_t			*ill;
18700 	ill_walk_context_t	ctx;
18701 	mblk_t			*mp_tail = NULL;
18702 	mib2_ipIfStatsEntry_t	global_ip_mib;
18703 
18704 	/*
18705 	 * Make a copy of the original message
18706 	 */
18707 	mp2ctl = copymsg(mpctl);
18708 
18709 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18710 	optp->level = MIB2_IP;
18711 	optp->name = MIB2_IP_TRAFFIC_STATS;
18712 	/* Include "unknown interface" ip_mib */
18713 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18714 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18715 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18716 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18717 	    (ipst->ips_ip_g_forward ? 1 : 2));
18718 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18719 	    (uint32_t)ipst->ips_ip_def_ttl);
18720 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18721 	    sizeof (mib2_ipIfStatsEntry_t));
18722 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18723 	    sizeof (mib2_ipAddrEntry_t));
18724 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18725 	    sizeof (mib2_ipRouteEntry_t));
18726 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18727 	    sizeof (mib2_ipNetToMediaEntry_t));
18728 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18729 	    sizeof (ip_member_t));
18730 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18731 	    sizeof (ip_grpsrc_t));
18732 
18733 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18734 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18735 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18736 		    "failed to allocate %u bytes\n",
18737 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18738 	}
18739 
18740 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18741 
18742 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18743 	ill = ILL_START_WALK_V4(&ctx, ipst);
18744 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18745 		ill->ill_ip_mib->ipIfStatsIfIndex =
18746 		    ill->ill_phyint->phyint_ifindex;
18747 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18748 		    (ipst->ips_ip_g_forward ? 1 : 2));
18749 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18750 		    (uint32_t)ipst->ips_ip_def_ttl);
18751 
18752 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18753 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18754 		    (char *)ill->ill_ip_mib,
18755 		    (int)sizeof (*ill->ill_ip_mib))) {
18756 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18757 			    "failed to allocate %u bytes\n",
18758 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18759 		}
18760 	}
18761 	rw_exit(&ipst->ips_ill_g_lock);
18762 
18763 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18764 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18765 	    "level %d, name %d, len %d\n",
18766 	    (int)optp->level, (int)optp->name, (int)optp->len));
18767 	qreply(q, mpctl);
18768 
18769 	if (mp2ctl == NULL)
18770 		return (NULL);
18771 
18772 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18773 }
18774 
18775 /* Global IPv4 ICMP statistics */
18776 static mblk_t *
18777 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18778 {
18779 	struct opthdr		*optp;
18780 	mblk_t			*mp2ctl;
18781 
18782 	/*
18783 	 * Make a copy of the original message
18784 	 */
18785 	mp2ctl = copymsg(mpctl);
18786 
18787 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18788 	optp->level = MIB2_ICMP;
18789 	optp->name = 0;
18790 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18791 	    (int)sizeof (ipst->ips_icmp_mib))) {
18792 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18793 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18794 	}
18795 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18796 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18797 	    (int)optp->level, (int)optp->name, (int)optp->len));
18798 	qreply(q, mpctl);
18799 	return (mp2ctl);
18800 }
18801 
18802 /* Global IPv4 IGMP statistics */
18803 static mblk_t *
18804 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18805 {
18806 	struct opthdr		*optp;
18807 	mblk_t			*mp2ctl;
18808 
18809 	/*
18810 	 * make a copy of the original message
18811 	 */
18812 	mp2ctl = copymsg(mpctl);
18813 
18814 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18815 	optp->level = EXPER_IGMP;
18816 	optp->name = 0;
18817 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18818 	    (int)sizeof (ipst->ips_igmpstat))) {
18819 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18820 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18821 	}
18822 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18823 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18824 	    (int)optp->level, (int)optp->name, (int)optp->len));
18825 	qreply(q, mpctl);
18826 	return (mp2ctl);
18827 }
18828 
18829 /* Global IPv4 Multicast Routing statistics */
18830 static mblk_t *
18831 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18832 {
18833 	struct opthdr		*optp;
18834 	mblk_t			*mp2ctl;
18835 
18836 	/*
18837 	 * make a copy of the original message
18838 	 */
18839 	mp2ctl = copymsg(mpctl);
18840 
18841 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18842 	optp->level = EXPER_DVMRP;
18843 	optp->name = 0;
18844 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18845 		ip0dbg(("ip_mroute_stats: failed\n"));
18846 	}
18847 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18848 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18849 	    (int)optp->level, (int)optp->name, (int)optp->len));
18850 	qreply(q, mpctl);
18851 	return (mp2ctl);
18852 }
18853 
18854 /* IPv4 address information */
18855 static mblk_t *
18856 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18857 {
18858 	struct opthdr		*optp;
18859 	mblk_t			*mp2ctl;
18860 	mblk_t			*mp_tail = NULL;
18861 	ill_t			*ill;
18862 	ipif_t			*ipif;
18863 	uint_t			bitval;
18864 	mib2_ipAddrEntry_t	mae;
18865 	zoneid_t		zoneid;
18866 	ill_walk_context_t ctx;
18867 
18868 	/*
18869 	 * make a copy of the original message
18870 	 */
18871 	mp2ctl = copymsg(mpctl);
18872 
18873 	/* ipAddrEntryTable */
18874 
18875 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18876 	optp->level = MIB2_IP;
18877 	optp->name = MIB2_IP_ADDR;
18878 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18879 
18880 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18881 	ill = ILL_START_WALK_V4(&ctx, ipst);
18882 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18883 		for (ipif = ill->ill_ipif; ipif != NULL;
18884 		    ipif = ipif->ipif_next) {
18885 			if (ipif->ipif_zoneid != zoneid &&
18886 			    ipif->ipif_zoneid != ALL_ZONES)
18887 				continue;
18888 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18889 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18890 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18891 
18892 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
18893 			    OCTET_LENGTH);
18894 			mae.ipAdEntIfIndex.o_length =
18895 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18896 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18897 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18898 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18899 			mae.ipAdEntInfo.ae_subnet_len =
18900 			    ip_mask_to_plen(ipif->ipif_net_mask);
18901 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18902 			for (bitval = 1;
18903 			    bitval &&
18904 			    !(bitval & ipif->ipif_brd_addr);
18905 			    bitval <<= 1)
18906 				noop;
18907 			mae.ipAdEntBcastAddr = bitval;
18908 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18909 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18910 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18911 			mae.ipAdEntInfo.ae_broadcast_addr =
18912 			    ipif->ipif_brd_addr;
18913 			mae.ipAdEntInfo.ae_pp_dst_addr =
18914 			    ipif->ipif_pp_dst_addr;
18915 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18916 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18917 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18918 
18919 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18920 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18921 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18922 				    "allocate %u bytes\n",
18923 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18924 			}
18925 		}
18926 	}
18927 	rw_exit(&ipst->ips_ill_g_lock);
18928 
18929 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18930 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18931 	    (int)optp->level, (int)optp->name, (int)optp->len));
18932 	qreply(q, mpctl);
18933 	return (mp2ctl);
18934 }
18935 
18936 /* IPv6 address information */
18937 static mblk_t *
18938 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18939 {
18940 	struct opthdr		*optp;
18941 	mblk_t			*mp2ctl;
18942 	mblk_t			*mp_tail = NULL;
18943 	ill_t			*ill;
18944 	ipif_t			*ipif;
18945 	mib2_ipv6AddrEntry_t	mae6;
18946 	zoneid_t		zoneid;
18947 	ill_walk_context_t	ctx;
18948 
18949 	/*
18950 	 * make a copy of the original message
18951 	 */
18952 	mp2ctl = copymsg(mpctl);
18953 
18954 	/* ipv6AddrEntryTable */
18955 
18956 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18957 	optp->level = MIB2_IP6;
18958 	optp->name = MIB2_IP6_ADDR;
18959 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18960 
18961 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18962 	ill = ILL_START_WALK_V6(&ctx, ipst);
18963 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18964 		for (ipif = ill->ill_ipif; ipif != NULL;
18965 		    ipif = ipif->ipif_next) {
18966 			if (ipif->ipif_zoneid != zoneid &&
18967 			    ipif->ipif_zoneid != ALL_ZONES)
18968 				continue;
18969 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18970 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18971 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18972 
18973 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
18974 			    OCTET_LENGTH);
18975 			mae6.ipv6AddrIfIndex.o_length =
18976 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18977 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18978 			mae6.ipv6AddrPfxLength =
18979 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18980 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18981 			mae6.ipv6AddrInfo.ae_subnet_len =
18982 			    mae6.ipv6AddrPfxLength;
18983 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18984 
18985 			/* Type: stateless(1), stateful(2), unknown(3) */
18986 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18987 				mae6.ipv6AddrType = 1;
18988 			else
18989 				mae6.ipv6AddrType = 2;
18990 			/* Anycast: true(1), false(2) */
18991 			if (ipif->ipif_flags & IPIF_ANYCAST)
18992 				mae6.ipv6AddrAnycastFlag = 1;
18993 			else
18994 				mae6.ipv6AddrAnycastFlag = 2;
18995 
18996 			/*
18997 			 * Address status: preferred(1), deprecated(2),
18998 			 * invalid(3), inaccessible(4), unknown(5)
18999 			 */
19000 			if (ipif->ipif_flags & IPIF_NOLOCAL)
19001 				mae6.ipv6AddrStatus = 3;
19002 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
19003 				mae6.ipv6AddrStatus = 2;
19004 			else
19005 				mae6.ipv6AddrStatus = 1;
19006 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
19007 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
19008 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
19009 			    ipif->ipif_v6pp_dst_addr;
19010 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
19011 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
19012 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
19013 			mae6.ipv6AddrIdentifier = ill->ill_token;
19014 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
19015 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
19016 			mae6.ipv6AddrRetransmitTime =
19017 			    ill->ill_reachable_retrans_time;
19018 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19019 			    (char *)&mae6,
19020 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
19021 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
19022 				    "allocate %u bytes\n",
19023 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
19024 			}
19025 		}
19026 	}
19027 	rw_exit(&ipst->ips_ill_g_lock);
19028 
19029 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19030 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
19031 	    (int)optp->level, (int)optp->name, (int)optp->len));
19032 	qreply(q, mpctl);
19033 	return (mp2ctl);
19034 }
19035 
19036 /* IPv4 multicast group membership. */
19037 static mblk_t *
19038 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19039 {
19040 	struct opthdr		*optp;
19041 	mblk_t			*mp2ctl;
19042 	ill_t			*ill;
19043 	ipif_t			*ipif;
19044 	ilm_t			*ilm;
19045 	ip_member_t		ipm;
19046 	mblk_t			*mp_tail = NULL;
19047 	ill_walk_context_t	ctx;
19048 	zoneid_t		zoneid;
19049 
19050 	/*
19051 	 * make a copy of the original message
19052 	 */
19053 	mp2ctl = copymsg(mpctl);
19054 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19055 
19056 	/* ipGroupMember table */
19057 	optp = (struct opthdr *)&mpctl->b_rptr[
19058 	    sizeof (struct T_optmgmt_ack)];
19059 	optp->level = MIB2_IP;
19060 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
19061 
19062 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19063 	ill = ILL_START_WALK_V4(&ctx, ipst);
19064 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19065 		ILM_WALKER_HOLD(ill);
19066 		for (ipif = ill->ill_ipif; ipif != NULL;
19067 		    ipif = ipif->ipif_next) {
19068 			if (ipif->ipif_zoneid != zoneid &&
19069 			    ipif->ipif_zoneid != ALL_ZONES)
19070 				continue;	/* not this zone */
19071 			ipif_get_name(ipif, ipm.ipGroupMemberIfIndex.o_bytes,
19072 			    OCTET_LENGTH);
19073 			ipm.ipGroupMemberIfIndex.o_length =
19074 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
19075 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
19076 				ASSERT(ilm->ilm_ipif != NULL);
19077 				ASSERT(ilm->ilm_ill == NULL);
19078 				if (ilm->ilm_ipif != ipif)
19079 					continue;
19080 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
19081 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
19082 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
19083 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19084 				    (char *)&ipm, (int)sizeof (ipm))) {
19085 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
19086 					    "failed to allocate %u bytes\n",
19087 					    (uint_t)sizeof (ipm)));
19088 				}
19089 			}
19090 		}
19091 		ILM_WALKER_RELE(ill);
19092 	}
19093 	rw_exit(&ipst->ips_ill_g_lock);
19094 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19095 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19096 	    (int)optp->level, (int)optp->name, (int)optp->len));
19097 	qreply(q, mpctl);
19098 	return (mp2ctl);
19099 }
19100 
19101 /* IPv6 multicast group membership. */
19102 static mblk_t *
19103 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19104 {
19105 	struct opthdr		*optp;
19106 	mblk_t			*mp2ctl;
19107 	ill_t			*ill;
19108 	ilm_t			*ilm;
19109 	ipv6_member_t		ipm6;
19110 	mblk_t			*mp_tail = NULL;
19111 	ill_walk_context_t	ctx;
19112 	zoneid_t		zoneid;
19113 
19114 	/*
19115 	 * make a copy of the original message
19116 	 */
19117 	mp2ctl = copymsg(mpctl);
19118 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19119 
19120 	/* ip6GroupMember table */
19121 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19122 	optp->level = MIB2_IP6;
19123 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
19124 
19125 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19126 	ill = ILL_START_WALK_V6(&ctx, ipst);
19127 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19128 		ILM_WALKER_HOLD(ill);
19129 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
19130 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
19131 			ASSERT(ilm->ilm_ipif == NULL);
19132 			ASSERT(ilm->ilm_ill != NULL);
19133 			if (ilm->ilm_zoneid != zoneid)
19134 				continue;	/* not this zone */
19135 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
19136 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
19137 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
19138 			if (!snmp_append_data2(mpctl->b_cont,
19139 			    &mp_tail,
19140 			    (char *)&ipm6, (int)sizeof (ipm6))) {
19141 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
19142 				    "failed to allocate %u bytes\n",
19143 				    (uint_t)sizeof (ipm6)));
19144 			}
19145 		}
19146 		ILM_WALKER_RELE(ill);
19147 	}
19148 	rw_exit(&ipst->ips_ill_g_lock);
19149 
19150 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19151 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19152 	    (int)optp->level, (int)optp->name, (int)optp->len));
19153 	qreply(q, mpctl);
19154 	return (mp2ctl);
19155 }
19156 
19157 /* IP multicast filtered sources */
19158 static mblk_t *
19159 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19160 {
19161 	struct opthdr		*optp;
19162 	mblk_t			*mp2ctl;
19163 	ill_t			*ill;
19164 	ipif_t			*ipif;
19165 	ilm_t			*ilm;
19166 	ip_grpsrc_t		ips;
19167 	mblk_t			*mp_tail = NULL;
19168 	ill_walk_context_t	ctx;
19169 	zoneid_t		zoneid;
19170 	int			i;
19171 	slist_t			*sl;
19172 
19173 	/*
19174 	 * make a copy of the original message
19175 	 */
19176 	mp2ctl = copymsg(mpctl);
19177 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19178 
19179 	/* ipGroupSource table */
19180 	optp = (struct opthdr *)&mpctl->b_rptr[
19181 	    sizeof (struct T_optmgmt_ack)];
19182 	optp->level = MIB2_IP;
19183 	optp->name = EXPER_IP_GROUP_SOURCES;
19184 
19185 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19186 	ill = ILL_START_WALK_V4(&ctx, ipst);
19187 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19188 		ILM_WALKER_HOLD(ill);
19189 		for (ipif = ill->ill_ipif; ipif != NULL;
19190 		    ipif = ipif->ipif_next) {
19191 			if (ipif->ipif_zoneid != zoneid)
19192 				continue;	/* not this zone */
19193 			ipif_get_name(ipif, ips.ipGroupSourceIfIndex.o_bytes,
19194 			    OCTET_LENGTH);
19195 			ips.ipGroupSourceIfIndex.o_length =
19196 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
19197 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
19198 				ASSERT(ilm->ilm_ipif != NULL);
19199 				ASSERT(ilm->ilm_ill == NULL);
19200 				sl = ilm->ilm_filter;
19201 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
19202 					continue;
19203 				ips.ipGroupSourceGroup = ilm->ilm_addr;
19204 				for (i = 0; i < sl->sl_numsrc; i++) {
19205 					if (!IN6_IS_ADDR_V4MAPPED(
19206 					    &sl->sl_addr[i]))
19207 						continue;
19208 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
19209 					    ips.ipGroupSourceAddress);
19210 					if (snmp_append_data2(mpctl->b_cont,
19211 					    &mp_tail, (char *)&ips,
19212 					    (int)sizeof (ips)) == 0) {
19213 						ip1dbg(("ip_snmp_get_mib2_"
19214 						    "ip_group_src: failed to "
19215 						    "allocate %u bytes\n",
19216 						    (uint_t)sizeof (ips)));
19217 					}
19218 				}
19219 			}
19220 		}
19221 		ILM_WALKER_RELE(ill);
19222 	}
19223 	rw_exit(&ipst->ips_ill_g_lock);
19224 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19225 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19226 	    (int)optp->level, (int)optp->name, (int)optp->len));
19227 	qreply(q, mpctl);
19228 	return (mp2ctl);
19229 }
19230 
19231 /* IPv6 multicast filtered sources. */
19232 static mblk_t *
19233 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19234 {
19235 	struct opthdr		*optp;
19236 	mblk_t			*mp2ctl;
19237 	ill_t			*ill;
19238 	ilm_t			*ilm;
19239 	ipv6_grpsrc_t		ips6;
19240 	mblk_t			*mp_tail = NULL;
19241 	ill_walk_context_t	ctx;
19242 	zoneid_t		zoneid;
19243 	int			i;
19244 	slist_t			*sl;
19245 
19246 	/*
19247 	 * make a copy of the original message
19248 	 */
19249 	mp2ctl = copymsg(mpctl);
19250 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19251 
19252 	/* ip6GroupMember table */
19253 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19254 	optp->level = MIB2_IP6;
19255 	optp->name = EXPER_IP6_GROUP_SOURCES;
19256 
19257 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19258 	ill = ILL_START_WALK_V6(&ctx, ipst);
19259 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19260 		ILM_WALKER_HOLD(ill);
19261 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
19262 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
19263 			ASSERT(ilm->ilm_ipif == NULL);
19264 			ASSERT(ilm->ilm_ill != NULL);
19265 			sl = ilm->ilm_filter;
19266 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
19267 				continue;
19268 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
19269 			for (i = 0; i < sl->sl_numsrc; i++) {
19270 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
19271 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19272 				    (char *)&ips6, (int)sizeof (ips6))) {
19273 					ip1dbg(("ip_snmp_get_mib2_ip6_"
19274 					    "group_src: failed to allocate "
19275 					    "%u bytes\n",
19276 					    (uint_t)sizeof (ips6)));
19277 				}
19278 			}
19279 		}
19280 		ILM_WALKER_RELE(ill);
19281 	}
19282 	rw_exit(&ipst->ips_ill_g_lock);
19283 
19284 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19285 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19286 	    (int)optp->level, (int)optp->name, (int)optp->len));
19287 	qreply(q, mpctl);
19288 	return (mp2ctl);
19289 }
19290 
19291 /* Multicast routing virtual interface table. */
19292 static mblk_t *
19293 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19294 {
19295 	struct opthdr		*optp;
19296 	mblk_t			*mp2ctl;
19297 
19298 	/*
19299 	 * make a copy of the original message
19300 	 */
19301 	mp2ctl = copymsg(mpctl);
19302 
19303 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19304 	optp->level = EXPER_DVMRP;
19305 	optp->name = EXPER_DVMRP_VIF;
19306 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
19307 		ip0dbg(("ip_mroute_vif: failed\n"));
19308 	}
19309 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19310 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
19311 	    (int)optp->level, (int)optp->name, (int)optp->len));
19312 	qreply(q, mpctl);
19313 	return (mp2ctl);
19314 }
19315 
19316 /* Multicast routing table. */
19317 static mblk_t *
19318 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19319 {
19320 	struct opthdr		*optp;
19321 	mblk_t			*mp2ctl;
19322 
19323 	/*
19324 	 * make a copy of the original message
19325 	 */
19326 	mp2ctl = copymsg(mpctl);
19327 
19328 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19329 	optp->level = EXPER_DVMRP;
19330 	optp->name = EXPER_DVMRP_MRT;
19331 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
19332 		ip0dbg(("ip_mroute_mrt: failed\n"));
19333 	}
19334 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19335 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
19336 	    (int)optp->level, (int)optp->name, (int)optp->len));
19337 	qreply(q, mpctl);
19338 	return (mp2ctl);
19339 }
19340 
19341 /*
19342  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
19343  * in one IRE walk.
19344  */
19345 static mblk_t *
19346 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19347 {
19348 	struct opthdr	*optp;
19349 	mblk_t		*mp2ctl;	/* Returned */
19350 	mblk_t		*mp3ctl;	/* nettomedia */
19351 	mblk_t		*mp4ctl;	/* routeattrs */
19352 	iproutedata_t	ird;
19353 	zoneid_t	zoneid;
19354 
19355 	/*
19356 	 * make copies of the original message
19357 	 *	- mp2ctl is returned unchanged to the caller for his use
19358 	 *	- mpctl is sent upstream as ipRouteEntryTable
19359 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
19360 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
19361 	 */
19362 	mp2ctl = copymsg(mpctl);
19363 	mp3ctl = copymsg(mpctl);
19364 	mp4ctl = copymsg(mpctl);
19365 	if (mp3ctl == NULL || mp4ctl == NULL) {
19366 		freemsg(mp4ctl);
19367 		freemsg(mp3ctl);
19368 		freemsg(mp2ctl);
19369 		freemsg(mpctl);
19370 		return (NULL);
19371 	}
19372 
19373 	bzero(&ird, sizeof (ird));
19374 
19375 	ird.ird_route.lp_head = mpctl->b_cont;
19376 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19377 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19378 
19379 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19380 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
19381 
19382 	/* ipRouteEntryTable in mpctl */
19383 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19384 	optp->level = MIB2_IP;
19385 	optp->name = MIB2_IP_ROUTE;
19386 	optp->len = msgdsize(ird.ird_route.lp_head);
19387 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19388 	    (int)optp->level, (int)optp->name, (int)optp->len));
19389 	qreply(q, mpctl);
19390 
19391 	/* ipNetToMediaEntryTable in mp3ctl */
19392 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19393 	optp->level = MIB2_IP;
19394 	optp->name = MIB2_IP_MEDIA;
19395 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19396 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19397 	    (int)optp->level, (int)optp->name, (int)optp->len));
19398 	qreply(q, mp3ctl);
19399 
19400 	/* ipRouteAttributeTable in mp4ctl */
19401 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19402 	optp->level = MIB2_IP;
19403 	optp->name = EXPER_IP_RTATTR;
19404 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19405 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19406 	    (int)optp->level, (int)optp->name, (int)optp->len));
19407 	if (optp->len == 0)
19408 		freemsg(mp4ctl);
19409 	else
19410 		qreply(q, mp4ctl);
19411 
19412 	return (mp2ctl);
19413 }
19414 
19415 /*
19416  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
19417  * ipv6NetToMediaEntryTable in an NDP walk.
19418  */
19419 static mblk_t *
19420 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19421 {
19422 	struct opthdr	*optp;
19423 	mblk_t		*mp2ctl;	/* Returned */
19424 	mblk_t		*mp3ctl;	/* nettomedia */
19425 	mblk_t		*mp4ctl;	/* routeattrs */
19426 	iproutedata_t	ird;
19427 	zoneid_t	zoneid;
19428 
19429 	/*
19430 	 * make copies of the original message
19431 	 *	- mp2ctl is returned unchanged to the caller for his use
19432 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
19433 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
19434 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
19435 	 */
19436 	mp2ctl = copymsg(mpctl);
19437 	mp3ctl = copymsg(mpctl);
19438 	mp4ctl = copymsg(mpctl);
19439 	if (mp3ctl == NULL || mp4ctl == NULL) {
19440 		freemsg(mp4ctl);
19441 		freemsg(mp3ctl);
19442 		freemsg(mp2ctl);
19443 		freemsg(mpctl);
19444 		return (NULL);
19445 	}
19446 
19447 	bzero(&ird, sizeof (ird));
19448 
19449 	ird.ird_route.lp_head = mpctl->b_cont;
19450 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19451 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19452 
19453 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19454 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
19455 
19456 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19457 	optp->level = MIB2_IP6;
19458 	optp->name = MIB2_IP6_ROUTE;
19459 	optp->len = msgdsize(ird.ird_route.lp_head);
19460 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19461 	    (int)optp->level, (int)optp->name, (int)optp->len));
19462 	qreply(q, mpctl);
19463 
19464 	/* ipv6NetToMediaEntryTable in mp3ctl */
19465 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
19466 
19467 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19468 	optp->level = MIB2_IP6;
19469 	optp->name = MIB2_IP6_MEDIA;
19470 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19471 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19472 	    (int)optp->level, (int)optp->name, (int)optp->len));
19473 	qreply(q, mp3ctl);
19474 
19475 	/* ipv6RouteAttributeTable in mp4ctl */
19476 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19477 	optp->level = MIB2_IP6;
19478 	optp->name = EXPER_IP_RTATTR;
19479 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19480 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19481 	    (int)optp->level, (int)optp->name, (int)optp->len));
19482 	if (optp->len == 0)
19483 		freemsg(mp4ctl);
19484 	else
19485 		qreply(q, mp4ctl);
19486 
19487 	return (mp2ctl);
19488 }
19489 
19490 /*
19491  * IPv6 mib: One per ill
19492  */
19493 static mblk_t *
19494 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19495 {
19496 	struct opthdr		*optp;
19497 	mblk_t			*mp2ctl;
19498 	ill_t			*ill;
19499 	ill_walk_context_t	ctx;
19500 	mblk_t			*mp_tail = NULL;
19501 
19502 	/*
19503 	 * Make a copy of the original message
19504 	 */
19505 	mp2ctl = copymsg(mpctl);
19506 
19507 	/* fixed length IPv6 structure ... */
19508 
19509 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19510 	optp->level = MIB2_IP6;
19511 	optp->name = 0;
19512 	/* Include "unknown interface" ip6_mib */
19513 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
19514 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
19515 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
19516 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
19517 	    ipst->ips_ipv6_forward ? 1 : 2);
19518 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
19519 	    ipst->ips_ipv6_def_hops);
19520 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
19521 	    sizeof (mib2_ipIfStatsEntry_t));
19522 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
19523 	    sizeof (mib2_ipv6AddrEntry_t));
19524 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
19525 	    sizeof (mib2_ipv6RouteEntry_t));
19526 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
19527 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19528 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
19529 	    sizeof (ipv6_member_t));
19530 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
19531 	    sizeof (ipv6_grpsrc_t));
19532 
19533 	/*
19534 	 * Synchronize 64- and 32-bit counters
19535 	 */
19536 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
19537 	    ipIfStatsHCInReceives);
19538 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
19539 	    ipIfStatsHCInDelivers);
19540 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
19541 	    ipIfStatsHCOutRequests);
19542 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
19543 	    ipIfStatsHCOutForwDatagrams);
19544 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
19545 	    ipIfStatsHCOutMcastPkts);
19546 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19547 	    ipIfStatsHCInMcastPkts);
19548 
19549 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19550 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19551 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19552 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19553 	}
19554 
19555 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19556 	ill = ILL_START_WALK_V6(&ctx, ipst);
19557 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19558 		ill->ill_ip_mib->ipIfStatsIfIndex =
19559 		    ill->ill_phyint->phyint_ifindex;
19560 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19561 		    ipst->ips_ipv6_forward ? 1 : 2);
19562 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19563 		    ill->ill_max_hops);
19564 
19565 		/*
19566 		 * Synchronize 64- and 32-bit counters
19567 		 */
19568 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19569 		    ipIfStatsHCInReceives);
19570 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19571 		    ipIfStatsHCInDelivers);
19572 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19573 		    ipIfStatsHCOutRequests);
19574 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19575 		    ipIfStatsHCOutForwDatagrams);
19576 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19577 		    ipIfStatsHCOutMcastPkts);
19578 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19579 		    ipIfStatsHCInMcastPkts);
19580 
19581 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19582 		    (char *)ill->ill_ip_mib,
19583 		    (int)sizeof (*ill->ill_ip_mib))) {
19584 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19585 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
19586 		}
19587 	}
19588 	rw_exit(&ipst->ips_ill_g_lock);
19589 
19590 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19591 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19592 	    (int)optp->level, (int)optp->name, (int)optp->len));
19593 	qreply(q, mpctl);
19594 	return (mp2ctl);
19595 }
19596 
19597 /*
19598  * ICMPv6 mib: One per ill
19599  */
19600 static mblk_t *
19601 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19602 {
19603 	struct opthdr		*optp;
19604 	mblk_t			*mp2ctl;
19605 	ill_t			*ill;
19606 	ill_walk_context_t	ctx;
19607 	mblk_t			*mp_tail = NULL;
19608 	/*
19609 	 * Make a copy of the original message
19610 	 */
19611 	mp2ctl = copymsg(mpctl);
19612 
19613 	/* fixed length ICMPv6 structure ... */
19614 
19615 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19616 	optp->level = MIB2_ICMP6;
19617 	optp->name = 0;
19618 	/* Include "unknown interface" icmp6_mib */
19619 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19620 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19621 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19622 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19623 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19624 	    (char *)&ipst->ips_icmp6_mib,
19625 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19626 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19627 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19628 	}
19629 
19630 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19631 	ill = ILL_START_WALK_V6(&ctx, ipst);
19632 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19633 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19634 		    ill->ill_phyint->phyint_ifindex;
19635 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19636 		    (char *)ill->ill_icmp6_mib,
19637 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19638 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19639 			    "%u bytes\n",
19640 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19641 		}
19642 	}
19643 	rw_exit(&ipst->ips_ill_g_lock);
19644 
19645 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19646 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19647 	    (int)optp->level, (int)optp->name, (int)optp->len));
19648 	qreply(q, mpctl);
19649 	return (mp2ctl);
19650 }
19651 
19652 /*
19653  * ire_walk routine to create both ipRouteEntryTable and
19654  * ipRouteAttributeTable in one IRE walk
19655  */
19656 static void
19657 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19658 {
19659 	ill_t				*ill;
19660 	ipif_t				*ipif;
19661 	mib2_ipRouteEntry_t		*re;
19662 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19663 	ipaddr_t			gw_addr;
19664 	tsol_ire_gw_secattr_t		*attrp;
19665 	tsol_gc_t			*gc = NULL;
19666 	tsol_gcgrp_t			*gcgrp = NULL;
19667 	uint_t				sacnt = 0;
19668 	int				i;
19669 
19670 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19671 
19672 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19673 		return;
19674 
19675 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19676 		mutex_enter(&attrp->igsa_lock);
19677 		if ((gc = attrp->igsa_gc) != NULL) {
19678 			gcgrp = gc->gc_grp;
19679 			ASSERT(gcgrp != NULL);
19680 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19681 			sacnt = 1;
19682 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19683 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19684 			gc = gcgrp->gcgrp_head;
19685 			sacnt = gcgrp->gcgrp_count;
19686 		}
19687 		mutex_exit(&attrp->igsa_lock);
19688 
19689 		/* do nothing if there's no gc to report */
19690 		if (gc == NULL) {
19691 			ASSERT(sacnt == 0);
19692 			if (gcgrp != NULL) {
19693 				/* we might as well drop the lock now */
19694 				rw_exit(&gcgrp->gcgrp_rwlock);
19695 				gcgrp = NULL;
19696 			}
19697 			attrp = NULL;
19698 		}
19699 
19700 		ASSERT(gc == NULL || (gcgrp != NULL &&
19701 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19702 	}
19703 	ASSERT(sacnt == 0 || gc != NULL);
19704 
19705 	if (sacnt != 0 &&
19706 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19707 		kmem_free(re, sizeof (*re));
19708 		rw_exit(&gcgrp->gcgrp_rwlock);
19709 		return;
19710 	}
19711 
19712 	/*
19713 	 * Return all IRE types for route table... let caller pick and choose
19714 	 */
19715 	re->ipRouteDest = ire->ire_addr;
19716 	ipif = ire->ire_ipif;
19717 	re->ipRouteIfIndex.o_length = 0;
19718 	if (ire->ire_type == IRE_CACHE) {
19719 		ill = (ill_t *)ire->ire_stq->q_ptr;
19720 		re->ipRouteIfIndex.o_length =
19721 		    ill->ill_name_length == 0 ? 0 :
19722 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19723 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19724 		    re->ipRouteIfIndex.o_length);
19725 	} else if (ipif != NULL) {
19726 		ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
19727 		re->ipRouteIfIndex.o_length =
19728 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19729 	}
19730 	re->ipRouteMetric1 = -1;
19731 	re->ipRouteMetric2 = -1;
19732 	re->ipRouteMetric3 = -1;
19733 	re->ipRouteMetric4 = -1;
19734 
19735 	gw_addr = ire->ire_gateway_addr;
19736 
19737 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19738 		re->ipRouteNextHop = ire->ire_src_addr;
19739 	else
19740 		re->ipRouteNextHop = gw_addr;
19741 	/* indirect(4), direct(3), or invalid(2) */
19742 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19743 		re->ipRouteType = 2;
19744 	else
19745 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19746 	re->ipRouteProto = -1;
19747 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19748 	re->ipRouteMask = ire->ire_mask;
19749 	re->ipRouteMetric5 = -1;
19750 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19751 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19752 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19753 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19754 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19755 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19756 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19757 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19758 
19759 	if (ire->ire_flags & RTF_DYNAMIC) {
19760 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19761 	} else {
19762 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19763 	}
19764 
19765 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19766 	    (char *)re, (int)sizeof (*re))) {
19767 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19768 		    (uint_t)sizeof (*re)));
19769 	}
19770 
19771 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19772 		iaeptr->iae_routeidx = ird->ird_idx;
19773 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19774 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19775 	}
19776 
19777 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19778 	    (char *)iae, sacnt * sizeof (*iae))) {
19779 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19780 		    (unsigned)(sacnt * sizeof (*iae))));
19781 	}
19782 
19783 	/* bump route index for next pass */
19784 	ird->ird_idx++;
19785 
19786 	kmem_free(re, sizeof (*re));
19787 	if (sacnt != 0)
19788 		kmem_free(iae, sacnt * sizeof (*iae));
19789 
19790 	if (gcgrp != NULL)
19791 		rw_exit(&gcgrp->gcgrp_rwlock);
19792 }
19793 
19794 /*
19795  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19796  */
19797 static void
19798 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19799 {
19800 	ill_t				*ill;
19801 	ipif_t				*ipif;
19802 	mib2_ipv6RouteEntry_t		*re;
19803 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19804 	in6_addr_t			gw_addr_v6;
19805 	tsol_ire_gw_secattr_t		*attrp;
19806 	tsol_gc_t			*gc = NULL;
19807 	tsol_gcgrp_t			*gcgrp = NULL;
19808 	uint_t				sacnt = 0;
19809 	int				i;
19810 
19811 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19812 
19813 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19814 		return;
19815 
19816 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19817 		mutex_enter(&attrp->igsa_lock);
19818 		if ((gc = attrp->igsa_gc) != NULL) {
19819 			gcgrp = gc->gc_grp;
19820 			ASSERT(gcgrp != NULL);
19821 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19822 			sacnt = 1;
19823 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19824 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19825 			gc = gcgrp->gcgrp_head;
19826 			sacnt = gcgrp->gcgrp_count;
19827 		}
19828 		mutex_exit(&attrp->igsa_lock);
19829 
19830 		/* do nothing if there's no gc to report */
19831 		if (gc == NULL) {
19832 			ASSERT(sacnt == 0);
19833 			if (gcgrp != NULL) {
19834 				/* we might as well drop the lock now */
19835 				rw_exit(&gcgrp->gcgrp_rwlock);
19836 				gcgrp = NULL;
19837 			}
19838 			attrp = NULL;
19839 		}
19840 
19841 		ASSERT(gc == NULL || (gcgrp != NULL &&
19842 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19843 	}
19844 	ASSERT(sacnt == 0 || gc != NULL);
19845 
19846 	if (sacnt != 0 &&
19847 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19848 		kmem_free(re, sizeof (*re));
19849 		rw_exit(&gcgrp->gcgrp_rwlock);
19850 		return;
19851 	}
19852 
19853 	/*
19854 	 * Return all IRE types for route table... let caller pick and choose
19855 	 */
19856 	re->ipv6RouteDest = ire->ire_addr_v6;
19857 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19858 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19859 	re->ipv6RouteIfIndex.o_length = 0;
19860 	ipif = ire->ire_ipif;
19861 	if (ire->ire_type == IRE_CACHE) {
19862 		ill = (ill_t *)ire->ire_stq->q_ptr;
19863 		re->ipv6RouteIfIndex.o_length =
19864 		    ill->ill_name_length == 0 ? 0 :
19865 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19866 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19867 		    re->ipv6RouteIfIndex.o_length);
19868 	} else if (ipif != NULL) {
19869 		ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
19870 		re->ipv6RouteIfIndex.o_length =
19871 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19872 	}
19873 
19874 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19875 
19876 	mutex_enter(&ire->ire_lock);
19877 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19878 	mutex_exit(&ire->ire_lock);
19879 
19880 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19881 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19882 	else
19883 		re->ipv6RouteNextHop = gw_addr_v6;
19884 
19885 	/* remote(4), local(3), or discard(2) */
19886 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19887 		re->ipv6RouteType = 2;
19888 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19889 		re->ipv6RouteType = 3;
19890 	else
19891 		re->ipv6RouteType = 4;
19892 
19893 	re->ipv6RouteProtocol	= -1;
19894 	re->ipv6RoutePolicy	= 0;
19895 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19896 	re->ipv6RouteNextHopRDI	= 0;
19897 	re->ipv6RouteWeight	= 0;
19898 	re->ipv6RouteMetric	= 0;
19899 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19900 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19901 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19902 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19903 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19904 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19905 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19906 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19907 
19908 	if (ire->ire_flags & RTF_DYNAMIC) {
19909 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19910 	} else {
19911 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19912 	}
19913 
19914 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19915 	    (char *)re, (int)sizeof (*re))) {
19916 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19917 		    (uint_t)sizeof (*re)));
19918 	}
19919 
19920 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19921 		iaeptr->iae_routeidx = ird->ird_idx;
19922 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19923 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19924 	}
19925 
19926 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19927 	    (char *)iae, sacnt * sizeof (*iae))) {
19928 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19929 		    (unsigned)(sacnt * sizeof (*iae))));
19930 	}
19931 
19932 	/* bump route index for next pass */
19933 	ird->ird_idx++;
19934 
19935 	kmem_free(re, sizeof (*re));
19936 	if (sacnt != 0)
19937 		kmem_free(iae, sacnt * sizeof (*iae));
19938 
19939 	if (gcgrp != NULL)
19940 		rw_exit(&gcgrp->gcgrp_rwlock);
19941 }
19942 
19943 /*
19944  * ndp_walk routine to create ipv6NetToMediaEntryTable
19945  */
19946 static int
19947 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19948 {
19949 	ill_t				*ill;
19950 	mib2_ipv6NetToMediaEntry_t	ntme;
19951 	dl_unitdata_req_t		*dl;
19952 
19953 	ill = nce->nce_ill;
19954 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19955 		return (0);
19956 
19957 	/*
19958 	 * Neighbor cache entry attached to IRE with on-link
19959 	 * destination.
19960 	 */
19961 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19962 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19963 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19964 	    (nce->nce_res_mp != NULL)) {
19965 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19966 		ntme.ipv6NetToMediaPhysAddress.o_length =
19967 		    dl->dl_dest_addr_length;
19968 	} else {
19969 		ntme.ipv6NetToMediaPhysAddress.o_length =
19970 		    ill->ill_phys_addr_length;
19971 	}
19972 	if (nce->nce_res_mp != NULL) {
19973 		bcopy((char *)nce->nce_res_mp->b_rptr +
19974 		    NCE_LL_ADDR_OFFSET(ill),
19975 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19976 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19977 	} else {
19978 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19979 		    ill->ill_phys_addr_length);
19980 	}
19981 	/*
19982 	 * Note: Returns ND_* states. Should be:
19983 	 * reachable(1), stale(2), delay(3), probe(4),
19984 	 * invalid(5), unknown(6)
19985 	 */
19986 	ntme.ipv6NetToMediaState = nce->nce_state;
19987 	ntme.ipv6NetToMediaLastUpdated = 0;
19988 
19989 	/* other(1), dynamic(2), static(3), local(4) */
19990 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19991 		ntme.ipv6NetToMediaType = 4;
19992 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19993 		ntme.ipv6NetToMediaType = 1;
19994 	} else {
19995 		ntme.ipv6NetToMediaType = 2;
19996 	}
19997 
19998 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19999 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
20000 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
20001 		    (uint_t)sizeof (ntme)));
20002 	}
20003 	return (0);
20004 }
20005 
20006 /*
20007  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
20008  */
20009 /* ARGSUSED */
20010 int
20011 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
20012 {
20013 	switch (level) {
20014 	case MIB2_IP:
20015 	case MIB2_ICMP:
20016 		switch (name) {
20017 		default:
20018 			break;
20019 		}
20020 		return (1);
20021 	default:
20022 		return (1);
20023 	}
20024 }
20025 
20026 /*
20027  * When there exists both a 64- and 32-bit counter of a particular type
20028  * (i.e., InReceives), only the 64-bit counters are added.
20029  */
20030 void
20031 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
20032 {
20033 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
20034 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
20035 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
20036 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
20037 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
20038 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
20039 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
20040 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
20041 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
20042 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
20043 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
20044 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
20045 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
20046 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
20047 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
20048 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
20049 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
20050 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
20051 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
20052 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
20053 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
20054 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
20055 	    o2->ipIfStatsInWrongIPVersion);
20056 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
20057 	    o2->ipIfStatsInWrongIPVersion);
20058 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
20059 	    o2->ipIfStatsOutSwitchIPVersion);
20060 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
20061 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
20062 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
20063 	    o2->ipIfStatsHCInForwDatagrams);
20064 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
20065 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
20066 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
20067 	    o2->ipIfStatsHCOutForwDatagrams);
20068 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
20069 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
20070 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
20071 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
20072 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
20073 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
20074 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
20075 	    o2->ipIfStatsHCOutMcastOctets);
20076 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
20077 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
20078 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
20079 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
20080 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
20081 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
20082 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
20083 }
20084 
20085 void
20086 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
20087 {
20088 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
20089 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
20090 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
20091 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
20092 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
20093 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
20094 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
20095 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
20096 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
20097 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
20098 	    o2->ipv6IfIcmpInRouterSolicits);
20099 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
20100 	    o2->ipv6IfIcmpInRouterAdvertisements);
20101 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
20102 	    o2->ipv6IfIcmpInNeighborSolicits);
20103 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
20104 	    o2->ipv6IfIcmpInNeighborAdvertisements);
20105 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
20106 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
20107 	    o2->ipv6IfIcmpInGroupMembQueries);
20108 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
20109 	    o2->ipv6IfIcmpInGroupMembResponses);
20110 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
20111 	    o2->ipv6IfIcmpInGroupMembReductions);
20112 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
20113 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
20114 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
20115 	    o2->ipv6IfIcmpOutDestUnreachs);
20116 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
20117 	    o2->ipv6IfIcmpOutAdminProhibs);
20118 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
20119 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
20120 	    o2->ipv6IfIcmpOutParmProblems);
20121 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
20122 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
20123 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
20124 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
20125 	    o2->ipv6IfIcmpOutRouterSolicits);
20126 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
20127 	    o2->ipv6IfIcmpOutRouterAdvertisements);
20128 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
20129 	    o2->ipv6IfIcmpOutNeighborSolicits);
20130 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
20131 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
20132 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
20133 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
20134 	    o2->ipv6IfIcmpOutGroupMembQueries);
20135 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
20136 	    o2->ipv6IfIcmpOutGroupMembResponses);
20137 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
20138 	    o2->ipv6IfIcmpOutGroupMembReductions);
20139 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
20140 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
20141 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
20142 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
20143 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
20144 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
20145 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
20146 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
20147 	    o2->ipv6IfIcmpInGroupMembTotal);
20148 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
20149 	    o2->ipv6IfIcmpInGroupMembBadQueries);
20150 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
20151 	    o2->ipv6IfIcmpInGroupMembBadReports);
20152 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
20153 	    o2->ipv6IfIcmpInGroupMembOurReports);
20154 }
20155 
20156 /*
20157  * Called before the options are updated to check if this packet will
20158  * be source routed from here.
20159  * This routine assumes that the options are well formed i.e. that they
20160  * have already been checked.
20161  */
20162 static boolean_t
20163 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
20164 {
20165 	ipoptp_t	opts;
20166 	uchar_t		*opt;
20167 	uint8_t		optval;
20168 	uint8_t		optlen;
20169 	ipaddr_t	dst;
20170 	ire_t		*ire;
20171 
20172 	if (IS_SIMPLE_IPH(ipha)) {
20173 		ip2dbg(("not source routed\n"));
20174 		return (B_FALSE);
20175 	}
20176 	dst = ipha->ipha_dst;
20177 	for (optval = ipoptp_first(&opts, ipha);
20178 	    optval != IPOPT_EOL;
20179 	    optval = ipoptp_next(&opts)) {
20180 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
20181 		opt = opts.ipoptp_cur;
20182 		optlen = opts.ipoptp_len;
20183 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
20184 		    optval, optlen));
20185 		switch (optval) {
20186 			uint32_t off;
20187 		case IPOPT_SSRR:
20188 		case IPOPT_LSRR:
20189 			/*
20190 			 * If dst is one of our addresses and there are some
20191 			 * entries left in the source route return (true).
20192 			 */
20193 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
20194 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
20195 			if (ire == NULL) {
20196 				ip2dbg(("ip_source_routed: not next"
20197 				    " source route 0x%x\n",
20198 				    ntohl(dst)));
20199 				return (B_FALSE);
20200 			}
20201 			ire_refrele(ire);
20202 			off = opt[IPOPT_OFFSET];
20203 			off--;
20204 			if (optlen < IP_ADDR_LEN ||
20205 			    off > optlen - IP_ADDR_LEN) {
20206 				/* End of source route */
20207 				ip1dbg(("ip_source_routed: end of SR\n"));
20208 				return (B_FALSE);
20209 			}
20210 			return (B_TRUE);
20211 		}
20212 	}
20213 	ip2dbg(("not source routed\n"));
20214 	return (B_FALSE);
20215 }
20216 
20217 /*
20218  * Check if the packet contains any source route.
20219  */
20220 static boolean_t
20221 ip_source_route_included(ipha_t *ipha)
20222 {
20223 	ipoptp_t	opts;
20224 	uint8_t		optval;
20225 
20226 	if (IS_SIMPLE_IPH(ipha))
20227 		return (B_FALSE);
20228 	for (optval = ipoptp_first(&opts, ipha);
20229 	    optval != IPOPT_EOL;
20230 	    optval = ipoptp_next(&opts)) {
20231 		switch (optval) {
20232 		case IPOPT_SSRR:
20233 		case IPOPT_LSRR:
20234 			return (B_TRUE);
20235 		}
20236 	}
20237 	return (B_FALSE);
20238 }
20239 
20240 /*
20241  * Called when the IRE expiration timer fires.
20242  */
20243 void
20244 ip_trash_timer_expire(void *args)
20245 {
20246 	int			flush_flag = 0;
20247 	ire_expire_arg_t	iea;
20248 	ip_stack_t		*ipst = (ip_stack_t *)args;
20249 
20250 	iea.iea_ipst = ipst;	/* No netstack_hold */
20251 
20252 	/*
20253 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
20254 	 * This lock makes sure that a new invocation of this function
20255 	 * that occurs due to an almost immediate timer firing will not
20256 	 * progress beyond this point until the current invocation is done
20257 	 */
20258 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20259 	ipst->ips_ip_ire_expire_id = 0;
20260 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20261 
20262 	/* Periodic timer */
20263 	if (ipst->ips_ip_ire_arp_time_elapsed >=
20264 	    ipst->ips_ip_ire_arp_interval) {
20265 		/*
20266 		 * Remove all IRE_CACHE entries since they might
20267 		 * contain arp information.
20268 		 */
20269 		flush_flag |= FLUSH_ARP_TIME;
20270 		ipst->ips_ip_ire_arp_time_elapsed = 0;
20271 		IP_STAT(ipst, ip_ire_arp_timer_expired);
20272 	}
20273 	if (ipst->ips_ip_ire_rd_time_elapsed >=
20274 	    ipst->ips_ip_ire_redir_interval) {
20275 		/* Remove all redirects */
20276 		flush_flag |= FLUSH_REDIRECT_TIME;
20277 		ipst->ips_ip_ire_rd_time_elapsed = 0;
20278 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
20279 	}
20280 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
20281 	    ipst->ips_ip_ire_pathmtu_interval) {
20282 		/* Increase path mtu */
20283 		flush_flag |= FLUSH_MTU_TIME;
20284 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
20285 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
20286 	}
20287 
20288 	/*
20289 	 * Optimize for the case when there are no redirects in the
20290 	 * ftable, that is, no need to walk the ftable in that case.
20291 	 */
20292 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
20293 		iea.iea_flush_flag = flush_flag;
20294 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
20295 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
20296 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
20297 		    NULL, ALL_ZONES, ipst);
20298 	}
20299 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
20300 	    ipst->ips_ip_redirect_cnt > 0) {
20301 		iea.iea_flush_flag = flush_flag;
20302 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
20303 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
20304 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
20305 	}
20306 	if (flush_flag & FLUSH_MTU_TIME) {
20307 		/*
20308 		 * Walk all IPv6 IRE's and update them
20309 		 * Note that ARP and redirect timers are not
20310 		 * needed since NUD handles stale entries.
20311 		 */
20312 		flush_flag = FLUSH_MTU_TIME;
20313 		iea.iea_flush_flag = flush_flag;
20314 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
20315 		    ALL_ZONES, ipst);
20316 	}
20317 
20318 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
20319 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
20320 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
20321 
20322 	/*
20323 	 * Hold the lock to serialize timeout calls and prevent
20324 	 * stale values in ip_ire_expire_id. Otherwise it is possible
20325 	 * for the timer to fire and a new invocation of this function
20326 	 * to start before the return value of timeout has been stored
20327 	 * in ip_ire_expire_id by the current invocation.
20328 	 */
20329 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20330 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
20331 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
20332 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20333 }
20334 
20335 /*
20336  * Called by the memory allocator subsystem directly, when the system
20337  * is running low on memory.
20338  */
20339 /* ARGSUSED */
20340 void
20341 ip_trash_ire_reclaim(void *args)
20342 {
20343 	netstack_handle_t nh;
20344 	netstack_t *ns;
20345 
20346 	netstack_next_init(&nh);
20347 	while ((ns = netstack_next(&nh)) != NULL) {
20348 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
20349 		netstack_rele(ns);
20350 	}
20351 	netstack_next_fini(&nh);
20352 }
20353 
20354 static void
20355 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
20356 {
20357 	ire_cache_count_t icc;
20358 	ire_cache_reclaim_t icr;
20359 	ncc_cache_count_t ncc;
20360 	nce_cache_reclaim_t ncr;
20361 	uint_t delete_cnt;
20362 	/*
20363 	 * Memory reclaim call back.
20364 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
20365 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
20366 	 * entries, determine what fraction to free for
20367 	 * each category of IRE_CACHE entries giving absolute priority
20368 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
20369 	 * entry will be freed unless all offlink entries are freed).
20370 	 */
20371 	icc.icc_total = 0;
20372 	icc.icc_unused = 0;
20373 	icc.icc_offlink = 0;
20374 	icc.icc_pmtu = 0;
20375 	icc.icc_onlink = 0;
20376 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20377 
20378 	/*
20379 	 * Free NCEs for IPv6 like the onlink ires.
20380 	 */
20381 	ncc.ncc_total = 0;
20382 	ncc.ncc_host = 0;
20383 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
20384 
20385 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
20386 	    icc.icc_pmtu + icc.icc_onlink);
20387 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
20388 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
20389 	if (delete_cnt == 0)
20390 		return;
20391 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
20392 	/* Always delete all unused offlink entries */
20393 	icr.icr_ipst = ipst;
20394 	icr.icr_unused = 1;
20395 	if (delete_cnt <= icc.icc_unused) {
20396 		/*
20397 		 * Only need to free unused entries.  In other words,
20398 		 * there are enough unused entries to free to meet our
20399 		 * target number of freed ire cache entries.
20400 		 */
20401 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
20402 		ncr.ncr_host = 0;
20403 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
20404 		/*
20405 		 * Only need to free unused entries, plus a fraction of offlink
20406 		 * entries.  It follows from the first if statement that
20407 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
20408 		 */
20409 		delete_cnt -= icc.icc_unused;
20410 		/* Round up # deleted by truncating fraction */
20411 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
20412 		icr.icr_pmtu = icr.icr_onlink = 0;
20413 		ncr.ncr_host = 0;
20414 	} else if (delete_cnt <=
20415 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
20416 		/*
20417 		 * Free all unused and offlink entries, plus a fraction of
20418 		 * pmtu entries.  It follows from the previous if statement
20419 		 * that icc_pmtu is non-zero, and that
20420 		 * delete_cnt != icc_unused + icc_offlink.
20421 		 */
20422 		icr.icr_offlink = 1;
20423 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
20424 		/* Round up # deleted by truncating fraction */
20425 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
20426 		icr.icr_onlink = 0;
20427 		ncr.ncr_host = 0;
20428 	} else {
20429 		/*
20430 		 * Free all unused, offlink, and pmtu entries, plus a fraction
20431 		 * of onlink entries.  If we're here, then we know that
20432 		 * icc_onlink is non-zero, and that
20433 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
20434 		 */
20435 		icr.icr_offlink = icr.icr_pmtu = 1;
20436 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
20437 		    icc.icc_pmtu;
20438 		/* Round up # deleted by truncating fraction */
20439 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
20440 		/* Using the same delete fraction as for onlink IREs */
20441 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
20442 	}
20443 #ifdef DEBUG
20444 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
20445 	    "fractions %d/%d/%d/%d\n",
20446 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
20447 	    icc.icc_unused, icc.icc_offlink,
20448 	    icc.icc_pmtu, icc.icc_onlink,
20449 	    icr.icr_unused, icr.icr_offlink,
20450 	    icr.icr_pmtu, icr.icr_onlink));
20451 #endif
20452 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
20453 	if (ncr.ncr_host != 0)
20454 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
20455 		    (uchar_t *)&ncr, ipst);
20456 #ifdef DEBUG
20457 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
20458 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
20459 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20460 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
20461 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
20462 	    icc.icc_pmtu, icc.icc_onlink));
20463 #endif
20464 }
20465 
20466 /*
20467  * ip_unbind is called when a copy of an unbind request is received from the
20468  * upper level protocol.  We remove this conn from any fanout hash list it is
20469  * on, and zero out the bind information.  No reply is expected up above.
20470  */
20471 void
20472 ip_unbind(conn_t *connp)
20473 {
20474 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
20475 
20476 	if (is_system_labeled() && connp->conn_anon_port) {
20477 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
20478 		    connp->conn_mlp_type, connp->conn_ulp,
20479 		    ntohs(connp->conn_lport), B_FALSE);
20480 		connp->conn_anon_port = 0;
20481 	}
20482 	connp->conn_mlp_type = mlptSingle;
20483 
20484 	ipcl_hash_remove(connp);
20485 
20486 }
20487 
20488 /*
20489  * Write side put procedure.  Outbound data, IOCTLs, responses from
20490  * resolvers, etc, come down through here.
20491  *
20492  * arg2 is always a queue_t *.
20493  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
20494  * the zoneid.
20495  * When that queue is not an ill_t, then arg must be a conn_t pointer.
20496  */
20497 void
20498 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
20499 {
20500 	ip_output_options(arg, mp, arg2, caller, &zero_info);
20501 }
20502 
20503 void
20504 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20505     ip_opt_info_t *infop)
20506 {
20507 	conn_t		*connp = NULL;
20508 	queue_t		*q = (queue_t *)arg2;
20509 	ipha_t		*ipha;
20510 #define	rptr	((uchar_t *)ipha)
20511 	ire_t		*ire = NULL;
20512 	ire_t		*sctp_ire = NULL;
20513 	uint32_t	v_hlen_tos_len;
20514 	ipaddr_t	dst;
20515 	mblk_t		*first_mp = NULL;
20516 	boolean_t	mctl_present;
20517 	ipsec_out_t	*io;
20518 	int		match_flags;
20519 	ill_t		*attach_ill = NULL;
20520 					/* Bind to IPIF_NOFAILOVER ill etc. */
20521 	ill_t		*xmit_ill = NULL;	/* IP_PKTINFO etc. */
20522 	ipif_t		*dst_ipif;
20523 	boolean_t	multirt_need_resolve = B_FALSE;
20524 	mblk_t		*copy_mp = NULL;
20525 	int		err;
20526 	zoneid_t	zoneid;
20527 	boolean_t	need_decref = B_FALSE;
20528 	boolean_t	ignore_dontroute = B_FALSE;
20529 	boolean_t	ignore_nexthop = B_FALSE;
20530 	boolean_t	ip_nexthop = B_FALSE;
20531 	ipaddr_t	nexthop_addr;
20532 	ip_stack_t	*ipst;
20533 
20534 #ifdef	_BIG_ENDIAN
20535 #define	V_HLEN	(v_hlen_tos_len >> 24)
20536 #else
20537 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20538 #endif
20539 
20540 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20541 	    "ip_wput_start: q %p", q);
20542 
20543 	/*
20544 	 * ip_wput fast path
20545 	 */
20546 
20547 	/* is packet from ARP ? */
20548 	if (q->q_next != NULL) {
20549 		zoneid = (zoneid_t)(uintptr_t)arg;
20550 		goto qnext;
20551 	}
20552 
20553 	connp = (conn_t *)arg;
20554 	ASSERT(connp != NULL);
20555 	zoneid = connp->conn_zoneid;
20556 	ipst = connp->conn_netstack->netstack_ip;
20557 	ASSERT(ipst != NULL);
20558 
20559 	/* is queue flow controlled? */
20560 	if ((q->q_first != NULL || connp->conn_draining) &&
20561 	    (caller == IP_WPUT)) {
20562 		ASSERT(!need_decref);
20563 		ASSERT(!IP_FLOW_CONTROLLED_ULP(connp->conn_ulp));
20564 		(void) putq(q, mp);
20565 		return;
20566 	}
20567 
20568 	/* Multidata transmit? */
20569 	if (DB_TYPE(mp) == M_MULTIDATA) {
20570 		/*
20571 		 * We should never get here, since all Multidata messages
20572 		 * originating from tcp should have been directed over to
20573 		 * tcp_multisend() in the first place.
20574 		 */
20575 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20576 		freemsg(mp);
20577 		return;
20578 	} else if (DB_TYPE(mp) != M_DATA)
20579 		goto notdata;
20580 
20581 	if (mp->b_flag & MSGHASREF) {
20582 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20583 		mp->b_flag &= ~MSGHASREF;
20584 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20585 		need_decref = B_TRUE;
20586 	}
20587 	ipha = (ipha_t *)mp->b_rptr;
20588 
20589 	/* is IP header non-aligned or mblk smaller than basic IP header */
20590 #ifndef SAFETY_BEFORE_SPEED
20591 	if (!OK_32PTR(rptr) ||
20592 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20593 		goto hdrtoosmall;
20594 #endif
20595 
20596 	ASSERT(OK_32PTR(ipha));
20597 
20598 	/*
20599 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20600 	 * wrong version, we'll catch it again in ip_output_v6.
20601 	 *
20602 	 * Note that this is *only* locally-generated output here, and never
20603 	 * forwarded data, and that we need to deal only with transports that
20604 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20605 	 * label.)
20606 	 */
20607 	if (is_system_labeled() &&
20608 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20609 	    !connp->conn_ulp_labeled) {
20610 		err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20611 		    connp->conn_mac_exempt, ipst);
20612 		ipha = (ipha_t *)mp->b_rptr;
20613 		if (err != 0) {
20614 			first_mp = mp;
20615 			if (err == EINVAL)
20616 				goto icmp_parameter_problem;
20617 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20618 			goto discard_pkt;
20619 		}
20620 	}
20621 
20622 	ASSERT(infop != NULL);
20623 
20624 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20625 		/*
20626 		 * IP_PKTINFO ancillary option is present.
20627 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20628 		 * allows using address of any zone as the source address.
20629 		 */
20630 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20631 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20632 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20633 		if (ire == NULL)
20634 			goto drop_pkt;
20635 		ire_refrele(ire);
20636 		ire = NULL;
20637 	}
20638 
20639 	/*
20640 	 * IP_DONTFAILOVER_IF and IP_BOUND_IF have precedence over ill index
20641 	 * passed in IP_PKTINFO.
20642 	 */
20643 	if (infop->ip_opt_ill_index != 0 &&
20644 	    connp->conn_outgoing_ill == NULL &&
20645 	    connp->conn_nofailover_ill == NULL) {
20646 
20647 		xmit_ill = ill_lookup_on_ifindex(
20648 		    infop->ip_opt_ill_index, B_FALSE, NULL, NULL, NULL, NULL,
20649 		    ipst);
20650 
20651 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20652 			goto drop_pkt;
20653 		/*
20654 		 * check that there is an ipif belonging
20655 		 * to our zone. IPCL_ZONEID is not used because
20656 		 * IP_ALLZONES option is valid only when the ill is
20657 		 * accessible from all zones i.e has a valid ipif in
20658 		 * all zones.
20659 		 */
20660 		if (!ipif_lookup_zoneid_group(xmit_ill, zoneid, 0, NULL)) {
20661 			goto drop_pkt;
20662 		}
20663 	}
20664 
20665 	/*
20666 	 * If there is a policy, try to attach an ipsec_out in
20667 	 * the front. At the end, first_mp either points to a
20668 	 * M_DATA message or IPSEC_OUT message linked to a
20669 	 * M_DATA message. We have to do it now as we might
20670 	 * lose the "conn" if we go through ip_newroute.
20671 	 */
20672 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20673 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
20674 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20675 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20676 			if (need_decref)
20677 				CONN_DEC_REF(connp);
20678 			return;
20679 		} else {
20680 			ASSERT(mp->b_datap->db_type == M_CTL);
20681 			first_mp = mp;
20682 			mp = mp->b_cont;
20683 			mctl_present = B_TRUE;
20684 		}
20685 	} else {
20686 		first_mp = mp;
20687 		mctl_present = B_FALSE;
20688 	}
20689 
20690 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20691 
20692 	/* is wrong version or IP options present */
20693 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20694 		goto version_hdrlen_check;
20695 	dst = ipha->ipha_dst;
20696 
20697 	if (connp->conn_nofailover_ill != NULL) {
20698 		attach_ill = conn_get_held_ill(connp,
20699 		    &connp->conn_nofailover_ill, &err);
20700 		if (err == ILL_LOOKUP_FAILED) {
20701 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20702 			if (need_decref)
20703 				CONN_DEC_REF(connp);
20704 			freemsg(first_mp);
20705 			return;
20706 		}
20707 	}
20708 
20709 	/* If IP_BOUND_IF has been set, use that ill. */
20710 	if (connp->conn_outgoing_ill != NULL) {
20711 		xmit_ill = conn_get_held_ill(connp,
20712 		    &connp->conn_outgoing_ill, &err);
20713 		if (err == ILL_LOOKUP_FAILED)
20714 			goto drop_pkt;
20715 
20716 		goto send_from_ill;
20717 	}
20718 
20719 	/* is packet multicast? */
20720 	if (CLASSD(dst))
20721 		goto multicast;
20722 
20723 	/*
20724 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20725 	 * takes precedence over conn_dontroute and conn_nexthop_set
20726 	 */
20727 	if (xmit_ill != NULL)
20728 		goto send_from_ill;
20729 
20730 	if (connp->conn_dontroute || connp->conn_nexthop_set) {
20731 		/*
20732 		 * If the destination is a broadcast, local, or loopback
20733 		 * address, SO_DONTROUTE and IP_NEXTHOP go through the
20734 		 * standard path.
20735 		 */
20736 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20737 		if ((ire == NULL) || (ire->ire_type &
20738 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK)) == 0) {
20739 			if (ire != NULL) {
20740 				ire_refrele(ire);
20741 				/* No more access to ire */
20742 				ire = NULL;
20743 			}
20744 			/*
20745 			 * bypass routing checks and go directly to interface.
20746 			 */
20747 			if (connp->conn_dontroute)
20748 				goto dontroute;
20749 
20750 			ASSERT(connp->conn_nexthop_set);
20751 			ip_nexthop = B_TRUE;
20752 			nexthop_addr = connp->conn_nexthop_v4;
20753 			goto send_from_ill;
20754 		}
20755 
20756 		/* Must be a broadcast, a loopback or a local ire */
20757 		ire_refrele(ire);
20758 		/* No more access to ire */
20759 		ire = NULL;
20760 	}
20761 
20762 	if (attach_ill != NULL)
20763 		goto send_from_ill;
20764 
20765 	/*
20766 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20767 	 * this for the tcp global queue and listen end point
20768 	 * as it does not really have a real destination to
20769 	 * talk to.  This is also true for SCTP.
20770 	 */
20771 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20772 	    !connp->conn_fully_bound) {
20773 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20774 		if (ire == NULL)
20775 			goto noirefound;
20776 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20777 		    "ip_wput_end: q %p (%S)", q, "end");
20778 
20779 		/*
20780 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20781 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20782 		 */
20783 		if (ire->ire_flags & RTF_MULTIRT) {
20784 
20785 			/*
20786 			 * Force the TTL of multirouted packets if required.
20787 			 * The TTL of such packets is bounded by the
20788 			 * ip_multirt_ttl ndd variable.
20789 			 */
20790 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20791 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20792 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20793 				    "(was %d), dst 0x%08x\n",
20794 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20795 				    ntohl(ire->ire_addr)));
20796 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20797 			}
20798 			/*
20799 			 * We look at this point if there are pending
20800 			 * unresolved routes. ire_multirt_resolvable()
20801 			 * checks in O(n) that all IRE_OFFSUBNET ire
20802 			 * entries for the packet's destination and
20803 			 * flagged RTF_MULTIRT are currently resolved.
20804 			 * If some remain unresolved, we make a copy
20805 			 * of the current message. It will be used
20806 			 * to initiate additional route resolutions.
20807 			 */
20808 			multirt_need_resolve =
20809 			    ire_multirt_need_resolve(ire->ire_addr,
20810 			    MBLK_GETLABEL(first_mp), ipst);
20811 			ip2dbg(("ip_wput[TCP]: ire %p, "
20812 			    "multirt_need_resolve %d, first_mp %p\n",
20813 			    (void *)ire, multirt_need_resolve,
20814 			    (void *)first_mp));
20815 			if (multirt_need_resolve) {
20816 				copy_mp = copymsg(first_mp);
20817 				if (copy_mp != NULL) {
20818 					MULTIRT_DEBUG_TAG(copy_mp);
20819 				}
20820 			}
20821 		}
20822 
20823 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20824 
20825 		/*
20826 		 * Try to resolve another multiroute if
20827 		 * ire_multirt_need_resolve() deemed it necessary.
20828 		 */
20829 		if (copy_mp != NULL)
20830 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20831 		if (need_decref)
20832 			CONN_DEC_REF(connp);
20833 		return;
20834 	}
20835 
20836 	/*
20837 	 * Access to conn_ire_cache. (protected by conn_lock)
20838 	 *
20839 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20840 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20841 	 * send a packet or two with the IRE_CACHE that is going away.
20842 	 * Access to the ire requires an ire refhold on the ire prior to
20843 	 * its use since an interface unplumb thread may delete the cached
20844 	 * ire and release the refhold at any time.
20845 	 *
20846 	 * Caching an ire in the conn_ire_cache
20847 	 *
20848 	 * o Caching an ire pointer in the conn requires a strict check for
20849 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20850 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20851 	 * in the conn is done after making sure under the bucket lock that the
20852 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20853 	 * caching an ire after the unplumb thread has cleaned up the conn.
20854 	 * If the conn does not send a packet subsequently the unplumb thread
20855 	 * will be hanging waiting for the ire count to drop to zero.
20856 	 *
20857 	 * o We also need to atomically test for a null conn_ire_cache and
20858 	 * set the conn_ire_cache under the the protection of the conn_lock
20859 	 * to avoid races among concurrent threads trying to simultaneously
20860 	 * cache an ire in the conn_ire_cache.
20861 	 */
20862 	mutex_enter(&connp->conn_lock);
20863 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20864 
20865 	if (ire != NULL && ire->ire_addr == dst &&
20866 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20867 
20868 		IRE_REFHOLD(ire);
20869 		mutex_exit(&connp->conn_lock);
20870 
20871 	} else {
20872 		boolean_t cached = B_FALSE;
20873 		connp->conn_ire_cache = NULL;
20874 		mutex_exit(&connp->conn_lock);
20875 		/* Release the old ire */
20876 		if (ire != NULL && sctp_ire == NULL)
20877 			IRE_REFRELE_NOTR(ire);
20878 
20879 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20880 		if (ire == NULL)
20881 			goto noirefound;
20882 		IRE_REFHOLD_NOTR(ire);
20883 
20884 		mutex_enter(&connp->conn_lock);
20885 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20886 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20887 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20888 				if (connp->conn_ulp == IPPROTO_TCP)
20889 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20890 				connp->conn_ire_cache = ire;
20891 				cached = B_TRUE;
20892 			}
20893 			rw_exit(&ire->ire_bucket->irb_lock);
20894 		}
20895 		mutex_exit(&connp->conn_lock);
20896 
20897 		/*
20898 		 * We can continue to use the ire but since it was
20899 		 * not cached, we should drop the extra reference.
20900 		 */
20901 		if (!cached)
20902 			IRE_REFRELE_NOTR(ire);
20903 	}
20904 
20905 
20906 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20907 	    "ip_wput_end: q %p (%S)", q, "end");
20908 
20909 	/*
20910 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20911 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20912 	 */
20913 	if (ire->ire_flags & RTF_MULTIRT) {
20914 
20915 		/*
20916 		 * Force the TTL of multirouted packets if required.
20917 		 * The TTL of such packets is bounded by the
20918 		 * ip_multirt_ttl ndd variable.
20919 		 */
20920 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20921 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20922 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20923 			    "(was %d), dst 0x%08x\n",
20924 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20925 			    ntohl(ire->ire_addr)));
20926 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20927 		}
20928 
20929 		/*
20930 		 * At this point, we check to see if there are any pending
20931 		 * unresolved routes. ire_multirt_resolvable()
20932 		 * checks in O(n) that all IRE_OFFSUBNET ire
20933 		 * entries for the packet's destination and
20934 		 * flagged RTF_MULTIRT are currently resolved.
20935 		 * If some remain unresolved, we make a copy
20936 		 * of the current message. It will be used
20937 		 * to initiate additional route resolutions.
20938 		 */
20939 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20940 		    MBLK_GETLABEL(first_mp), ipst);
20941 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20942 		    "multirt_need_resolve %d, first_mp %p\n",
20943 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20944 		if (multirt_need_resolve) {
20945 			copy_mp = copymsg(first_mp);
20946 			if (copy_mp != NULL) {
20947 				MULTIRT_DEBUG_TAG(copy_mp);
20948 			}
20949 		}
20950 	}
20951 
20952 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20953 
20954 	/*
20955 	 * Try to resolve another multiroute if
20956 	 * ire_multirt_resolvable() deemed it necessary
20957 	 */
20958 	if (copy_mp != NULL)
20959 		ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20960 	if (need_decref)
20961 		CONN_DEC_REF(connp);
20962 	return;
20963 
20964 qnext:
20965 	/*
20966 	 * Upper Level Protocols pass down complete IP datagrams
20967 	 * as M_DATA messages.	Everything else is a sideshow.
20968 	 *
20969 	 * 1) We could be re-entering ip_wput because of ip_neworute
20970 	 *    in which case we could have a IPSEC_OUT message. We
20971 	 *    need to pass through ip_wput like other datagrams and
20972 	 *    hence cannot branch to ip_wput_nondata.
20973 	 *
20974 	 * 2) ARP, AH, ESP, and other clients who are on the module
20975 	 *    instance of IP stream, give us something to deal with.
20976 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20977 	 *
20978 	 * 3) ICMP replies also could come here.
20979 	 */
20980 	ipst = ILLQ_TO_IPST(q);
20981 
20982 	if (DB_TYPE(mp) != M_DATA) {
20983 notdata:
20984 		if (DB_TYPE(mp) == M_CTL) {
20985 			/*
20986 			 * M_CTL messages are used by ARP, AH and ESP to
20987 			 * communicate with IP. We deal with IPSEC_IN and
20988 			 * IPSEC_OUT here. ip_wput_nondata handles other
20989 			 * cases.
20990 			 */
20991 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20992 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20993 				first_mp = mp->b_cont;
20994 				first_mp->b_flag &= ~MSGHASREF;
20995 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20996 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20997 				CONN_DEC_REF(connp);
20998 				connp = NULL;
20999 			}
21000 			if (ii->ipsec_info_type == IPSEC_IN) {
21001 				/*
21002 				 * Either this message goes back to
21003 				 * IPsec for further processing or to
21004 				 * ULP after policy checks.
21005 				 */
21006 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
21007 				return;
21008 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
21009 				io = (ipsec_out_t *)ii;
21010 				if (io->ipsec_out_proc_begin) {
21011 					/*
21012 					 * IPsec processing has already started.
21013 					 * Complete it.
21014 					 * IPQoS notes: We don't care what is
21015 					 * in ipsec_out_ill_index since this
21016 					 * won't be processed for IPQoS policies
21017 					 * in ipsec_out_process.
21018 					 */
21019 					ipsec_out_process(q, mp, NULL,
21020 					    io->ipsec_out_ill_index);
21021 					return;
21022 				} else {
21023 					connp = (q->q_next != NULL) ?
21024 					    NULL : Q_TO_CONN(q);
21025 					first_mp = mp;
21026 					mp = mp->b_cont;
21027 					mctl_present = B_TRUE;
21028 				}
21029 				zoneid = io->ipsec_out_zoneid;
21030 				ASSERT(zoneid != ALL_ZONES);
21031 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
21032 				/*
21033 				 * It's an IPsec control message requesting
21034 				 * an SADB update to be sent to the IPsec
21035 				 * hardware acceleration capable ills.
21036 				 */
21037 				ipsec_ctl_t *ipsec_ctl =
21038 				    (ipsec_ctl_t *)mp->b_rptr;
21039 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
21040 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
21041 				mblk_t *cmp = mp->b_cont;
21042 
21043 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
21044 				ASSERT(cmp != NULL);
21045 
21046 				freeb(mp);
21047 				ill_ipsec_capab_send_all(satype, cmp, sa,
21048 				    ipst->ips_netstack);
21049 				return;
21050 			} else {
21051 				/*
21052 				 * This must be ARP or special TSOL signaling.
21053 				 */
21054 				ip_wput_nondata(NULL, q, mp, NULL);
21055 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21056 				    "ip_wput_end: q %p (%S)", q, "nondata");
21057 				return;
21058 			}
21059 		} else {
21060 			/*
21061 			 * This must be non-(ARP/AH/ESP) messages.
21062 			 */
21063 			ASSERT(!need_decref);
21064 			ip_wput_nondata(NULL, q, mp, NULL);
21065 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21066 			    "ip_wput_end: q %p (%S)", q, "nondata");
21067 			return;
21068 		}
21069 	} else {
21070 		first_mp = mp;
21071 		mctl_present = B_FALSE;
21072 	}
21073 
21074 	ASSERT(first_mp != NULL);
21075 	/*
21076 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
21077 	 * to make sure that this packet goes out on the same interface it
21078 	 * came in. We handle that here.
21079 	 */
21080 	if (mctl_present) {
21081 		uint_t ifindex;
21082 
21083 		io = (ipsec_out_t *)first_mp->b_rptr;
21084 		if (io->ipsec_out_attach_if || io->ipsec_out_ip_nexthop) {
21085 			/*
21086 			 * We may have lost the conn context if we are
21087 			 * coming here from ip_newroute(). Copy the
21088 			 * nexthop information.
21089 			 */
21090 			if (io->ipsec_out_ip_nexthop) {
21091 				ip_nexthop = B_TRUE;
21092 				nexthop_addr = io->ipsec_out_nexthop_addr;
21093 
21094 				ipha = (ipha_t *)mp->b_rptr;
21095 				dst = ipha->ipha_dst;
21096 				goto send_from_ill;
21097 			} else {
21098 				ASSERT(io->ipsec_out_ill_index != 0);
21099 				ifindex = io->ipsec_out_ill_index;
21100 				attach_ill = ill_lookup_on_ifindex(ifindex,
21101 				    B_FALSE, NULL, NULL, NULL, NULL, ipst);
21102 				if (attach_ill == NULL) {
21103 					ASSERT(xmit_ill == NULL);
21104 					ip1dbg(("ip_output: bad ifindex for "
21105 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
21106 					    ifindex));
21107 					freemsg(first_mp);
21108 					BUMP_MIB(&ipst->ips_ip_mib,
21109 					    ipIfStatsOutDiscards);
21110 					ASSERT(!need_decref);
21111 					return;
21112 				}
21113 			}
21114 		}
21115 	}
21116 
21117 	ASSERT(xmit_ill == NULL);
21118 
21119 	/* We have a complete IP datagram heading outbound. */
21120 	ipha = (ipha_t *)mp->b_rptr;
21121 
21122 #ifndef SPEED_BEFORE_SAFETY
21123 	/*
21124 	 * Make sure we have a full-word aligned message and that at least
21125 	 * a simple IP header is accessible in the first message.  If not,
21126 	 * try a pullup.  For labeled systems we need to always take this
21127 	 * path as M_CTLs are "notdata" but have trailing data to process.
21128 	 */
21129 	if (!OK_32PTR(rptr) ||
21130 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH || is_system_labeled()) {
21131 hdrtoosmall:
21132 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
21133 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21134 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
21135 			if (first_mp == NULL)
21136 				first_mp = mp;
21137 			goto discard_pkt;
21138 		}
21139 
21140 		/* This function assumes that mp points to an IPv4 packet. */
21141 		if (is_system_labeled() && q->q_next == NULL &&
21142 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
21143 		    !connp->conn_ulp_labeled) {
21144 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
21145 			    connp->conn_mac_exempt, ipst);
21146 			ipha = (ipha_t *)mp->b_rptr;
21147 			if (first_mp != NULL)
21148 				first_mp->b_cont = mp;
21149 			if (err != 0) {
21150 				if (first_mp == NULL)
21151 					first_mp = mp;
21152 				if (err == EINVAL)
21153 					goto icmp_parameter_problem;
21154 				ip2dbg(("ip_wput: label check failed (%d)\n",
21155 				    err));
21156 				goto discard_pkt;
21157 			}
21158 		}
21159 
21160 		ipha = (ipha_t *)mp->b_rptr;
21161 		if (first_mp == NULL) {
21162 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
21163 			/*
21164 			 * If we got here because of "goto hdrtoosmall"
21165 			 * We need to attach a IPSEC_OUT.
21166 			 */
21167 			if (connp->conn_out_enforce_policy) {
21168 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
21169 				    NULL, ipha->ipha_protocol,
21170 				    ipst->ips_netstack)) == NULL)) {
21171 					BUMP_MIB(&ipst->ips_ip_mib,
21172 					    ipIfStatsOutDiscards);
21173 					if (need_decref)
21174 						CONN_DEC_REF(connp);
21175 					return;
21176 				} else {
21177 					ASSERT(mp->b_datap->db_type == M_CTL);
21178 					first_mp = mp;
21179 					mp = mp->b_cont;
21180 					mctl_present = B_TRUE;
21181 				}
21182 			} else {
21183 				first_mp = mp;
21184 				mctl_present = B_FALSE;
21185 			}
21186 		}
21187 	}
21188 #endif
21189 
21190 	/* Most of the code below is written for speed, not readability */
21191 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21192 
21193 	/*
21194 	 * If ip_newroute() fails, we're going to need a full
21195 	 * header for the icmp wraparound.
21196 	 */
21197 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
21198 		uint_t	v_hlen;
21199 version_hdrlen_check:
21200 		ASSERT(first_mp != NULL);
21201 		v_hlen = V_HLEN;
21202 		/*
21203 		 * siphon off IPv6 packets coming down from transport
21204 		 * layer modules here.
21205 		 * Note: high-order bit carries NUD reachability confirmation
21206 		 */
21207 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
21208 			/*
21209 			 * FIXME: assume that callers of ip_output* call
21210 			 * the right version?
21211 			 */
21212 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
21213 			ASSERT(xmit_ill == NULL);
21214 			if (attach_ill != NULL)
21215 				ill_refrele(attach_ill);
21216 			if (need_decref)
21217 				mp->b_flag |= MSGHASREF;
21218 			(void) ip_output_v6(arg, first_mp, arg2, caller);
21219 			return;
21220 		}
21221 
21222 		if ((v_hlen >> 4) != IP_VERSION) {
21223 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21224 			    "ip_wput_end: q %p (%S)", q, "badvers");
21225 			goto discard_pkt;
21226 		}
21227 		/*
21228 		 * Is the header length at least 20 bytes?
21229 		 *
21230 		 * Are there enough bytes accessible in the header?  If
21231 		 * not, try a pullup.
21232 		 */
21233 		v_hlen &= 0xF;
21234 		v_hlen <<= 2;
21235 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
21236 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21237 			    "ip_wput_end: q %p (%S)", q, "badlen");
21238 			goto discard_pkt;
21239 		}
21240 		if (v_hlen > (mp->b_wptr - rptr)) {
21241 			if (!pullupmsg(mp, v_hlen)) {
21242 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21243 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
21244 				goto discard_pkt;
21245 			}
21246 			ipha = (ipha_t *)mp->b_rptr;
21247 		}
21248 		/*
21249 		 * Move first entry from any source route into ipha_dst and
21250 		 * verify the options
21251 		 */
21252 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
21253 		    zoneid, ipst)) {
21254 			ASSERT(xmit_ill == NULL);
21255 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21256 			if (attach_ill != NULL)
21257 				ill_refrele(attach_ill);
21258 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21259 			    "ip_wput_end: q %p (%S)", q, "badopts");
21260 			if (need_decref)
21261 				CONN_DEC_REF(connp);
21262 			return;
21263 		}
21264 	}
21265 	dst = ipha->ipha_dst;
21266 
21267 	/*
21268 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
21269 	 * we have to run the packet through ip_newroute which will take
21270 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
21271 	 * a resolver, or assigning a default gateway, etc.
21272 	 */
21273 	if (CLASSD(dst)) {
21274 		ipif_t	*ipif;
21275 		uint32_t setsrc = 0;
21276 
21277 multicast:
21278 		ASSERT(first_mp != NULL);
21279 		ip2dbg(("ip_wput: CLASSD\n"));
21280 		if (connp == NULL) {
21281 			/*
21282 			 * Use the first good ipif on the ill.
21283 			 * XXX Should this ever happen? (Appears
21284 			 * to show up with just ppp and no ethernet due
21285 			 * to in.rdisc.)
21286 			 * However, ire_send should be able to
21287 			 * call ip_wput_ire directly.
21288 			 *
21289 			 * XXX Also, this can happen for ICMP and other packets
21290 			 * with multicast source addresses.  Perhaps we should
21291 			 * fix things so that we drop the packet in question,
21292 			 * but for now, just run with it.
21293 			 */
21294 			ill_t *ill = (ill_t *)q->q_ptr;
21295 
21296 			/*
21297 			 * Don't honor attach_if for this case. If ill
21298 			 * is part of the group, ipif could belong to
21299 			 * any ill and we cannot maintain attach_ill
21300 			 * and ipif_ill same anymore and the assert
21301 			 * below would fail.
21302 			 */
21303 			if (mctl_present && io->ipsec_out_attach_if) {
21304 				io->ipsec_out_ill_index = 0;
21305 				io->ipsec_out_attach_if = B_FALSE;
21306 				ASSERT(attach_ill != NULL);
21307 				ill_refrele(attach_ill);
21308 				attach_ill = NULL;
21309 			}
21310 
21311 			ASSERT(attach_ill == NULL);
21312 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
21313 			if (ipif == NULL) {
21314 				if (need_decref)
21315 					CONN_DEC_REF(connp);
21316 				freemsg(first_mp);
21317 				return;
21318 			}
21319 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
21320 			    ntohl(dst), ill->ill_name));
21321 		} else {
21322 			/*
21323 			 * The order of precedence is IP_BOUND_IF, IP_PKTINFO
21324 			 * and IP_MULTICAST_IF.  The block comment above this
21325 			 * function explains the locking mechanism used here.
21326 			 */
21327 			if (xmit_ill == NULL) {
21328 				xmit_ill = conn_get_held_ill(connp,
21329 				    &connp->conn_outgoing_ill, &err);
21330 				if (err == ILL_LOOKUP_FAILED) {
21331 					ip1dbg(("ip_wput: No ill for "
21332 					    "IP_BOUND_IF\n"));
21333 					BUMP_MIB(&ipst->ips_ip_mib,
21334 					    ipIfStatsOutNoRoutes);
21335 					goto drop_pkt;
21336 				}
21337 			}
21338 
21339 			if (xmit_ill == NULL) {
21340 				ipif = conn_get_held_ipif(connp,
21341 				    &connp->conn_multicast_ipif, &err);
21342 				if (err == IPIF_LOOKUP_FAILED) {
21343 					ip1dbg(("ip_wput: No ipif for "
21344 					    "multicast\n"));
21345 					BUMP_MIB(&ipst->ips_ip_mib,
21346 					    ipIfStatsOutNoRoutes);
21347 					goto drop_pkt;
21348 				}
21349 			}
21350 			if (xmit_ill != NULL) {
21351 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21352 				if (ipif == NULL) {
21353 					ip1dbg(("ip_wput: No ipif for "
21354 					    "xmit_ill\n"));
21355 					BUMP_MIB(&ipst->ips_ip_mib,
21356 					    ipIfStatsOutNoRoutes);
21357 					goto drop_pkt;
21358 				}
21359 			} else if (ipif == NULL || ipif->ipif_isv6) {
21360 				/*
21361 				 * We must do this ipif determination here
21362 				 * else we could pass through ip_newroute
21363 				 * and come back here without the conn context.
21364 				 *
21365 				 * Note: we do late binding i.e. we bind to
21366 				 * the interface when the first packet is sent.
21367 				 * For performance reasons we do not rebind on
21368 				 * each packet but keep the binding until the
21369 				 * next IP_MULTICAST_IF option.
21370 				 *
21371 				 * conn_multicast_{ipif,ill} are shared between
21372 				 * IPv4 and IPv6 and AF_INET6 sockets can
21373 				 * send both IPv4 and IPv6 packets. Hence
21374 				 * we have to check that "isv6" matches above.
21375 				 */
21376 				if (ipif != NULL)
21377 					ipif_refrele(ipif);
21378 				ipif = ipif_lookup_group(dst, zoneid, ipst);
21379 				if (ipif == NULL) {
21380 					ip1dbg(("ip_wput: No ipif for "
21381 					    "multicast\n"));
21382 					BUMP_MIB(&ipst->ips_ip_mib,
21383 					    ipIfStatsOutNoRoutes);
21384 					goto drop_pkt;
21385 				}
21386 				err = conn_set_held_ipif(connp,
21387 				    &connp->conn_multicast_ipif, ipif);
21388 				if (err == IPIF_LOOKUP_FAILED) {
21389 					ipif_refrele(ipif);
21390 					ip1dbg(("ip_wput: No ipif for "
21391 					    "multicast\n"));
21392 					BUMP_MIB(&ipst->ips_ip_mib,
21393 					    ipIfStatsOutNoRoutes);
21394 					goto drop_pkt;
21395 				}
21396 			}
21397 		}
21398 		ASSERT(!ipif->ipif_isv6);
21399 		/*
21400 		 * As we may lose the conn by the time we reach ip_wput_ire,
21401 		 * we copy conn_multicast_loop and conn_dontroute on to an
21402 		 * ipsec_out. In case if this datagram goes out secure,
21403 		 * we need the ill_index also. Copy that also into the
21404 		 * ipsec_out.
21405 		 */
21406 		if (mctl_present) {
21407 			io = (ipsec_out_t *)first_mp->b_rptr;
21408 			ASSERT(first_mp->b_datap->db_type == M_CTL);
21409 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
21410 		} else {
21411 			ASSERT(mp == first_mp);
21412 			if ((first_mp = allocb(sizeof (ipsec_info_t),
21413 			    BPRI_HI)) == NULL) {
21414 				ipif_refrele(ipif);
21415 				first_mp = mp;
21416 				goto discard_pkt;
21417 			}
21418 			first_mp->b_datap->db_type = M_CTL;
21419 			first_mp->b_wptr += sizeof (ipsec_info_t);
21420 			/* ipsec_out_secure is B_FALSE now */
21421 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
21422 			io = (ipsec_out_t *)first_mp->b_rptr;
21423 			io->ipsec_out_type = IPSEC_OUT;
21424 			io->ipsec_out_len = sizeof (ipsec_out_t);
21425 			io->ipsec_out_use_global_policy = B_TRUE;
21426 			io->ipsec_out_ns = ipst->ips_netstack;
21427 			first_mp->b_cont = mp;
21428 			mctl_present = B_TRUE;
21429 		}
21430 		if (attach_ill != NULL) {
21431 			ASSERT(attach_ill == ipif->ipif_ill);
21432 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21433 
21434 			/*
21435 			 * Check if we need an ire that will not be
21436 			 * looked up by anybody else i.e. HIDDEN.
21437 			 */
21438 			if (ill_is_probeonly(attach_ill)) {
21439 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21440 			}
21441 			io->ipsec_out_ill_index =
21442 			    attach_ill->ill_phyint->phyint_ifindex;
21443 			io->ipsec_out_attach_if = B_TRUE;
21444 		} else {
21445 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
21446 			io->ipsec_out_ill_index =
21447 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
21448 		}
21449 		if (connp != NULL) {
21450 			io->ipsec_out_multicast_loop =
21451 			    connp->conn_multicast_loop;
21452 			io->ipsec_out_dontroute = connp->conn_dontroute;
21453 			io->ipsec_out_zoneid = connp->conn_zoneid;
21454 		}
21455 		/*
21456 		 * If the application uses IP_MULTICAST_IF with
21457 		 * different logical addresses of the same ILL, we
21458 		 * need to make sure that the soruce address of
21459 		 * the packet matches the logical IP address used
21460 		 * in the option. We do it by initializing ipha_src
21461 		 * here. This should keep IPsec also happy as
21462 		 * when we return from IPsec processing, we don't
21463 		 * have to worry about getting the right address on
21464 		 * the packet. Thus it is sufficient to look for
21465 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
21466 		 * MATCH_IRE_IPIF.
21467 		 *
21468 		 * NOTE : We need to do it for non-secure case also as
21469 		 * this might go out secure if there is a global policy
21470 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
21471 		 * address, the source should be initialized already and
21472 		 * hence we won't be initializing here.
21473 		 *
21474 		 * As we do not have the ire yet, it is possible that
21475 		 * we set the source address here and then later discover
21476 		 * that the ire implies the source address to be assigned
21477 		 * through the RTF_SETSRC flag.
21478 		 * In that case, the setsrc variable will remind us
21479 		 * that overwritting the source address by the one
21480 		 * of the RTF_SETSRC-flagged ire is allowed.
21481 		 */
21482 		if (ipha->ipha_src == INADDR_ANY &&
21483 		    (connp == NULL || !connp->conn_unspec_src)) {
21484 			ipha->ipha_src = ipif->ipif_src_addr;
21485 			setsrc = RTF_SETSRC;
21486 		}
21487 		/*
21488 		 * Find an IRE which matches the destination and the outgoing
21489 		 * queue (i.e. the outgoing interface.)
21490 		 * For loopback use a unicast IP address for
21491 		 * the ire lookup.
21492 		 */
21493 		if (IS_LOOPBACK(ipif->ipif_ill))
21494 			dst = ipif->ipif_lcl_addr;
21495 
21496 		/*
21497 		 * If xmit_ill is set, we branch out to ip_newroute_ipif.
21498 		 * We don't need to lookup ire in ctable as the packet
21499 		 * needs to be sent to the destination through the specified
21500 		 * ill irrespective of ires in the cache table.
21501 		 */
21502 		ire = NULL;
21503 		if (xmit_ill == NULL) {
21504 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21505 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21506 		}
21507 
21508 		/*
21509 		 * refrele attach_ill as its not needed anymore.
21510 		 */
21511 		if (attach_ill != NULL) {
21512 			ill_refrele(attach_ill);
21513 			attach_ill = NULL;
21514 		}
21515 
21516 		if (ire == NULL) {
21517 			/*
21518 			 * Multicast loopback and multicast forwarding is
21519 			 * done in ip_wput_ire.
21520 			 *
21521 			 * Mark this packet to make it be delivered to
21522 			 * ip_wput_ire after the new ire has been
21523 			 * created.
21524 			 *
21525 			 * The call to ip_newroute_ipif takes into account
21526 			 * the setsrc reminder. In any case, we take care
21527 			 * of the RTF_MULTIRT flag.
21528 			 */
21529 			mp->b_prev = mp->b_next = NULL;
21530 			if (xmit_ill == NULL ||
21531 			    xmit_ill->ill_ipif_up_count > 0) {
21532 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21533 				    setsrc | RTF_MULTIRT, zoneid, infop);
21534 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21535 				    "ip_wput_end: q %p (%S)", q, "noire");
21536 			} else {
21537 				freemsg(first_mp);
21538 			}
21539 			ipif_refrele(ipif);
21540 			if (xmit_ill != NULL)
21541 				ill_refrele(xmit_ill);
21542 			if (need_decref)
21543 				CONN_DEC_REF(connp);
21544 			return;
21545 		}
21546 
21547 		ipif_refrele(ipif);
21548 		ipif = NULL;
21549 		ASSERT(xmit_ill == NULL);
21550 
21551 		/*
21552 		 * Honor the RTF_SETSRC flag for multicast packets,
21553 		 * if allowed by the setsrc reminder.
21554 		 */
21555 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21556 			ipha->ipha_src = ire->ire_src_addr;
21557 		}
21558 
21559 		/*
21560 		 * Unconditionally force the TTL to 1 for
21561 		 * multirouted multicast packets:
21562 		 * multirouted multicast should not cross
21563 		 * multicast routers.
21564 		 */
21565 		if (ire->ire_flags & RTF_MULTIRT) {
21566 			if (ipha->ipha_ttl > 1) {
21567 				ip2dbg(("ip_wput: forcing multicast "
21568 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21569 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21570 				ipha->ipha_ttl = 1;
21571 			}
21572 		}
21573 	} else {
21574 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
21575 		if ((ire != NULL) && (ire->ire_type &
21576 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21577 			ignore_dontroute = B_TRUE;
21578 			ignore_nexthop = B_TRUE;
21579 		}
21580 		if (ire != NULL) {
21581 			ire_refrele(ire);
21582 			ire = NULL;
21583 		}
21584 		/*
21585 		 * Guard against coming in from arp in which case conn is NULL.
21586 		 * Also guard against non M_DATA with dontroute set but
21587 		 * destined to local, loopback or broadcast addresses.
21588 		 */
21589 		if (connp != NULL && connp->conn_dontroute &&
21590 		    !ignore_dontroute) {
21591 dontroute:
21592 			/*
21593 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21594 			 * routing protocols from seeing false direct
21595 			 * connectivity.
21596 			 */
21597 			ipha->ipha_ttl = 1;
21598 			/* If suitable ipif not found, drop packet */
21599 			dst_ipif = ipif_lookup_onlink_addr(dst, zoneid, ipst);
21600 			if (dst_ipif == NULL) {
21601 noroute:
21602 				ip1dbg(("ip_wput: no route for dst using"
21603 				    " SO_DONTROUTE\n"));
21604 				BUMP_MIB(&ipst->ips_ip_mib,
21605 				    ipIfStatsOutNoRoutes);
21606 				mp->b_prev = mp->b_next = NULL;
21607 				if (first_mp == NULL)
21608 					first_mp = mp;
21609 				goto drop_pkt;
21610 			} else {
21611 				/*
21612 				 * If suitable ipif has been found, set
21613 				 * xmit_ill to the corresponding
21614 				 * ipif_ill because we'll be using the
21615 				 * send_from_ill logic below.
21616 				 */
21617 				ASSERT(xmit_ill == NULL);
21618 				xmit_ill = dst_ipif->ipif_ill;
21619 				mutex_enter(&xmit_ill->ill_lock);
21620 				if (!ILL_CAN_LOOKUP(xmit_ill)) {
21621 					mutex_exit(&xmit_ill->ill_lock);
21622 					xmit_ill = NULL;
21623 					ipif_refrele(dst_ipif);
21624 					goto noroute;
21625 				}
21626 				ill_refhold_locked(xmit_ill);
21627 				mutex_exit(&xmit_ill->ill_lock);
21628 				ipif_refrele(dst_ipif);
21629 			}
21630 		}
21631 		/*
21632 		 * If we are bound to IPIF_NOFAILOVER address, look for
21633 		 * an IRE_CACHE matching the ill.
21634 		 */
21635 send_from_ill:
21636 		if (attach_ill != NULL) {
21637 			ipif_t	*attach_ipif;
21638 
21639 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21640 
21641 			/*
21642 			 * Check if we need an ire that will not be
21643 			 * looked up by anybody else i.e. HIDDEN.
21644 			 */
21645 			if (ill_is_probeonly(attach_ill)) {
21646 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21647 			}
21648 
21649 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
21650 			if (attach_ipif == NULL) {
21651 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
21652 				goto discard_pkt;
21653 			}
21654 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
21655 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21656 			ipif_refrele(attach_ipif);
21657 		} else if (xmit_ill != NULL) {
21658 			ipif_t *ipif;
21659 
21660 			/*
21661 			 * Mark this packet as originated locally
21662 			 */
21663 			mp->b_prev = mp->b_next = NULL;
21664 
21665 			/*
21666 			 * Could be SO_DONTROUTE case also.
21667 			 * Verify that at least one ipif is up on the ill.
21668 			 */
21669 			if (xmit_ill->ill_ipif_up_count == 0) {
21670 				ip1dbg(("ip_output: xmit_ill %s is down\n",
21671 				    xmit_ill->ill_name));
21672 				goto drop_pkt;
21673 			}
21674 
21675 			ipif = ipif_get_next_ipif(NULL, xmit_ill);
21676 			if (ipif == NULL) {
21677 				ip1dbg(("ip_output: xmit_ill %s NULL ipif\n",
21678 				    xmit_ill->ill_name));
21679 				goto drop_pkt;
21680 			}
21681 
21682 			/*
21683 			 * Look for a ire that is part of the group,
21684 			 * if found use it else call ip_newroute_ipif.
21685 			 * IPCL_ZONEID is not used for matching because
21686 			 * IP_ALLZONES option is valid only when the
21687 			 * ill is accessible from all zones i.e has a
21688 			 * valid ipif in all zones.
21689 			 */
21690 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
21691 			ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21692 			    MBLK_GETLABEL(mp), match_flags, ipst);
21693 			/*
21694 			 * If an ire exists use it or else create
21695 			 * an ire but don't add it to the cache.
21696 			 * Adding an ire may cause issues with
21697 			 * asymmetric routing.
21698 			 * In case of multiroute always act as if
21699 			 * ire does not exist.
21700 			 */
21701 			if (ire == NULL || ire->ire_flags & RTF_MULTIRT) {
21702 				if (ire != NULL)
21703 					ire_refrele(ire);
21704 				ip_newroute_ipif(q, first_mp, ipif,
21705 				    dst, connp, 0, zoneid, infop);
21706 				ipif_refrele(ipif);
21707 				ip1dbg(("ip_output: xmit_ill via %s\n",
21708 				    xmit_ill->ill_name));
21709 				ill_refrele(xmit_ill);
21710 				if (need_decref)
21711 					CONN_DEC_REF(connp);
21712 				return;
21713 			}
21714 			ipif_refrele(ipif);
21715 		} else if (ip_nexthop || (connp != NULL &&
21716 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21717 			if (!ip_nexthop) {
21718 				ip_nexthop = B_TRUE;
21719 				nexthop_addr = connp->conn_nexthop_v4;
21720 			}
21721 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21722 			    MATCH_IRE_GW;
21723 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21724 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21725 		} else {
21726 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp),
21727 			    ipst);
21728 		}
21729 		if (!ire) {
21730 			/*
21731 			 * Make sure we don't load spread if this
21732 			 * is IPIF_NOFAILOVER case.
21733 			 */
21734 			if ((attach_ill != NULL) ||
21735 			    (ip_nexthop && !ignore_nexthop)) {
21736 				if (mctl_present) {
21737 					io = (ipsec_out_t *)first_mp->b_rptr;
21738 					ASSERT(first_mp->b_datap->db_type ==
21739 					    M_CTL);
21740 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21741 				} else {
21742 					ASSERT(mp == first_mp);
21743 					first_mp = allocb(
21744 					    sizeof (ipsec_info_t), BPRI_HI);
21745 					if (first_mp == NULL) {
21746 						first_mp = mp;
21747 						goto discard_pkt;
21748 					}
21749 					first_mp->b_datap->db_type = M_CTL;
21750 					first_mp->b_wptr +=
21751 					    sizeof (ipsec_info_t);
21752 					/* ipsec_out_secure is B_FALSE now */
21753 					bzero(first_mp->b_rptr,
21754 					    sizeof (ipsec_info_t));
21755 					io = (ipsec_out_t *)first_mp->b_rptr;
21756 					io->ipsec_out_type = IPSEC_OUT;
21757 					io->ipsec_out_len =
21758 					    sizeof (ipsec_out_t);
21759 					io->ipsec_out_use_global_policy =
21760 					    B_TRUE;
21761 					io->ipsec_out_ns = ipst->ips_netstack;
21762 					first_mp->b_cont = mp;
21763 					mctl_present = B_TRUE;
21764 				}
21765 				if (attach_ill != NULL) {
21766 					io->ipsec_out_ill_index = attach_ill->
21767 					    ill_phyint->phyint_ifindex;
21768 					io->ipsec_out_attach_if = B_TRUE;
21769 				} else {
21770 					io->ipsec_out_ip_nexthop = ip_nexthop;
21771 					io->ipsec_out_nexthop_addr =
21772 					    nexthop_addr;
21773 				}
21774 			}
21775 noirefound:
21776 			/*
21777 			 * Mark this packet as having originated on
21778 			 * this machine.  This will be noted in
21779 			 * ire_add_then_send, which needs to know
21780 			 * whether to run it back through ip_wput or
21781 			 * ip_rput following successful resolution.
21782 			 */
21783 			mp->b_prev = NULL;
21784 			mp->b_next = NULL;
21785 			ip_newroute(q, first_mp, dst, connp, zoneid, ipst);
21786 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21787 			    "ip_wput_end: q %p (%S)", q, "newroute");
21788 			if (attach_ill != NULL)
21789 				ill_refrele(attach_ill);
21790 			if (xmit_ill != NULL)
21791 				ill_refrele(xmit_ill);
21792 			if (need_decref)
21793 				CONN_DEC_REF(connp);
21794 			return;
21795 		}
21796 	}
21797 
21798 	/* We now know where we are going with it. */
21799 
21800 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21801 	    "ip_wput_end: q %p (%S)", q, "end");
21802 
21803 	/*
21804 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21805 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21806 	 */
21807 	if (ire->ire_flags & RTF_MULTIRT) {
21808 		/*
21809 		 * Force the TTL of multirouted packets if required.
21810 		 * The TTL of such packets is bounded by the
21811 		 * ip_multirt_ttl ndd variable.
21812 		 */
21813 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21814 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21815 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21816 			    "(was %d), dst 0x%08x\n",
21817 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21818 			    ntohl(ire->ire_addr)));
21819 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21820 		}
21821 		/*
21822 		 * At this point, we check to see if there are any pending
21823 		 * unresolved routes. ire_multirt_resolvable()
21824 		 * checks in O(n) that all IRE_OFFSUBNET ire
21825 		 * entries for the packet's destination and
21826 		 * flagged RTF_MULTIRT are currently resolved.
21827 		 * If some remain unresolved, we make a copy
21828 		 * of the current message. It will be used
21829 		 * to initiate additional route resolutions.
21830 		 */
21831 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21832 		    MBLK_GETLABEL(first_mp), ipst);
21833 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21834 		    "multirt_need_resolve %d, first_mp %p\n",
21835 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21836 		if (multirt_need_resolve) {
21837 			copy_mp = copymsg(first_mp);
21838 			if (copy_mp != NULL) {
21839 				MULTIRT_DEBUG_TAG(copy_mp);
21840 			}
21841 		}
21842 	}
21843 
21844 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21845 	/*
21846 	 * Try to resolve another multiroute if
21847 	 * ire_multirt_resolvable() deemed it necessary.
21848 	 * At this point, we need to distinguish
21849 	 * multicasts from other packets. For multicasts,
21850 	 * we call ip_newroute_ipif() and request that both
21851 	 * multirouting and setsrc flags are checked.
21852 	 */
21853 	if (copy_mp != NULL) {
21854 		if (CLASSD(dst)) {
21855 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21856 			if (ipif) {
21857 				ASSERT(infop->ip_opt_ill_index == 0);
21858 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21859 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21860 				ipif_refrele(ipif);
21861 			} else {
21862 				MULTIRT_DEBUG_UNTAG(copy_mp);
21863 				freemsg(copy_mp);
21864 				copy_mp = NULL;
21865 			}
21866 		} else {
21867 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
21868 		}
21869 	}
21870 	if (attach_ill != NULL)
21871 		ill_refrele(attach_ill);
21872 	if (xmit_ill != NULL)
21873 		ill_refrele(xmit_ill);
21874 	if (need_decref)
21875 		CONN_DEC_REF(connp);
21876 	return;
21877 
21878 icmp_parameter_problem:
21879 	/* could not have originated externally */
21880 	ASSERT(mp->b_prev == NULL);
21881 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21882 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21883 		/* it's the IP header length that's in trouble */
21884 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21885 		first_mp = NULL;
21886 	}
21887 
21888 discard_pkt:
21889 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21890 drop_pkt:
21891 	ip1dbg(("ip_wput: dropped packet\n"));
21892 	if (ire != NULL)
21893 		ire_refrele(ire);
21894 	if (need_decref)
21895 		CONN_DEC_REF(connp);
21896 	freemsg(first_mp);
21897 	if (attach_ill != NULL)
21898 		ill_refrele(attach_ill);
21899 	if (xmit_ill != NULL)
21900 		ill_refrele(xmit_ill);
21901 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21902 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21903 }
21904 
21905 /*
21906  * If this is a conn_t queue, then we pass in the conn. This includes the
21907  * zoneid.
21908  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21909  * in which case we use the global zoneid since those are all part of
21910  * the global zone.
21911  */
21912 void
21913 ip_wput(queue_t *q, mblk_t *mp)
21914 {
21915 	if (CONN_Q(q))
21916 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21917 	else
21918 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21919 }
21920 
21921 /*
21922  *
21923  * The following rules must be observed when accessing any ipif or ill
21924  * that has been cached in the conn. Typically conn_nofailover_ill,
21925  * conn_outgoing_ill, conn_multicast_ipif and conn_multicast_ill.
21926  *
21927  * Access: The ipif or ill pointed to from the conn can be accessed under
21928  * the protection of the conn_lock or after it has been refheld under the
21929  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21930  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21931  * The reason for this is that a concurrent unplumb could actually be
21932  * cleaning up these cached pointers by walking the conns and might have
21933  * finished cleaning up the conn in question. The macros check that an
21934  * unplumb has not yet started on the ipif or ill.
21935  *
21936  * Caching: An ipif or ill pointer may be cached in the conn only after
21937  * making sure that an unplumb has not started. So the caching is done
21938  * while holding both the conn_lock and the ill_lock and after using the
21939  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21940  * flag before starting the cleanup of conns.
21941  *
21942  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21943  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21944  * or a reference to the ipif or a reference to an ire that references the
21945  * ipif. An ipif does not change its ill except for failover/failback. Since
21946  * failover/failback happens only after bringing down the ipif and making sure
21947  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
21948  * the above holds.
21949  */
21950 ipif_t *
21951 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21952 {
21953 	ipif_t	*ipif;
21954 	ill_t	*ill;
21955 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21956 
21957 	*err = 0;
21958 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21959 	mutex_enter(&connp->conn_lock);
21960 	ipif = *ipifp;
21961 	if (ipif != NULL) {
21962 		ill = ipif->ipif_ill;
21963 		mutex_enter(&ill->ill_lock);
21964 		if (IPIF_CAN_LOOKUP(ipif)) {
21965 			ipif_refhold_locked(ipif);
21966 			mutex_exit(&ill->ill_lock);
21967 			mutex_exit(&connp->conn_lock);
21968 			rw_exit(&ipst->ips_ill_g_lock);
21969 			return (ipif);
21970 		} else {
21971 			*err = IPIF_LOOKUP_FAILED;
21972 		}
21973 		mutex_exit(&ill->ill_lock);
21974 	}
21975 	mutex_exit(&connp->conn_lock);
21976 	rw_exit(&ipst->ips_ill_g_lock);
21977 	return (NULL);
21978 }
21979 
21980 ill_t *
21981 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21982 {
21983 	ill_t	*ill;
21984 
21985 	*err = 0;
21986 	mutex_enter(&connp->conn_lock);
21987 	ill = *illp;
21988 	if (ill != NULL) {
21989 		mutex_enter(&ill->ill_lock);
21990 		if (ILL_CAN_LOOKUP(ill)) {
21991 			ill_refhold_locked(ill);
21992 			mutex_exit(&ill->ill_lock);
21993 			mutex_exit(&connp->conn_lock);
21994 			return (ill);
21995 		} else {
21996 			*err = ILL_LOOKUP_FAILED;
21997 		}
21998 		mutex_exit(&ill->ill_lock);
21999 	}
22000 	mutex_exit(&connp->conn_lock);
22001 	return (NULL);
22002 }
22003 
22004 static int
22005 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
22006 {
22007 	ill_t	*ill;
22008 
22009 	ill = ipif->ipif_ill;
22010 	mutex_enter(&connp->conn_lock);
22011 	mutex_enter(&ill->ill_lock);
22012 	if (IPIF_CAN_LOOKUP(ipif)) {
22013 		*ipifp = ipif;
22014 		mutex_exit(&ill->ill_lock);
22015 		mutex_exit(&connp->conn_lock);
22016 		return (0);
22017 	}
22018 	mutex_exit(&ill->ill_lock);
22019 	mutex_exit(&connp->conn_lock);
22020 	return (IPIF_LOOKUP_FAILED);
22021 }
22022 
22023 /*
22024  * This is called if the outbound datagram needs fragmentation.
22025  *
22026  * NOTE : This function does not ire_refrele the ire argument passed in.
22027  */
22028 static void
22029 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
22030     ip_stack_t *ipst, conn_t *connp)
22031 {
22032 	ipha_t		*ipha;
22033 	mblk_t		*mp;
22034 	uint32_t	v_hlen_tos_len;
22035 	uint32_t	max_frag;
22036 	uint32_t	frag_flag;
22037 	boolean_t	dont_use;
22038 
22039 	if (ipsec_mp->b_datap->db_type == M_CTL) {
22040 		mp = ipsec_mp->b_cont;
22041 	} else {
22042 		mp = ipsec_mp;
22043 	}
22044 
22045 	ipha = (ipha_t *)mp->b_rptr;
22046 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22047 
22048 #ifdef	_BIG_ENDIAN
22049 #define	V_HLEN	(v_hlen_tos_len >> 24)
22050 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22051 #else
22052 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22053 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22054 #endif
22055 
22056 #ifndef SPEED_BEFORE_SAFETY
22057 	/*
22058 	 * Check that ipha_length is consistent with
22059 	 * the mblk length
22060 	 */
22061 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
22062 		ip0dbg(("Packet length mismatch: %d, %ld\n",
22063 		    LENGTH, msgdsize(mp)));
22064 		freemsg(ipsec_mp);
22065 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22066 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
22067 		    "packet length mismatch");
22068 		return;
22069 	}
22070 #endif
22071 	/*
22072 	 * Don't use frag_flag if pre-built packet or source
22073 	 * routed or if multicast (since multicast packets do not solicit
22074 	 * ICMP "packet too big" messages). Get the values of
22075 	 * max_frag and frag_flag atomically by acquiring the
22076 	 * ire_lock.
22077 	 */
22078 	mutex_enter(&ire->ire_lock);
22079 	max_frag = ire->ire_max_frag;
22080 	frag_flag = ire->ire_frag_flag;
22081 	mutex_exit(&ire->ire_lock);
22082 
22083 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
22084 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
22085 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
22086 
22087 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
22088 	    (dont_use ? 0 : frag_flag), zoneid, ipst, connp);
22089 }
22090 
22091 /*
22092  * Used for deciding the MSS size for the upper layer. Thus
22093  * we need to check the outbound policy values in the conn.
22094  */
22095 int
22096 conn_ipsec_length(conn_t *connp)
22097 {
22098 	ipsec_latch_t *ipl;
22099 
22100 	ipl = connp->conn_latch;
22101 	if (ipl == NULL)
22102 		return (0);
22103 
22104 	if (ipl->ipl_out_policy == NULL)
22105 		return (0);
22106 
22107 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
22108 }
22109 
22110 /*
22111  * Returns an estimate of the IPsec headers size. This is used if
22112  * we don't want to call into IPsec to get the exact size.
22113  */
22114 int
22115 ipsec_out_extra_length(mblk_t *ipsec_mp)
22116 {
22117 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
22118 	ipsec_action_t *a;
22119 
22120 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
22121 	if (!io->ipsec_out_secure)
22122 		return (0);
22123 
22124 	a = io->ipsec_out_act;
22125 
22126 	if (a == NULL) {
22127 		ASSERT(io->ipsec_out_policy != NULL);
22128 		a = io->ipsec_out_policy->ipsp_act;
22129 	}
22130 	ASSERT(a != NULL);
22131 
22132 	return (a->ipa_ovhd);
22133 }
22134 
22135 /*
22136  * Returns an estimate of the IPsec headers size. This is used if
22137  * we don't want to call into IPsec to get the exact size.
22138  */
22139 int
22140 ipsec_in_extra_length(mblk_t *ipsec_mp)
22141 {
22142 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
22143 	ipsec_action_t *a;
22144 
22145 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
22146 
22147 	a = ii->ipsec_in_action;
22148 	return (a == NULL ? 0 : a->ipa_ovhd);
22149 }
22150 
22151 /*
22152  * If there are any source route options, return the true final
22153  * destination. Otherwise, return the destination.
22154  */
22155 ipaddr_t
22156 ip_get_dst(ipha_t *ipha)
22157 {
22158 	ipoptp_t	opts;
22159 	uchar_t		*opt;
22160 	uint8_t		optval;
22161 	uint8_t		optlen;
22162 	ipaddr_t	dst;
22163 	uint32_t off;
22164 
22165 	dst = ipha->ipha_dst;
22166 
22167 	if (IS_SIMPLE_IPH(ipha))
22168 		return (dst);
22169 
22170 	for (optval = ipoptp_first(&opts, ipha);
22171 	    optval != IPOPT_EOL;
22172 	    optval = ipoptp_next(&opts)) {
22173 		opt = opts.ipoptp_cur;
22174 		optlen = opts.ipoptp_len;
22175 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
22176 		switch (optval) {
22177 		case IPOPT_SSRR:
22178 		case IPOPT_LSRR:
22179 			off = opt[IPOPT_OFFSET];
22180 			/*
22181 			 * If one of the conditions is true, it means
22182 			 * end of options and dst already has the right
22183 			 * value.
22184 			 */
22185 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
22186 				off = optlen - IP_ADDR_LEN;
22187 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
22188 			}
22189 			return (dst);
22190 		default:
22191 			break;
22192 		}
22193 	}
22194 
22195 	return (dst);
22196 }
22197 
22198 mblk_t *
22199 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
22200     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
22201 {
22202 	ipsec_out_t	*io;
22203 	mblk_t		*first_mp;
22204 	boolean_t policy_present;
22205 	ip_stack_t	*ipst;
22206 	ipsec_stack_t	*ipss;
22207 
22208 	ASSERT(ire != NULL);
22209 	ipst = ire->ire_ipst;
22210 	ipss = ipst->ips_netstack->netstack_ipsec;
22211 
22212 	first_mp = mp;
22213 	if (mp->b_datap->db_type == M_CTL) {
22214 		io = (ipsec_out_t *)first_mp->b_rptr;
22215 		/*
22216 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
22217 		 *
22218 		 * 1) There is per-socket policy (including cached global
22219 		 *    policy) or a policy on the IP-in-IP tunnel.
22220 		 * 2) There is no per-socket policy, but it is
22221 		 *    a multicast packet that needs to go out
22222 		 *    on a specific interface. This is the case
22223 		 *    where (ip_wput and ip_wput_multicast) attaches
22224 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
22225 		 *
22226 		 * In case (2) we check with global policy to
22227 		 * see if there is a match and set the ill_index
22228 		 * appropriately so that we can lookup the ire
22229 		 * properly in ip_wput_ipsec_out.
22230 		 */
22231 
22232 		/*
22233 		 * ipsec_out_use_global_policy is set to B_FALSE
22234 		 * in ipsec_in_to_out(). Refer to that function for
22235 		 * details.
22236 		 */
22237 		if ((io->ipsec_out_latch == NULL) &&
22238 		    (io->ipsec_out_use_global_policy)) {
22239 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
22240 			    ire, connp, unspec_src, zoneid));
22241 		}
22242 		if (!io->ipsec_out_secure) {
22243 			/*
22244 			 * If this is not a secure packet, drop
22245 			 * the IPSEC_OUT mp and treat it as a clear
22246 			 * packet. This happens when we are sending
22247 			 * a ICMP reply back to a clear packet. See
22248 			 * ipsec_in_to_out() for details.
22249 			 */
22250 			mp = first_mp->b_cont;
22251 			freeb(first_mp);
22252 		}
22253 		return (mp);
22254 	}
22255 	/*
22256 	 * See whether we need to attach a global policy here. We
22257 	 * don't depend on the conn (as it could be null) for deciding
22258 	 * what policy this datagram should go through because it
22259 	 * should have happened in ip_wput if there was some
22260 	 * policy. This normally happens for connections which are not
22261 	 * fully bound preventing us from caching policies in
22262 	 * ip_bind. Packets coming from the TCP listener/global queue
22263 	 * - which are non-hard_bound - could also be affected by
22264 	 * applying policy here.
22265 	 *
22266 	 * If this packet is coming from tcp global queue or listener,
22267 	 * we will be applying policy here.  This may not be *right*
22268 	 * if these packets are coming from the detached connection as
22269 	 * it could have gone in clear before. This happens only if a
22270 	 * TCP connection started when there is no policy and somebody
22271 	 * added policy before it became detached. Thus packets of the
22272 	 * detached connection could go out secure and the other end
22273 	 * would drop it because it will be expecting in clear. The
22274 	 * converse is not true i.e if somebody starts a TCP
22275 	 * connection and deletes the policy, all the packets will
22276 	 * still go out with the policy that existed before deleting
22277 	 * because ip_unbind sends up policy information which is used
22278 	 * by TCP on subsequent ip_wputs. The right solution is to fix
22279 	 * TCP to attach a dummy IPSEC_OUT and set
22280 	 * ipsec_out_use_global_policy to B_FALSE. As this might
22281 	 * affect performance for normal cases, we are not doing it.
22282 	 * Thus, set policy before starting any TCP connections.
22283 	 *
22284 	 * NOTE - We might apply policy even for a hard bound connection
22285 	 * - for which we cached policy in ip_bind - if somebody added
22286 	 * global policy after we inherited the policy in ip_bind.
22287 	 * This means that the packets that were going out in clear
22288 	 * previously would start going secure and hence get dropped
22289 	 * on the other side. To fix this, TCP attaches a dummy
22290 	 * ipsec_out and make sure that we don't apply global policy.
22291 	 */
22292 	if (ipha != NULL)
22293 		policy_present = ipss->ipsec_outbound_v4_policy_present;
22294 	else
22295 		policy_present = ipss->ipsec_outbound_v6_policy_present;
22296 	if (!policy_present)
22297 		return (mp);
22298 
22299 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
22300 	    zoneid));
22301 }
22302 
22303 ire_t *
22304 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
22305 {
22306 	ipaddr_t addr;
22307 	ire_t *save_ire;
22308 	irb_t *irb;
22309 	ill_group_t *illgrp;
22310 	int	err;
22311 
22312 	save_ire = ire;
22313 	addr = ire->ire_addr;
22314 
22315 	ASSERT(ire->ire_type == IRE_BROADCAST);
22316 
22317 	illgrp = connp->conn_outgoing_ill->ill_group;
22318 	if (illgrp == NULL) {
22319 		*conn_outgoing_ill = conn_get_held_ill(connp,
22320 		    &connp->conn_outgoing_ill, &err);
22321 		if (err == ILL_LOOKUP_FAILED) {
22322 			ire_refrele(save_ire);
22323 			return (NULL);
22324 		}
22325 		return (save_ire);
22326 	}
22327 	/*
22328 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
22329 	 * If it is part of the group, we need to send on the ire
22330 	 * that has been cleared of IRE_MARK_NORECV and that belongs
22331 	 * to this group. This is okay as IP_BOUND_IF really means
22332 	 * any ill in the group. We depend on the fact that the
22333 	 * first ire in the group is always cleared of IRE_MARK_NORECV
22334 	 * if such an ire exists. This is possible only if you have
22335 	 * at least one ill in the group that has not failed.
22336 	 *
22337 	 * First get to the ire that matches the address and group.
22338 	 *
22339 	 * We don't look for an ire with a matching zoneid because a given zone
22340 	 * won't always have broadcast ires on all ills in the group.
22341 	 */
22342 	irb = ire->ire_bucket;
22343 	rw_enter(&irb->irb_lock, RW_READER);
22344 	if (ire->ire_marks & IRE_MARK_NORECV) {
22345 		/*
22346 		 * If the current zone only has an ire broadcast for this
22347 		 * address marked NORECV, the ire we want is ahead in the
22348 		 * bucket, so we look it up deliberately ignoring the zoneid.
22349 		 */
22350 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
22351 			if (ire->ire_addr != addr)
22352 				continue;
22353 			/* skip over deleted ires */
22354 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
22355 				continue;
22356 		}
22357 	}
22358 	while (ire != NULL) {
22359 		/*
22360 		 * If a new interface is coming up, we could end up
22361 		 * seeing the loopback ire and the non-loopback ire
22362 		 * may not have been added yet. So check for ire_stq
22363 		 */
22364 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
22365 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
22366 			break;
22367 		}
22368 		ire = ire->ire_next;
22369 	}
22370 	if (ire != NULL && ire->ire_addr == addr &&
22371 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
22372 		IRE_REFHOLD(ire);
22373 		rw_exit(&irb->irb_lock);
22374 		ire_refrele(save_ire);
22375 		*conn_outgoing_ill = ire_to_ill(ire);
22376 		/*
22377 		 * Refhold the ill to make the conn_outgoing_ill
22378 		 * independent of the ire. ip_wput_ire goes in a loop
22379 		 * and may refrele the ire. Since we have an ire at this
22380 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
22381 		 */
22382 		ill_refhold(*conn_outgoing_ill);
22383 		return (ire);
22384 	}
22385 	rw_exit(&irb->irb_lock);
22386 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
22387 	/*
22388 	 * If we can't find a suitable ire, return the original ire.
22389 	 */
22390 	return (save_ire);
22391 }
22392 
22393 /*
22394  * This function does the ire_refrele of the ire passed in as the
22395  * argument. As this function looks up more ires i.e broadcast ires,
22396  * it needs to REFRELE them. Currently, for simplicity we don't
22397  * differentiate the one passed in and looked up here. We always
22398  * REFRELE.
22399  * IPQoS Notes:
22400  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
22401  * IPsec packets are done in ipsec_out_process.
22402  *
22403  */
22404 void
22405 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
22406     zoneid_t zoneid)
22407 {
22408 	ipha_t		*ipha;
22409 #define	rptr	((uchar_t *)ipha)
22410 	queue_t		*stq;
22411 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
22412 	uint32_t	v_hlen_tos_len;
22413 	uint32_t	ttl_protocol;
22414 	ipaddr_t	src;
22415 	ipaddr_t	dst;
22416 	uint32_t	cksum;
22417 	ipaddr_t	orig_src;
22418 	ire_t		*ire1;
22419 	mblk_t		*next_mp;
22420 	uint_t		hlen;
22421 	uint16_t	*up;
22422 	uint32_t	max_frag = ire->ire_max_frag;
22423 	ill_t		*ill = ire_to_ill(ire);
22424 	int		clusterwide;
22425 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
22426 	int		ipsec_len;
22427 	mblk_t		*first_mp;
22428 	ipsec_out_t	*io;
22429 	boolean_t	conn_dontroute;		/* conn value for multicast */
22430 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
22431 	boolean_t	multicast_forward;	/* Should we forward ? */
22432 	boolean_t	unspec_src;
22433 	ill_t		*conn_outgoing_ill = NULL;
22434 	ill_t		*ire_ill;
22435 	ill_t		*ire1_ill;
22436 	ill_t		*out_ill;
22437 	uint32_t 	ill_index = 0;
22438 	boolean_t	multirt_send = B_FALSE;
22439 	int		err;
22440 	ipxmit_state_t	pktxmit_state;
22441 	ip_stack_t	*ipst = ire->ire_ipst;
22442 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
22443 
22444 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
22445 	    "ip_wput_ire_start: q %p", q);
22446 
22447 	multicast_forward = B_FALSE;
22448 	unspec_src = (connp != NULL && connp->conn_unspec_src);
22449 
22450 	if (ire->ire_flags & RTF_MULTIRT) {
22451 		/*
22452 		 * Multirouting case. The bucket where ire is stored
22453 		 * probably holds other RTF_MULTIRT flagged ire
22454 		 * to the destination. In this call to ip_wput_ire,
22455 		 * we attempt to send the packet through all
22456 		 * those ires. Thus, we first ensure that ire is the
22457 		 * first RTF_MULTIRT ire in the bucket,
22458 		 * before walking the ire list.
22459 		 */
22460 		ire_t *first_ire;
22461 		irb_t *irb = ire->ire_bucket;
22462 		ASSERT(irb != NULL);
22463 
22464 		/* Make sure we do not omit any multiroute ire. */
22465 		IRB_REFHOLD(irb);
22466 		for (first_ire = irb->irb_ire;
22467 		    first_ire != NULL;
22468 		    first_ire = first_ire->ire_next) {
22469 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22470 			    (first_ire->ire_addr == ire->ire_addr) &&
22471 			    !(first_ire->ire_marks &
22472 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
22473 				break;
22474 			}
22475 		}
22476 
22477 		if ((first_ire != NULL) && (first_ire != ire)) {
22478 			IRE_REFHOLD(first_ire);
22479 			ire_refrele(ire);
22480 			ire = first_ire;
22481 			ill = ire_to_ill(ire);
22482 		}
22483 		IRB_REFRELE(irb);
22484 	}
22485 
22486 	/*
22487 	 * conn_outgoing_ill variable is used only in the broadcast loop.
22488 	 * for performance we don't grab the mutexs in the fastpath
22489 	 */
22490 	if ((connp != NULL) &&
22491 	    (ire->ire_type == IRE_BROADCAST) &&
22492 	    ((connp->conn_nofailover_ill != NULL) ||
22493 	    (connp->conn_outgoing_ill != NULL))) {
22494 		/*
22495 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
22496 		 * option. So, see if this endpoint is bound to a
22497 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
22498 		 * that if the interface is failed, we will still send
22499 		 * the packet on the same ill which is what we want.
22500 		 */
22501 		conn_outgoing_ill = conn_get_held_ill(connp,
22502 		    &connp->conn_nofailover_ill, &err);
22503 		if (err == ILL_LOOKUP_FAILED) {
22504 			ire_refrele(ire);
22505 			freemsg(mp);
22506 			return;
22507 		}
22508 		if (conn_outgoing_ill == NULL) {
22509 			/*
22510 			 * Choose a good ill in the group to send the
22511 			 * packets on.
22512 			 */
22513 			ire = conn_set_outgoing_ill(connp, ire,
22514 			    &conn_outgoing_ill);
22515 			if (ire == NULL) {
22516 				freemsg(mp);
22517 				return;
22518 			}
22519 		}
22520 	}
22521 
22522 	if (mp->b_datap->db_type != M_CTL) {
22523 		ipha = (ipha_t *)mp->b_rptr;
22524 	} else {
22525 		io = (ipsec_out_t *)mp->b_rptr;
22526 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22527 		ASSERT(zoneid == io->ipsec_out_zoneid);
22528 		ASSERT(zoneid != ALL_ZONES);
22529 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22530 		dst = ipha->ipha_dst;
22531 		/*
22532 		 * For the multicast case, ipsec_out carries conn_dontroute and
22533 		 * conn_multicast_loop as conn may not be available here. We
22534 		 * need this for multicast loopback and forwarding which is done
22535 		 * later in the code.
22536 		 */
22537 		if (CLASSD(dst)) {
22538 			conn_dontroute = io->ipsec_out_dontroute;
22539 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22540 			/*
22541 			 * If conn_dontroute is not set or conn_multicast_loop
22542 			 * is set, we need to do forwarding/loopback. For
22543 			 * datagrams from ip_wput_multicast, conn_dontroute is
22544 			 * set to B_TRUE and conn_multicast_loop is set to
22545 			 * B_FALSE so that we neither do forwarding nor
22546 			 * loopback.
22547 			 */
22548 			if (!conn_dontroute || conn_multicast_loop)
22549 				multicast_forward = B_TRUE;
22550 		}
22551 	}
22552 
22553 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22554 	    ire->ire_zoneid != ALL_ZONES) {
22555 		/*
22556 		 * When a zone sends a packet to another zone, we try to deliver
22557 		 * the packet under the same conditions as if the destination
22558 		 * was a real node on the network. To do so, we look for a
22559 		 * matching route in the forwarding table.
22560 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22561 		 * ip_newroute() does.
22562 		 * Note that IRE_LOCAL are special, since they are used
22563 		 * when the zoneid doesn't match in some cases. This means that
22564 		 * we need to handle ipha_src differently since ire_src_addr
22565 		 * belongs to the receiving zone instead of the sending zone.
22566 		 * When ip_restrict_interzone_loopback is set, then
22567 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22568 		 * for loopback between zones when the logical "Ethernet" would
22569 		 * have looped them back.
22570 		 */
22571 		ire_t *src_ire;
22572 
22573 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22574 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22575 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22576 		if (src_ire != NULL &&
22577 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22578 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22579 		    ire_local_same_ill_group(ire, src_ire))) {
22580 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22581 				ipha->ipha_src = src_ire->ire_src_addr;
22582 			ire_refrele(src_ire);
22583 		} else {
22584 			ire_refrele(ire);
22585 			if (conn_outgoing_ill != NULL)
22586 				ill_refrele(conn_outgoing_ill);
22587 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22588 			if (src_ire != NULL) {
22589 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22590 					ire_refrele(src_ire);
22591 					freemsg(mp);
22592 					return;
22593 				}
22594 				ire_refrele(src_ire);
22595 			}
22596 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22597 				/* Failed */
22598 				freemsg(mp);
22599 				return;
22600 			}
22601 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22602 			    ipst);
22603 			return;
22604 		}
22605 	}
22606 
22607 	if (mp->b_datap->db_type == M_CTL ||
22608 	    ipss->ipsec_outbound_v4_policy_present) {
22609 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22610 		    unspec_src, zoneid);
22611 		if (mp == NULL) {
22612 			ire_refrele(ire);
22613 			if (conn_outgoing_ill != NULL)
22614 				ill_refrele(conn_outgoing_ill);
22615 			return;
22616 		}
22617 		/*
22618 		 * Trusted Extensions supports all-zones interfaces, so
22619 		 * zoneid == ALL_ZONES is valid, but IPsec maps ALL_ZONES to
22620 		 * the global zone.
22621 		 */
22622 		if (zoneid == ALL_ZONES && mp->b_datap->db_type == M_CTL) {
22623 			io = (ipsec_out_t *)mp->b_rptr;
22624 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
22625 			zoneid = io->ipsec_out_zoneid;
22626 		}
22627 	}
22628 
22629 	first_mp = mp;
22630 	ipsec_len = 0;
22631 
22632 	if (first_mp->b_datap->db_type == M_CTL) {
22633 		io = (ipsec_out_t *)first_mp->b_rptr;
22634 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22635 		mp = first_mp->b_cont;
22636 		ipsec_len = ipsec_out_extra_length(first_mp);
22637 		ASSERT(ipsec_len >= 0);
22638 		/* We already picked up the zoneid from the M_CTL above */
22639 		ASSERT(zoneid == io->ipsec_out_zoneid);
22640 		ASSERT(zoneid != ALL_ZONES);
22641 
22642 		/*
22643 		 * Drop M_CTL here if IPsec processing is not needed.
22644 		 * (Non-IPsec use of M_CTL extracted any information it
22645 		 * needed above).
22646 		 */
22647 		if (ipsec_len == 0) {
22648 			freeb(first_mp);
22649 			first_mp = mp;
22650 		}
22651 	}
22652 
22653 	/*
22654 	 * Fast path for ip_wput_ire
22655 	 */
22656 
22657 	ipha = (ipha_t *)mp->b_rptr;
22658 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22659 	dst = ipha->ipha_dst;
22660 
22661 	/*
22662 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22663 	 * if the socket is a SOCK_RAW type. The transport checksum should
22664 	 * be provided in the pre-built packet, so we don't need to compute it.
22665 	 * Also, other application set flags, like DF, should not be altered.
22666 	 * Other transport MUST pass down zero.
22667 	 */
22668 	ip_hdr_included = ipha->ipha_ident;
22669 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22670 
22671 	if (CLASSD(dst)) {
22672 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22673 		    ntohl(dst),
22674 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22675 		    ntohl(ire->ire_addr)));
22676 	}
22677 
22678 /* Macros to extract header fields from data already in registers */
22679 #ifdef	_BIG_ENDIAN
22680 #define	V_HLEN	(v_hlen_tos_len >> 24)
22681 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22682 #define	PROTO	(ttl_protocol & 0xFF)
22683 #else
22684 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22685 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22686 #define	PROTO	(ttl_protocol >> 8)
22687 #endif
22688 
22689 
22690 	orig_src = src = ipha->ipha_src;
22691 	/* (The loop back to "another" is explained down below.) */
22692 another:;
22693 	/*
22694 	 * Assign an ident value for this packet.  We assign idents on
22695 	 * a per destination basis out of the IRE.  There could be
22696 	 * other threads targeting the same destination, so we have to
22697 	 * arrange for a atomic increment.  Note that we use a 32-bit
22698 	 * atomic add because it has better performance than its
22699 	 * 16-bit sibling.
22700 	 *
22701 	 * If running in cluster mode and if the source address
22702 	 * belongs to a replicated service then vector through
22703 	 * cl_inet_ipident vector to allocate ip identifier
22704 	 * NOTE: This is a contract private interface with the
22705 	 * clustering group.
22706 	 */
22707 	clusterwide = 0;
22708 	if (cl_inet_ipident) {
22709 		ASSERT(cl_inet_isclusterwide);
22710 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
22711 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
22712 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
22713 			    AF_INET, (uint8_t *)(uintptr_t)src,
22714 			    (uint8_t *)(uintptr_t)dst);
22715 			clusterwide = 1;
22716 		}
22717 	}
22718 	if (!clusterwide) {
22719 		ipha->ipha_ident =
22720 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22721 	}
22722 
22723 #ifndef _BIG_ENDIAN
22724 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22725 #endif
22726 
22727 	/*
22728 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22729 	 * This is needed to obey conn_unspec_src when packets go through
22730 	 * ip_newroute + arp.
22731 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22732 	 */
22733 	if (src == INADDR_ANY && !unspec_src) {
22734 		/*
22735 		 * Assign the appropriate source address from the IRE if none
22736 		 * was specified.
22737 		 */
22738 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22739 
22740 		/*
22741 		 * With IP multipathing, broadcast packets are sent on the ire
22742 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
22743 		 * the group. However, this ire might not be in the same zone so
22744 		 * we can't always use its source address. We look for a
22745 		 * broadcast ire in the same group and in the right zone.
22746 		 */
22747 		if (ire->ire_type == IRE_BROADCAST &&
22748 		    ire->ire_zoneid != zoneid) {
22749 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
22750 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
22751 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
22752 			if (src_ire != NULL) {
22753 				src = src_ire->ire_src_addr;
22754 				ire_refrele(src_ire);
22755 			} else {
22756 				ire_refrele(ire);
22757 				if (conn_outgoing_ill != NULL)
22758 					ill_refrele(conn_outgoing_ill);
22759 				freemsg(first_mp);
22760 				if (ill != NULL) {
22761 					BUMP_MIB(ill->ill_ip_mib,
22762 					    ipIfStatsOutDiscards);
22763 				} else {
22764 					BUMP_MIB(&ipst->ips_ip_mib,
22765 					    ipIfStatsOutDiscards);
22766 				}
22767 				return;
22768 			}
22769 		} else {
22770 			src = ire->ire_src_addr;
22771 		}
22772 
22773 		if (connp == NULL) {
22774 			ip1dbg(("ip_wput_ire: no connp and no src "
22775 			    "address for dst 0x%x, using src 0x%x\n",
22776 			    ntohl(dst),
22777 			    ntohl(src)));
22778 		}
22779 		ipha->ipha_src = src;
22780 	}
22781 	stq = ire->ire_stq;
22782 
22783 	/*
22784 	 * We only allow ire chains for broadcasts since there will
22785 	 * be multiple IRE_CACHE entries for the same multicast
22786 	 * address (one per ipif).
22787 	 */
22788 	next_mp = NULL;
22789 
22790 	/* broadcast packet */
22791 	if (ire->ire_type == IRE_BROADCAST)
22792 		goto broadcast;
22793 
22794 	/* loopback ? */
22795 	if (stq == NULL)
22796 		goto nullstq;
22797 
22798 	/* The ill_index for outbound ILL */
22799 	ill_index = Q_TO_INDEX(stq);
22800 
22801 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22802 	ttl_protocol = ((uint16_t *)ipha)[4];
22803 
22804 	/* pseudo checksum (do it in parts for IP header checksum) */
22805 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22806 
22807 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22808 		queue_t *dev_q = stq->q_next;
22809 
22810 		/* flow controlled */
22811 		if (DEV_Q_FLOW_BLOCKED(dev_q))
22812 			goto blocked;
22813 
22814 		if ((PROTO == IPPROTO_UDP) &&
22815 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22816 			hlen = (V_HLEN & 0xF) << 2;
22817 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22818 			if (*up != 0) {
22819 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22820 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22821 				/* Software checksum? */
22822 				if (DB_CKSUMFLAGS(mp) == 0) {
22823 					IP_STAT(ipst, ip_out_sw_cksum);
22824 					IP_STAT_UPDATE(ipst,
22825 					    ip_udp_out_sw_cksum_bytes,
22826 					    LENGTH - hlen);
22827 				}
22828 			}
22829 		}
22830 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22831 		hlen = (V_HLEN & 0xF) << 2;
22832 		if (PROTO == IPPROTO_TCP) {
22833 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22834 			/*
22835 			 * The packet header is processed once and for all, even
22836 			 * in the multirouting case. We disable hardware
22837 			 * checksum if the packet is multirouted, as it will be
22838 			 * replicated via several interfaces, and not all of
22839 			 * them may have this capability.
22840 			 */
22841 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22842 			    LENGTH, max_frag, ipsec_len, cksum);
22843 			/* Software checksum? */
22844 			if (DB_CKSUMFLAGS(mp) == 0) {
22845 				IP_STAT(ipst, ip_out_sw_cksum);
22846 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22847 				    LENGTH - hlen);
22848 			}
22849 		} else {
22850 			sctp_hdr_t	*sctph;
22851 
22852 			ASSERT(PROTO == IPPROTO_SCTP);
22853 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22854 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22855 			/*
22856 			 * Zero out the checksum field to ensure proper
22857 			 * checksum calculation.
22858 			 */
22859 			sctph->sh_chksum = 0;
22860 #ifdef	DEBUG
22861 			if (!skip_sctp_cksum)
22862 #endif
22863 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22864 		}
22865 	}
22866 
22867 	/*
22868 	 * If this is a multicast packet and originated from ip_wput
22869 	 * we need to do loopback and forwarding checks. If it comes
22870 	 * from ip_wput_multicast, we SHOULD not do this.
22871 	 */
22872 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22873 
22874 	/* checksum */
22875 	cksum += ttl_protocol;
22876 
22877 	/* fragment the packet */
22878 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22879 		goto fragmentit;
22880 	/*
22881 	 * Don't use frag_flag if packet is pre-built or source
22882 	 * routed or if multicast (since multicast packets do
22883 	 * not solicit ICMP "packet too big" messages).
22884 	 */
22885 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22886 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22887 	    !ip_source_route_included(ipha)) &&
22888 	    !CLASSD(ipha->ipha_dst))
22889 		ipha->ipha_fragment_offset_and_flags |=
22890 		    htons(ire->ire_frag_flag);
22891 
22892 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22893 		/* calculate IP header checksum */
22894 		cksum += ipha->ipha_ident;
22895 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22896 		cksum += ipha->ipha_fragment_offset_and_flags;
22897 
22898 		/* IP options present */
22899 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22900 		if (hlen)
22901 			goto checksumoptions;
22902 
22903 		/* calculate hdr checksum */
22904 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22905 		cksum = ~(cksum + (cksum >> 16));
22906 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22907 	}
22908 	if (ipsec_len != 0) {
22909 		/*
22910 		 * We will do the rest of the processing after
22911 		 * we come back from IPsec in ip_wput_ipsec_out().
22912 		 */
22913 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22914 
22915 		io = (ipsec_out_t *)first_mp->b_rptr;
22916 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
22917 		    ill_phyint->phyint_ifindex;
22918 
22919 		ipsec_out_process(q, first_mp, ire, ill_index);
22920 		ire_refrele(ire);
22921 		if (conn_outgoing_ill != NULL)
22922 			ill_refrele(conn_outgoing_ill);
22923 		return;
22924 	}
22925 
22926 	/*
22927 	 * In most cases, the emission loop below is entered only
22928 	 * once. Only in the case where the ire holds the
22929 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22930 	 * flagged ires in the bucket, and send the packet
22931 	 * through all crossed RTF_MULTIRT routes.
22932 	 */
22933 	if (ire->ire_flags & RTF_MULTIRT) {
22934 		multirt_send = B_TRUE;
22935 	}
22936 	do {
22937 		if (multirt_send) {
22938 			irb_t *irb;
22939 			/*
22940 			 * We are in a multiple send case, need to get
22941 			 * the next ire and make a duplicate of the packet.
22942 			 * ire1 holds here the next ire to process in the
22943 			 * bucket. If multirouting is expected,
22944 			 * any non-RTF_MULTIRT ire that has the
22945 			 * right destination address is ignored.
22946 			 */
22947 			irb = ire->ire_bucket;
22948 			ASSERT(irb != NULL);
22949 
22950 			IRB_REFHOLD(irb);
22951 			for (ire1 = ire->ire_next;
22952 			    ire1 != NULL;
22953 			    ire1 = ire1->ire_next) {
22954 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22955 					continue;
22956 				if (ire1->ire_addr != ire->ire_addr)
22957 					continue;
22958 				if (ire1->ire_marks &
22959 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
22960 					continue;
22961 
22962 				/* Got one */
22963 				IRE_REFHOLD(ire1);
22964 				break;
22965 			}
22966 			IRB_REFRELE(irb);
22967 
22968 			if (ire1 != NULL) {
22969 				next_mp = copyb(mp);
22970 				if ((next_mp == NULL) ||
22971 				    ((mp->b_cont != NULL) &&
22972 				    ((next_mp->b_cont =
22973 				    dupmsg(mp->b_cont)) == NULL))) {
22974 					freemsg(next_mp);
22975 					next_mp = NULL;
22976 					ire_refrele(ire1);
22977 					ire1 = NULL;
22978 				}
22979 			}
22980 
22981 			/* Last multiroute ire; don't loop anymore. */
22982 			if (ire1 == NULL) {
22983 				multirt_send = B_FALSE;
22984 			}
22985 		}
22986 
22987 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22988 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22989 		    mblk_t *, mp);
22990 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22991 		    ipst->ips_ipv4firewall_physical_out,
22992 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, 0, ipst);
22993 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22994 
22995 		if (mp == NULL)
22996 			goto release_ire_and_ill;
22997 
22998 		if (ipst->ips_ipobs_enabled) {
22999 			zoneid_t szone;
23000 
23001 			/*
23002 			 * On the outbound path the destination zone will be
23003 			 * unknown as we're sending this packet out on the
23004 			 * wire.
23005 			 */
23006 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp, ipst,
23007 			    ALL_ZONES);
23008 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
23009 			    ire->ire_ipif->ipif_ill, IPV4_VERSION, 0, ipst);
23010 		}
23011 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
23012 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
23013 
23014 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE, connp);
23015 
23016 		if ((pktxmit_state == SEND_FAILED) ||
23017 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23018 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
23019 			    "- packet dropped\n"));
23020 release_ire_and_ill:
23021 			ire_refrele(ire);
23022 			if (next_mp != NULL) {
23023 				freemsg(next_mp);
23024 				ire_refrele(ire1);
23025 			}
23026 			if (conn_outgoing_ill != NULL)
23027 				ill_refrele(conn_outgoing_ill);
23028 			return;
23029 		}
23030 
23031 		if (CLASSD(dst)) {
23032 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
23033 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
23034 			    LENGTH);
23035 		}
23036 
23037 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23038 		    "ip_wput_ire_end: q %p (%S)",
23039 		    q, "last copy out");
23040 		IRE_REFRELE(ire);
23041 
23042 		if (multirt_send) {
23043 			ASSERT(ire1);
23044 			/*
23045 			 * Proceed with the next RTF_MULTIRT ire,
23046 			 * Also set up the send-to queue accordingly.
23047 			 */
23048 			ire = ire1;
23049 			ire1 = NULL;
23050 			stq = ire->ire_stq;
23051 			mp = next_mp;
23052 			next_mp = NULL;
23053 			ipha = (ipha_t *)mp->b_rptr;
23054 			ill_index = Q_TO_INDEX(stq);
23055 			ill = (ill_t *)stq->q_ptr;
23056 		}
23057 	} while (multirt_send);
23058 	if (conn_outgoing_ill != NULL)
23059 		ill_refrele(conn_outgoing_ill);
23060 	return;
23061 
23062 	/*
23063 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
23064 	 */
23065 broadcast:
23066 	{
23067 		/*
23068 		 * To avoid broadcast storms, we usually set the TTL to 1 for
23069 		 * broadcasts.  However, if SO_DONTROUTE isn't set, this value
23070 		 * can be overridden stack-wide through the ip_broadcast_ttl
23071 		 * ndd tunable, or on a per-connection basis through the
23072 		 * IP_BROADCAST_TTL socket option.
23073 		 *
23074 		 * In the event that we are replying to incoming ICMP packets,
23075 		 * connp could be NULL.
23076 		 */
23077 		ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
23078 		if (connp != NULL) {
23079 			if (connp->conn_dontroute)
23080 				ipha->ipha_ttl = 1;
23081 			else if (connp->conn_broadcast_ttl != 0)
23082 				ipha->ipha_ttl = connp->conn_broadcast_ttl;
23083 		}
23084 
23085 		/*
23086 		 * Note that we are not doing a IRB_REFHOLD here.
23087 		 * Actually we don't care if the list changes i.e
23088 		 * if somebody deletes an IRE from the list while
23089 		 * we drop the lock, the next time we come around
23090 		 * ire_next will be NULL and hence we won't send
23091 		 * out multiple copies which is fine.
23092 		 */
23093 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
23094 		ire1 = ire->ire_next;
23095 		if (conn_outgoing_ill != NULL) {
23096 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
23097 				ASSERT(ire1 == ire->ire_next);
23098 				if (ire1 != NULL && ire1->ire_addr == dst) {
23099 					ire_refrele(ire);
23100 					ire = ire1;
23101 					IRE_REFHOLD(ire);
23102 					ire1 = ire->ire_next;
23103 					continue;
23104 				}
23105 				rw_exit(&ire->ire_bucket->irb_lock);
23106 				/* Did not find a matching ill */
23107 				ip1dbg(("ip_wput_ire: broadcast with no "
23108 				    "matching IP_BOUND_IF ill %s dst %x\n",
23109 				    conn_outgoing_ill->ill_name, dst));
23110 				freemsg(first_mp);
23111 				if (ire != NULL)
23112 					ire_refrele(ire);
23113 				ill_refrele(conn_outgoing_ill);
23114 				return;
23115 			}
23116 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
23117 			/*
23118 			 * If the next IRE has the same address and is not one
23119 			 * of the two copies that we need to send, try to see
23120 			 * whether this copy should be sent at all. This
23121 			 * assumes that we insert loopbacks first and then
23122 			 * non-loopbacks. This is acheived by inserting the
23123 			 * loopback always before non-loopback.
23124 			 * This is used to send a single copy of a broadcast
23125 			 * packet out all physical interfaces that have an
23126 			 * matching IRE_BROADCAST while also looping
23127 			 * back one copy (to ip_wput_local) for each
23128 			 * matching physical interface. However, we avoid
23129 			 * sending packets out different logical that match by
23130 			 * having ipif_up/ipif_down supress duplicate
23131 			 * IRE_BROADCASTS.
23132 			 *
23133 			 * This feature is currently used to get broadcasts
23134 			 * sent to multiple interfaces, when the broadcast
23135 			 * address being used applies to multiple interfaces.
23136 			 * For example, a whole net broadcast will be
23137 			 * replicated on every connected subnet of
23138 			 * the target net.
23139 			 *
23140 			 * Each zone has its own set of IRE_BROADCASTs, so that
23141 			 * we're able to distribute inbound packets to multiple
23142 			 * zones who share a broadcast address. We avoid looping
23143 			 * back outbound packets in different zones but on the
23144 			 * same ill, as the application would see duplicates.
23145 			 *
23146 			 * If the interfaces are part of the same group,
23147 			 * we would want to send only one copy out for
23148 			 * whole group.
23149 			 *
23150 			 * This logic assumes that ire_add_v4() groups the
23151 			 * IRE_BROADCAST entries so that those with the same
23152 			 * ire_addr and ill_group are kept together.
23153 			 */
23154 			ire_ill = ire->ire_ipif->ipif_ill;
23155 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
23156 				if (ire_ill->ill_group != NULL &&
23157 				    (ire->ire_marks & IRE_MARK_NORECV)) {
23158 					/*
23159 					 * If the current zone only has an ire
23160 					 * broadcast for this address marked
23161 					 * NORECV, the ire we want is ahead in
23162 					 * the bucket, so we look it up
23163 					 * deliberately ignoring the zoneid.
23164 					 */
23165 					for (ire1 = ire->ire_bucket->irb_ire;
23166 					    ire1 != NULL;
23167 					    ire1 = ire1->ire_next) {
23168 						ire1_ill =
23169 						    ire1->ire_ipif->ipif_ill;
23170 						if (ire1->ire_addr != dst)
23171 							continue;
23172 						/* skip over the current ire */
23173 						if (ire1 == ire)
23174 							continue;
23175 						/* skip over deleted ires */
23176 						if (ire1->ire_marks &
23177 						    IRE_MARK_CONDEMNED)
23178 							continue;
23179 						/*
23180 						 * non-loopback ire in our
23181 						 * group: use it for the next
23182 						 * pass in the loop
23183 						 */
23184 						if (ire1->ire_stq != NULL &&
23185 						    ire1_ill->ill_group ==
23186 						    ire_ill->ill_group)
23187 							break;
23188 					}
23189 				}
23190 			} else {
23191 				while (ire1 != NULL && ire1->ire_addr == dst) {
23192 					ire1_ill = ire1->ire_ipif->ipif_ill;
23193 					/*
23194 					 * We can have two broadcast ires on the
23195 					 * same ill in different zones; here
23196 					 * we'll send a copy of the packet on
23197 					 * each ill and the fanout code will
23198 					 * call conn_wantpacket() to check that
23199 					 * the zone has the broadcast address
23200 					 * configured on the ill. If the two
23201 					 * ires are in the same group we only
23202 					 * send one copy up.
23203 					 */
23204 					if (ire1_ill != ire_ill &&
23205 					    (ire1_ill->ill_group == NULL ||
23206 					    ire_ill->ill_group == NULL ||
23207 					    ire1_ill->ill_group !=
23208 					    ire_ill->ill_group)) {
23209 						break;
23210 					}
23211 					ire1 = ire1->ire_next;
23212 				}
23213 			}
23214 		}
23215 		ASSERT(multirt_send == B_FALSE);
23216 		if (ire1 != NULL && ire1->ire_addr == dst) {
23217 			if ((ire->ire_flags & RTF_MULTIRT) &&
23218 			    (ire1->ire_flags & RTF_MULTIRT)) {
23219 				/*
23220 				 * We are in the multirouting case.
23221 				 * The message must be sent at least
23222 				 * on both ires. These ires have been
23223 				 * inserted AFTER the standard ones
23224 				 * in ip_rt_add(). There are thus no
23225 				 * other ire entries for the destination
23226 				 * address in the rest of the bucket
23227 				 * that do not have the RTF_MULTIRT
23228 				 * flag. We don't process a copy
23229 				 * of the message here. This will be
23230 				 * done in the final sending loop.
23231 				 */
23232 				multirt_send = B_TRUE;
23233 			} else {
23234 				next_mp = ip_copymsg(first_mp);
23235 				if (next_mp != NULL)
23236 					IRE_REFHOLD(ire1);
23237 			}
23238 		}
23239 		rw_exit(&ire->ire_bucket->irb_lock);
23240 	}
23241 
23242 	if (stq) {
23243 		/*
23244 		 * A non-NULL send-to queue means this packet is going
23245 		 * out of this machine.
23246 		 */
23247 		out_ill = (ill_t *)stq->q_ptr;
23248 
23249 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
23250 		ttl_protocol = ((uint16_t *)ipha)[4];
23251 		/*
23252 		 * We accumulate the pseudo header checksum in cksum.
23253 		 * This is pretty hairy code, so watch close.  One
23254 		 * thing to keep in mind is that UDP and TCP have
23255 		 * stored their respective datagram lengths in their
23256 		 * checksum fields.  This lines things up real nice.
23257 		 */
23258 		cksum = (dst >> 16) + (dst & 0xFFFF) +
23259 		    (src >> 16) + (src & 0xFFFF);
23260 		/*
23261 		 * We assume the udp checksum field contains the
23262 		 * length, so to compute the pseudo header checksum,
23263 		 * all we need is the protocol number and src/dst.
23264 		 */
23265 		/* Provide the checksums for UDP and TCP. */
23266 		if ((PROTO == IPPROTO_TCP) &&
23267 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
23268 			/* hlen gets the number of uchar_ts in the IP header */
23269 			hlen = (V_HLEN & 0xF) << 2;
23270 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
23271 			IP_STAT(ipst, ip_out_sw_cksum);
23272 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
23273 			    LENGTH - hlen);
23274 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
23275 		} else if (PROTO == IPPROTO_SCTP &&
23276 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
23277 			sctp_hdr_t	*sctph;
23278 
23279 			hlen = (V_HLEN & 0xF) << 2;
23280 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
23281 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
23282 			sctph->sh_chksum = 0;
23283 #ifdef	DEBUG
23284 			if (!skip_sctp_cksum)
23285 #endif
23286 				sctph->sh_chksum = sctp_cksum(mp, hlen);
23287 		} else {
23288 			queue_t	*dev_q = stq->q_next;
23289 
23290 			if (DEV_Q_FLOW_BLOCKED(dev_q)) {
23291 blocked:
23292 				ipha->ipha_ident = ip_hdr_included;
23293 				/*
23294 				 * If we don't have a conn to apply
23295 				 * backpressure, free the message.
23296 				 * In the ire_send path, we don't know
23297 				 * the position to requeue the packet. Rather
23298 				 * than reorder packets, we just drop this
23299 				 * packet.
23300 				 */
23301 				if (ipst->ips_ip_output_queue &&
23302 				    connp != NULL &&
23303 				    caller != IRE_SEND) {
23304 					if (caller == IP_WSRV) {
23305 						connp->conn_did_putbq = 1;
23306 						(void) putbq(connp->conn_wq,
23307 						    first_mp);
23308 						conn_drain_insert(connp);
23309 						/*
23310 						 * This is the service thread,
23311 						 * and the queue is already
23312 						 * noenabled. The check for
23313 						 * canput and the putbq is not
23314 						 * atomic. So we need to check
23315 						 * again.
23316 						 */
23317 						if (canput(stq->q_next))
23318 							connp->conn_did_putbq
23319 							    = 0;
23320 						IP_STAT(ipst, ip_conn_flputbq);
23321 					} else {
23322 						/*
23323 						 * We are not the service proc.
23324 						 * ip_wsrv will be scheduled or
23325 						 * is already running.
23326 						 */
23327 
23328 						(void) putq(connp->conn_wq,
23329 						    first_mp);
23330 					}
23331 				} else {
23332 					out_ill = (ill_t *)stq->q_ptr;
23333 					BUMP_MIB(out_ill->ill_ip_mib,
23334 					    ipIfStatsOutDiscards);
23335 					freemsg(first_mp);
23336 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23337 					    "ip_wput_ire_end: q %p (%S)",
23338 					    q, "discard");
23339 				}
23340 				ire_refrele(ire);
23341 				if (next_mp) {
23342 					ire_refrele(ire1);
23343 					freemsg(next_mp);
23344 				}
23345 				if (conn_outgoing_ill != NULL)
23346 					ill_refrele(conn_outgoing_ill);
23347 				return;
23348 			}
23349 			if ((PROTO == IPPROTO_UDP) &&
23350 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
23351 				/*
23352 				 * hlen gets the number of uchar_ts in the
23353 				 * IP header
23354 				 */
23355 				hlen = (V_HLEN & 0xF) << 2;
23356 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
23357 				max_frag = ire->ire_max_frag;
23358 				if (*up != 0) {
23359 					IP_CKSUM_XMIT(out_ill, ire, mp, ipha,
23360 					    up, PROTO, hlen, LENGTH, max_frag,
23361 					    ipsec_len, cksum);
23362 					/* Software checksum? */
23363 					if (DB_CKSUMFLAGS(mp) == 0) {
23364 						IP_STAT(ipst, ip_out_sw_cksum);
23365 						IP_STAT_UPDATE(ipst,
23366 						    ip_udp_out_sw_cksum_bytes,
23367 						    LENGTH - hlen);
23368 					}
23369 				}
23370 			}
23371 		}
23372 		/*
23373 		 * Need to do this even when fragmenting. The local
23374 		 * loopback can be done without computing checksums
23375 		 * but forwarding out other interface must be done
23376 		 * after the IP checksum (and ULP checksums) have been
23377 		 * computed.
23378 		 *
23379 		 * NOTE : multicast_forward is set only if this packet
23380 		 * originated from ip_wput. For packets originating from
23381 		 * ip_wput_multicast, it is not set.
23382 		 */
23383 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
23384 multi_loopback:
23385 			ip2dbg(("ip_wput: multicast, loop %d\n",
23386 			    conn_multicast_loop));
23387 
23388 			/*  Forget header checksum offload */
23389 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
23390 
23391 			/*
23392 			 * Local loopback of multicasts?  Check the
23393 			 * ill.
23394 			 *
23395 			 * Note that the loopback function will not come
23396 			 * in through ip_rput - it will only do the
23397 			 * client fanout thus we need to do an mforward
23398 			 * as well.  The is different from the BSD
23399 			 * logic.
23400 			 */
23401 			if (ill != NULL) {
23402 				ilm_t	*ilm;
23403 
23404 				ILM_WALKER_HOLD(ill);
23405 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
23406 				    ALL_ZONES);
23407 				ILM_WALKER_RELE(ill);
23408 				if (ilm != NULL) {
23409 					/*
23410 					 * Pass along the virtual output q.
23411 					 * ip_wput_local() will distribute the
23412 					 * packet to all the matching zones,
23413 					 * except the sending zone when
23414 					 * IP_MULTICAST_LOOP is false.
23415 					 */
23416 					ip_multicast_loopback(q, ill, first_mp,
23417 					    conn_multicast_loop ? 0 :
23418 					    IP_FF_NO_MCAST_LOOP, zoneid);
23419 				}
23420 			}
23421 			if (ipha->ipha_ttl == 0) {
23422 				/*
23423 				 * 0 => only to this host i.e. we are
23424 				 * done. We are also done if this was the
23425 				 * loopback interface since it is sufficient
23426 				 * to loopback one copy of a multicast packet.
23427 				 */
23428 				freemsg(first_mp);
23429 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23430 				    "ip_wput_ire_end: q %p (%S)",
23431 				    q, "loopback");
23432 				ire_refrele(ire);
23433 				if (conn_outgoing_ill != NULL)
23434 					ill_refrele(conn_outgoing_ill);
23435 				return;
23436 			}
23437 			/*
23438 			 * ILLF_MULTICAST is checked in ip_newroute
23439 			 * i.e. we don't need to check it here since
23440 			 * all IRE_CACHEs come from ip_newroute.
23441 			 * For multicast traffic, SO_DONTROUTE is interpreted
23442 			 * to mean only send the packet out the interface
23443 			 * (optionally specified with IP_MULTICAST_IF)
23444 			 * and do not forward it out additional interfaces.
23445 			 * RSVP and the rsvp daemon is an example of a
23446 			 * protocol and user level process that
23447 			 * handles it's own routing. Hence, it uses the
23448 			 * SO_DONTROUTE option to accomplish this.
23449 			 */
23450 
23451 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
23452 			    ill != NULL) {
23453 				/* Unconditionally redo the checksum */
23454 				ipha->ipha_hdr_checksum = 0;
23455 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23456 
23457 				/*
23458 				 * If this needs to go out secure, we need
23459 				 * to wait till we finish the IPsec
23460 				 * processing.
23461 				 */
23462 				if (ipsec_len == 0 &&
23463 				    ip_mforward(ill, ipha, mp)) {
23464 					freemsg(first_mp);
23465 					ip1dbg(("ip_wput: mforward failed\n"));
23466 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23467 					    "ip_wput_ire_end: q %p (%S)",
23468 					    q, "mforward failed");
23469 					ire_refrele(ire);
23470 					if (conn_outgoing_ill != NULL)
23471 						ill_refrele(conn_outgoing_ill);
23472 					return;
23473 				}
23474 			}
23475 		}
23476 		max_frag = ire->ire_max_frag;
23477 		cksum += ttl_protocol;
23478 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
23479 			/* No fragmentation required for this one. */
23480 			/*
23481 			 * Don't use frag_flag if packet is pre-built or source
23482 			 * routed or if multicast (since multicast packets do
23483 			 * not solicit ICMP "packet too big" messages).
23484 			 */
23485 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
23486 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
23487 			    !ip_source_route_included(ipha)) &&
23488 			    !CLASSD(ipha->ipha_dst))
23489 				ipha->ipha_fragment_offset_and_flags |=
23490 				    htons(ire->ire_frag_flag);
23491 
23492 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
23493 				/* Complete the IP header checksum. */
23494 				cksum += ipha->ipha_ident;
23495 				cksum += (v_hlen_tos_len >> 16)+
23496 				    (v_hlen_tos_len & 0xFFFF);
23497 				cksum += ipha->ipha_fragment_offset_and_flags;
23498 				hlen = (V_HLEN & 0xF) -
23499 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
23500 				if (hlen) {
23501 checksumoptions:
23502 					/*
23503 					 * Account for the IP Options in the IP
23504 					 * header checksum.
23505 					 */
23506 					up = (uint16_t *)(rptr+
23507 					    IP_SIMPLE_HDR_LENGTH);
23508 					do {
23509 						cksum += up[0];
23510 						cksum += up[1];
23511 						up += 2;
23512 					} while (--hlen);
23513 				}
23514 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
23515 				cksum = ~(cksum + (cksum >> 16));
23516 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
23517 			}
23518 			if (ipsec_len != 0) {
23519 				ipsec_out_process(q, first_mp, ire, ill_index);
23520 				if (!next_mp) {
23521 					ire_refrele(ire);
23522 					if (conn_outgoing_ill != NULL)
23523 						ill_refrele(conn_outgoing_ill);
23524 					return;
23525 				}
23526 				goto next;
23527 			}
23528 
23529 			/*
23530 			 * multirt_send has already been handled
23531 			 * for broadcast, but not yet for multicast
23532 			 * or IP options.
23533 			 */
23534 			if (next_mp == NULL) {
23535 				if (ire->ire_flags & RTF_MULTIRT) {
23536 					multirt_send = B_TRUE;
23537 				}
23538 			}
23539 
23540 			/*
23541 			 * In most cases, the emission loop below is
23542 			 * entered only once. Only in the case where
23543 			 * the ire holds the RTF_MULTIRT flag, do we loop
23544 			 * to process all RTF_MULTIRT ires in the bucket,
23545 			 * and send the packet through all crossed
23546 			 * RTF_MULTIRT routes.
23547 			 */
23548 			do {
23549 				if (multirt_send) {
23550 					irb_t *irb;
23551 
23552 					irb = ire->ire_bucket;
23553 					ASSERT(irb != NULL);
23554 					/*
23555 					 * We are in a multiple send case,
23556 					 * need to get the next IRE and make
23557 					 * a duplicate of the packet.
23558 					 */
23559 					IRB_REFHOLD(irb);
23560 					for (ire1 = ire->ire_next;
23561 					    ire1 != NULL;
23562 					    ire1 = ire1->ire_next) {
23563 						if (!(ire1->ire_flags &
23564 						    RTF_MULTIRT)) {
23565 							continue;
23566 						}
23567 						if (ire1->ire_addr !=
23568 						    ire->ire_addr) {
23569 							continue;
23570 						}
23571 						if (ire1->ire_marks &
23572 						    (IRE_MARK_CONDEMNED|
23573 						    IRE_MARK_HIDDEN)) {
23574 							continue;
23575 						}
23576 
23577 						/* Got one */
23578 						IRE_REFHOLD(ire1);
23579 						break;
23580 					}
23581 					IRB_REFRELE(irb);
23582 
23583 					if (ire1 != NULL) {
23584 						next_mp = copyb(mp);
23585 						if ((next_mp == NULL) ||
23586 						    ((mp->b_cont != NULL) &&
23587 						    ((next_mp->b_cont =
23588 						    dupmsg(mp->b_cont))
23589 						    == NULL))) {
23590 							freemsg(next_mp);
23591 							next_mp = NULL;
23592 							ire_refrele(ire1);
23593 							ire1 = NULL;
23594 						}
23595 					}
23596 
23597 					/*
23598 					 * Last multiroute ire; don't loop
23599 					 * anymore. The emission is over
23600 					 * and next_mp is NULL.
23601 					 */
23602 					if (ire1 == NULL) {
23603 						multirt_send = B_FALSE;
23604 					}
23605 				}
23606 
23607 				out_ill = ire_to_ill(ire);
23608 				DTRACE_PROBE4(ip4__physical__out__start,
23609 				    ill_t *, NULL,
23610 				    ill_t *, out_ill,
23611 				    ipha_t *, ipha, mblk_t *, mp);
23612 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23613 				    ipst->ips_ipv4firewall_physical_out,
23614 				    NULL, out_ill, ipha, mp, mp, 0, ipst);
23615 				DTRACE_PROBE1(ip4__physical__out__end,
23616 				    mblk_t *, mp);
23617 				if (mp == NULL)
23618 					goto release_ire_and_ill_2;
23619 
23620 				ASSERT(ipsec_len == 0);
23621 				mp->b_prev =
23622 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23623 				DTRACE_PROBE2(ip__xmit__2,
23624 				    mblk_t *, mp, ire_t *, ire);
23625 				pktxmit_state = ip_xmit_v4(mp, ire,
23626 				    NULL, B_TRUE, connp);
23627 				if ((pktxmit_state == SEND_FAILED) ||
23628 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23629 release_ire_and_ill_2:
23630 					if (next_mp) {
23631 						freemsg(next_mp);
23632 						ire_refrele(ire1);
23633 					}
23634 					ire_refrele(ire);
23635 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23636 					    "ip_wput_ire_end: q %p (%S)",
23637 					    q, "discard MDATA");
23638 					if (conn_outgoing_ill != NULL)
23639 						ill_refrele(conn_outgoing_ill);
23640 					return;
23641 				}
23642 
23643 				if (CLASSD(dst)) {
23644 					BUMP_MIB(out_ill->ill_ip_mib,
23645 					    ipIfStatsHCOutMcastPkts);
23646 					UPDATE_MIB(out_ill->ill_ip_mib,
23647 					    ipIfStatsHCOutMcastOctets,
23648 					    LENGTH);
23649 				} else if (ire->ire_type == IRE_BROADCAST) {
23650 					BUMP_MIB(out_ill->ill_ip_mib,
23651 					    ipIfStatsHCOutBcastPkts);
23652 				}
23653 
23654 				if (multirt_send) {
23655 					/*
23656 					 * We are in a multiple send case,
23657 					 * need to re-enter the sending loop
23658 					 * using the next ire.
23659 					 */
23660 					ire_refrele(ire);
23661 					ire = ire1;
23662 					stq = ire->ire_stq;
23663 					mp = next_mp;
23664 					next_mp = NULL;
23665 					ipha = (ipha_t *)mp->b_rptr;
23666 					ill_index = Q_TO_INDEX(stq);
23667 				}
23668 			} while (multirt_send);
23669 
23670 			if (!next_mp) {
23671 				/*
23672 				 * Last copy going out (the ultra-common
23673 				 * case).  Note that we intentionally replicate
23674 				 * the putnext rather than calling it before
23675 				 * the next_mp check in hopes of a little
23676 				 * tail-call action out of the compiler.
23677 				 */
23678 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23679 				    "ip_wput_ire_end: q %p (%S)",
23680 				    q, "last copy out(1)");
23681 				ire_refrele(ire);
23682 				if (conn_outgoing_ill != NULL)
23683 					ill_refrele(conn_outgoing_ill);
23684 				return;
23685 			}
23686 			/* More copies going out below. */
23687 		} else {
23688 			int offset;
23689 fragmentit:
23690 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23691 			/*
23692 			 * If this would generate a icmp_frag_needed message,
23693 			 * we need to handle it before we do the IPsec
23694 			 * processing. Otherwise, we need to strip the IPsec
23695 			 * headers before we send up the message to the ULPs
23696 			 * which becomes messy and difficult.
23697 			 */
23698 			if (ipsec_len != 0) {
23699 				if ((max_frag < (unsigned int)(LENGTH +
23700 				    ipsec_len)) && (offset & IPH_DF)) {
23701 					out_ill = (ill_t *)stq->q_ptr;
23702 					BUMP_MIB(out_ill->ill_ip_mib,
23703 					    ipIfStatsOutFragFails);
23704 					BUMP_MIB(out_ill->ill_ip_mib,
23705 					    ipIfStatsOutFragReqds);
23706 					ipha->ipha_hdr_checksum = 0;
23707 					ipha->ipha_hdr_checksum =
23708 					    (uint16_t)ip_csum_hdr(ipha);
23709 					icmp_frag_needed(ire->ire_stq, first_mp,
23710 					    max_frag, zoneid, ipst);
23711 					if (!next_mp) {
23712 						ire_refrele(ire);
23713 						if (conn_outgoing_ill != NULL) {
23714 							ill_refrele(
23715 							    conn_outgoing_ill);
23716 						}
23717 						return;
23718 					}
23719 				} else {
23720 					/*
23721 					 * This won't cause a icmp_frag_needed
23722 					 * message. to be generated. Send it on
23723 					 * the wire. Note that this could still
23724 					 * cause fragmentation and all we
23725 					 * do is the generation of the message
23726 					 * to the ULP if needed before IPsec.
23727 					 */
23728 					if (!next_mp) {
23729 						ipsec_out_process(q, first_mp,
23730 						    ire, ill_index);
23731 						TRACE_2(TR_FAC_IP,
23732 						    TR_IP_WPUT_IRE_END,
23733 						    "ip_wput_ire_end: q %p "
23734 						    "(%S)", q,
23735 						    "last ipsec_out_process");
23736 						ire_refrele(ire);
23737 						if (conn_outgoing_ill != NULL) {
23738 							ill_refrele(
23739 							    conn_outgoing_ill);
23740 						}
23741 						return;
23742 					}
23743 					ipsec_out_process(q, first_mp,
23744 					    ire, ill_index);
23745 				}
23746 			} else {
23747 				/*
23748 				 * Initiate IPPF processing. For
23749 				 * fragmentable packets we finish
23750 				 * all QOS packet processing before
23751 				 * calling:
23752 				 * ip_wput_ire_fragmentit->ip_wput_frag
23753 				 */
23754 
23755 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23756 					ip_process(IPP_LOCAL_OUT, &mp,
23757 					    ill_index);
23758 					if (mp == NULL) {
23759 						out_ill = (ill_t *)stq->q_ptr;
23760 						BUMP_MIB(out_ill->ill_ip_mib,
23761 						    ipIfStatsOutDiscards);
23762 						if (next_mp != NULL) {
23763 							freemsg(next_mp);
23764 							ire_refrele(ire1);
23765 						}
23766 						ire_refrele(ire);
23767 						TRACE_2(TR_FAC_IP,
23768 						    TR_IP_WPUT_IRE_END,
23769 						    "ip_wput_ire: q %p (%S)",
23770 						    q, "discard MDATA");
23771 						if (conn_outgoing_ill != NULL) {
23772 							ill_refrele(
23773 							    conn_outgoing_ill);
23774 						}
23775 						return;
23776 					}
23777 				}
23778 				if (!next_mp) {
23779 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23780 					    "ip_wput_ire_end: q %p (%S)",
23781 					    q, "last fragmentation");
23782 					ip_wput_ire_fragmentit(mp, ire,
23783 					    zoneid, ipst, connp);
23784 					ire_refrele(ire);
23785 					if (conn_outgoing_ill != NULL)
23786 						ill_refrele(conn_outgoing_ill);
23787 					return;
23788 				}
23789 				ip_wput_ire_fragmentit(mp, ire,
23790 				    zoneid, ipst, connp);
23791 			}
23792 		}
23793 	} else {
23794 nullstq:
23795 		/* A NULL stq means the destination address is local. */
23796 		UPDATE_OB_PKT_COUNT(ire);
23797 		ire->ire_last_used_time = lbolt;
23798 		ASSERT(ire->ire_ipif != NULL);
23799 		if (!next_mp) {
23800 			/*
23801 			 * Is there an "in" and "out" for traffic local
23802 			 * to a host (loopback)?  The code in Solaris doesn't
23803 			 * explicitly draw a line in its code for in vs out,
23804 			 * so we've had to draw a line in the sand: ip_wput_ire
23805 			 * is considered to be the "output" side and
23806 			 * ip_wput_local to be the "input" side.
23807 			 */
23808 			out_ill = ire_to_ill(ire);
23809 
23810 			/*
23811 			 * DTrace this as ip:::send.  A blocked packet will
23812 			 * fire the send probe, but not the receive probe.
23813 			 */
23814 			DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23815 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23816 			    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23817 
23818 			DTRACE_PROBE4(ip4__loopback__out__start,
23819 			    ill_t *, NULL, ill_t *, out_ill,
23820 			    ipha_t *, ipha, mblk_t *, first_mp);
23821 
23822 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23823 			    ipst->ips_ipv4firewall_loopback_out,
23824 			    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23825 
23826 			DTRACE_PROBE1(ip4__loopback__out_end,
23827 			    mblk_t *, first_mp);
23828 
23829 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23830 			    "ip_wput_ire_end: q %p (%S)",
23831 			    q, "local address");
23832 
23833 			if (first_mp != NULL)
23834 				ip_wput_local(q, out_ill, ipha,
23835 				    first_mp, ire, 0, ire->ire_zoneid);
23836 			ire_refrele(ire);
23837 			if (conn_outgoing_ill != NULL)
23838 				ill_refrele(conn_outgoing_ill);
23839 			return;
23840 		}
23841 
23842 		out_ill = ire_to_ill(ire);
23843 
23844 		/*
23845 		 * DTrace this as ip:::send.  A blocked packet will fire the
23846 		 * send probe, but not the receive probe.
23847 		 */
23848 		DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23849 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23850 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23851 
23852 		DTRACE_PROBE4(ip4__loopback__out__start,
23853 		    ill_t *, NULL, ill_t *, out_ill,
23854 		    ipha_t *, ipha, mblk_t *, first_mp);
23855 
23856 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23857 		    ipst->ips_ipv4firewall_loopback_out,
23858 		    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23859 
23860 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23861 
23862 		if (first_mp != NULL)
23863 			ip_wput_local(q, out_ill, ipha,
23864 			    first_mp, ire, 0, ire->ire_zoneid);
23865 	}
23866 next:
23867 	/*
23868 	 * More copies going out to additional interfaces.
23869 	 * ire1 has already been held. We don't need the
23870 	 * "ire" anymore.
23871 	 */
23872 	ire_refrele(ire);
23873 	ire = ire1;
23874 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23875 	mp = next_mp;
23876 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23877 	ill = ire_to_ill(ire);
23878 	first_mp = mp;
23879 	if (ipsec_len != 0) {
23880 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23881 		mp = mp->b_cont;
23882 	}
23883 	dst = ire->ire_addr;
23884 	ipha = (ipha_t *)mp->b_rptr;
23885 	/*
23886 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23887 	 * Restore ipha_ident "no checksum" flag.
23888 	 */
23889 	src = orig_src;
23890 	ipha->ipha_ident = ip_hdr_included;
23891 	goto another;
23892 
23893 #undef	rptr
23894 #undef	Q_TO_INDEX
23895 }
23896 
23897 /*
23898  * Routine to allocate a message that is used to notify the ULP about MDT.
23899  * The caller may provide a pointer to the link-layer MDT capabilities,
23900  * or NULL if MDT is to be disabled on the stream.
23901  */
23902 mblk_t *
23903 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23904 {
23905 	mblk_t *mp;
23906 	ip_mdt_info_t *mdti;
23907 	ill_mdt_capab_t *idst;
23908 
23909 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23910 		DB_TYPE(mp) = M_CTL;
23911 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23912 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23913 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23914 		idst = &(mdti->mdt_capab);
23915 
23916 		/*
23917 		 * If the caller provides us with the capability, copy
23918 		 * it over into our notification message; otherwise
23919 		 * we zero out the capability portion.
23920 		 */
23921 		if (isrc != NULL)
23922 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23923 		else
23924 			bzero((caddr_t)idst, sizeof (*idst));
23925 	}
23926 	return (mp);
23927 }
23928 
23929 /*
23930  * Routine which determines whether MDT can be enabled on the destination
23931  * IRE and IPC combination, and if so, allocates and returns the MDT
23932  * notification mblk that may be used by ULP.  We also check if we need to
23933  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23934  * MDT usage in the past have been lifted.  This gets called during IP
23935  * and ULP binding.
23936  */
23937 mblk_t *
23938 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23939     ill_mdt_capab_t *mdt_cap)
23940 {
23941 	mblk_t *mp;
23942 	boolean_t rc = B_FALSE;
23943 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23944 
23945 	ASSERT(dst_ire != NULL);
23946 	ASSERT(connp != NULL);
23947 	ASSERT(mdt_cap != NULL);
23948 
23949 	/*
23950 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23951 	 * Multidata, which is handled in tcp_multisend().  This
23952 	 * is the reason why we do all these checks here, to ensure
23953 	 * that we don't enable Multidata for the cases which we
23954 	 * can't handle at the moment.
23955 	 */
23956 	do {
23957 		/* Only do TCP at the moment */
23958 		if (connp->conn_ulp != IPPROTO_TCP)
23959 			break;
23960 
23961 		/*
23962 		 * IPsec outbound policy present?  Note that we get here
23963 		 * after calling ipsec_conn_cache_policy() where the global
23964 		 * policy checking is performed.  conn_latch will be
23965 		 * non-NULL as long as there's a policy defined,
23966 		 * i.e. conn_out_enforce_policy may be NULL in such case
23967 		 * when the connection is non-secure, and hence we check
23968 		 * further if the latch refers to an outbound policy.
23969 		 */
23970 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23971 			break;
23972 
23973 		/* CGTP (multiroute) is enabled? */
23974 		if (dst_ire->ire_flags & RTF_MULTIRT)
23975 			break;
23976 
23977 		/* Outbound IPQoS enabled? */
23978 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23979 			/*
23980 			 * In this case, we disable MDT for this and all
23981 			 * future connections going over the interface.
23982 			 */
23983 			mdt_cap->ill_mdt_on = 0;
23984 			break;
23985 		}
23986 
23987 		/* socket option(s) present? */
23988 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23989 			break;
23990 
23991 		rc = B_TRUE;
23992 	/* CONSTCOND */
23993 	} while (0);
23994 
23995 	/* Remember the result */
23996 	connp->conn_mdt_ok = rc;
23997 
23998 	if (!rc)
23999 		return (NULL);
24000 	else if (!mdt_cap->ill_mdt_on) {
24001 		/*
24002 		 * If MDT has been previously turned off in the past, and we
24003 		 * currently can do MDT (due to IPQoS policy removal, etc.)
24004 		 * then enable it for this interface.
24005 		 */
24006 		mdt_cap->ill_mdt_on = 1;
24007 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
24008 		    "interface %s\n", ill_name));
24009 	}
24010 
24011 	/* Allocate the MDT info mblk */
24012 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
24013 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
24014 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
24015 		return (NULL);
24016 	}
24017 	return (mp);
24018 }
24019 
24020 /*
24021  * Routine to allocate a message that is used to notify the ULP about LSO.
24022  * The caller may provide a pointer to the link-layer LSO capabilities,
24023  * or NULL if LSO is to be disabled on the stream.
24024  */
24025 mblk_t *
24026 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
24027 {
24028 	mblk_t *mp;
24029 	ip_lso_info_t *lsoi;
24030 	ill_lso_capab_t *idst;
24031 
24032 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
24033 		DB_TYPE(mp) = M_CTL;
24034 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
24035 		lsoi = (ip_lso_info_t *)mp->b_rptr;
24036 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
24037 		idst = &(lsoi->lso_capab);
24038 
24039 		/*
24040 		 * If the caller provides us with the capability, copy
24041 		 * it over into our notification message; otherwise
24042 		 * we zero out the capability portion.
24043 		 */
24044 		if (isrc != NULL)
24045 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
24046 		else
24047 			bzero((caddr_t)idst, sizeof (*idst));
24048 	}
24049 	return (mp);
24050 }
24051 
24052 /*
24053  * Routine which determines whether LSO can be enabled on the destination
24054  * IRE and IPC combination, and if so, allocates and returns the LSO
24055  * notification mblk that may be used by ULP.  We also check if we need to
24056  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
24057  * LSO usage in the past have been lifted.  This gets called during IP
24058  * and ULP binding.
24059  */
24060 mblk_t *
24061 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
24062     ill_lso_capab_t *lso_cap)
24063 {
24064 	mblk_t *mp;
24065 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
24066 
24067 	ASSERT(dst_ire != NULL);
24068 	ASSERT(connp != NULL);
24069 	ASSERT(lso_cap != NULL);
24070 
24071 	connp->conn_lso_ok = B_TRUE;
24072 
24073 	if ((connp->conn_ulp != IPPROTO_TCP) ||
24074 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
24075 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
24076 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
24077 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
24078 		connp->conn_lso_ok = B_FALSE;
24079 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
24080 			/*
24081 			 * Disable LSO for this and all future connections going
24082 			 * over the interface.
24083 			 */
24084 			lso_cap->ill_lso_on = 0;
24085 		}
24086 	}
24087 
24088 	if (!connp->conn_lso_ok)
24089 		return (NULL);
24090 	else if (!lso_cap->ill_lso_on) {
24091 		/*
24092 		 * If LSO has been previously turned off in the past, and we
24093 		 * currently can do LSO (due to IPQoS policy removal, etc.)
24094 		 * then enable it for this interface.
24095 		 */
24096 		lso_cap->ill_lso_on = 1;
24097 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
24098 		    ill_name));
24099 	}
24100 
24101 	/* Allocate the LSO info mblk */
24102 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
24103 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
24104 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
24105 
24106 	return (mp);
24107 }
24108 
24109 /*
24110  * Create destination address attribute, and fill it with the physical
24111  * destination address and SAP taken from the template DL_UNITDATA_REQ
24112  * message block.
24113  */
24114 boolean_t
24115 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
24116 {
24117 	dl_unitdata_req_t *dlurp;
24118 	pattr_t *pa;
24119 	pattrinfo_t pa_info;
24120 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
24121 	uint_t das_len, das_off;
24122 
24123 	ASSERT(dlmp != NULL);
24124 
24125 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
24126 	das_len = dlurp->dl_dest_addr_length;
24127 	das_off = dlurp->dl_dest_addr_offset;
24128 
24129 	pa_info.type = PATTR_DSTADDRSAP;
24130 	pa_info.len = sizeof (**das) + das_len - 1;
24131 
24132 	/* create and associate the attribute */
24133 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
24134 	if (pa != NULL) {
24135 		ASSERT(*das != NULL);
24136 		(*das)->addr_is_group = 0;
24137 		(*das)->addr_len = (uint8_t)das_len;
24138 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
24139 	}
24140 
24141 	return (pa != NULL);
24142 }
24143 
24144 /*
24145  * Create hardware checksum attribute and fill it with the values passed.
24146  */
24147 boolean_t
24148 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
24149     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
24150 {
24151 	pattr_t *pa;
24152 	pattrinfo_t pa_info;
24153 
24154 	ASSERT(mmd != NULL);
24155 
24156 	pa_info.type = PATTR_HCKSUM;
24157 	pa_info.len = sizeof (pattr_hcksum_t);
24158 
24159 	/* create and associate the attribute */
24160 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
24161 	if (pa != NULL) {
24162 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
24163 
24164 		hck->hcksum_start_offset = start_offset;
24165 		hck->hcksum_stuff_offset = stuff_offset;
24166 		hck->hcksum_end_offset = end_offset;
24167 		hck->hcksum_flags = flags;
24168 	}
24169 	return (pa != NULL);
24170 }
24171 
24172 /*
24173  * Create zerocopy attribute and fill it with the specified flags
24174  */
24175 boolean_t
24176 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
24177 {
24178 	pattr_t *pa;
24179 	pattrinfo_t pa_info;
24180 
24181 	ASSERT(mmd != NULL);
24182 	pa_info.type = PATTR_ZCOPY;
24183 	pa_info.len = sizeof (pattr_zcopy_t);
24184 
24185 	/* create and associate the attribute */
24186 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
24187 	if (pa != NULL) {
24188 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
24189 
24190 		zcopy->zcopy_flags = flags;
24191 	}
24192 	return (pa != NULL);
24193 }
24194 
24195 /*
24196  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
24197  * block chain. We could rewrite to handle arbitrary message block chains but
24198  * that would make the code complicated and slow. Right now there three
24199  * restrictions:
24200  *
24201  *   1. The first message block must contain the complete IP header and
24202  *	at least 1 byte of payload data.
24203  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
24204  *	so that we can use a single Multidata message.
24205  *   3. No frag must be distributed over two or more message blocks so
24206  *	that we don't need more than two packet descriptors per frag.
24207  *
24208  * The above restrictions allow us to support userland applications (which
24209  * will send down a single message block) and NFS over UDP (which will
24210  * send down a chain of at most three message blocks).
24211  *
24212  * We also don't use MDT for payloads with less than or equal to
24213  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
24214  */
24215 boolean_t
24216 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
24217 {
24218 	int	blocks;
24219 	ssize_t	total, missing, size;
24220 
24221 	ASSERT(mp != NULL);
24222 	ASSERT(hdr_len > 0);
24223 
24224 	size = MBLKL(mp) - hdr_len;
24225 	if (size <= 0)
24226 		return (B_FALSE);
24227 
24228 	/* The first mblk contains the header and some payload. */
24229 	blocks = 1;
24230 	total = size;
24231 	size %= len;
24232 	missing = (size == 0) ? 0 : (len - size);
24233 	mp = mp->b_cont;
24234 
24235 	while (mp != NULL) {
24236 		/*
24237 		 * Give up if we encounter a zero length message block.
24238 		 * In practice, this should rarely happen and therefore
24239 		 * not worth the trouble of freeing and re-linking the
24240 		 * mblk from the chain to handle such case.
24241 		 */
24242 		if ((size = MBLKL(mp)) == 0)
24243 			return (B_FALSE);
24244 
24245 		/* Too many payload buffers for a single Multidata message? */
24246 		if (++blocks > MULTIDATA_MAX_PBUFS)
24247 			return (B_FALSE);
24248 
24249 		total += size;
24250 		/* Is a frag distributed over two or more message blocks? */
24251 		if (missing > size)
24252 			return (B_FALSE);
24253 		size -= missing;
24254 
24255 		size %= len;
24256 		missing = (size == 0) ? 0 : (len - size);
24257 
24258 		mp = mp->b_cont;
24259 	}
24260 
24261 	return (total > ip_wput_frag_mdt_min);
24262 }
24263 
24264 /*
24265  * Outbound IPv4 fragmentation routine using MDT.
24266  */
24267 static void
24268 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
24269     uint32_t frag_flag, int offset)
24270 {
24271 	ipha_t		*ipha_orig;
24272 	int		i1, ip_data_end;
24273 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
24274 	mblk_t		*hdr_mp, *md_mp = NULL;
24275 	unsigned char	*hdr_ptr, *pld_ptr;
24276 	multidata_t	*mmd;
24277 	ip_pdescinfo_t	pdi;
24278 	ill_t		*ill;
24279 	ip_stack_t	*ipst = ire->ire_ipst;
24280 
24281 	ASSERT(DB_TYPE(mp) == M_DATA);
24282 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
24283 
24284 	ill = ire_to_ill(ire);
24285 	ASSERT(ill != NULL);
24286 
24287 	ipha_orig = (ipha_t *)mp->b_rptr;
24288 	mp->b_rptr += sizeof (ipha_t);
24289 
24290 	/* Calculate how many packets we will send out */
24291 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
24292 	pkts = (i1 + len - 1) / len;
24293 	ASSERT(pkts > 1);
24294 
24295 	/* Allocate a message block which will hold all the IP Headers. */
24296 	wroff = ipst->ips_ip_wroff_extra;
24297 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
24298 
24299 	i1 = pkts * hdr_chunk_len;
24300 	/*
24301 	 * Create the header buffer, Multidata and destination address
24302 	 * and SAP attribute that should be associated with it.
24303 	 */
24304 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
24305 	    ((hdr_mp->b_wptr += i1),
24306 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
24307 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
24308 		freemsg(mp);
24309 		if (md_mp == NULL) {
24310 			freemsg(hdr_mp);
24311 		} else {
24312 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
24313 			freemsg(md_mp);
24314 		}
24315 		IP_STAT(ipst, ip_frag_mdt_allocfail);
24316 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
24317 		return;
24318 	}
24319 	IP_STAT(ipst, ip_frag_mdt_allocd);
24320 
24321 	/*
24322 	 * Add a payload buffer to the Multidata; this operation must not
24323 	 * fail, or otherwise our logic in this routine is broken.  There
24324 	 * is no memory allocation done by the routine, so any returned
24325 	 * failure simply tells us that we've done something wrong.
24326 	 *
24327 	 * A failure tells us that either we're adding the same payload
24328 	 * buffer more than once, or we're trying to add more buffers than
24329 	 * allowed.  None of the above cases should happen, and we panic
24330 	 * because either there's horrible heap corruption, and/or
24331 	 * programming mistake.
24332 	 */
24333 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24334 		goto pbuf_panic;
24335 
24336 	hdr_ptr = hdr_mp->b_rptr;
24337 	pld_ptr = mp->b_rptr;
24338 
24339 	/* Establish the ending byte offset, based on the starting offset. */
24340 	offset <<= 3;
24341 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
24342 	    IP_SIMPLE_HDR_LENGTH;
24343 
24344 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
24345 
24346 	while (pld_ptr < mp->b_wptr) {
24347 		ipha_t		*ipha;
24348 		uint16_t	offset_and_flags;
24349 		uint16_t	ip_len;
24350 		int		error;
24351 
24352 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
24353 		ipha = (ipha_t *)(hdr_ptr + wroff);
24354 		ASSERT(OK_32PTR(ipha));
24355 		*ipha = *ipha_orig;
24356 
24357 		if (ip_data_end - offset > len) {
24358 			offset_and_flags = IPH_MF;
24359 		} else {
24360 			/*
24361 			 * Last frag. Set len to the length of this last piece.
24362 			 */
24363 			len = ip_data_end - offset;
24364 			/* A frag of a frag might have IPH_MF non-zero */
24365 			offset_and_flags =
24366 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24367 			    IPH_MF;
24368 		}
24369 		offset_and_flags |= (uint16_t)(offset >> 3);
24370 		offset_and_flags |= (uint16_t)frag_flag;
24371 		/* Store the offset and flags in the IP header. */
24372 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24373 
24374 		/* Store the length in the IP header. */
24375 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
24376 		ipha->ipha_length = htons(ip_len);
24377 
24378 		/*
24379 		 * Set the IP header checksum.  Note that mp is just
24380 		 * the header, so this is easy to pass to ip_csum.
24381 		 */
24382 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24383 
24384 		DTRACE_IP7(send, mblk_t *, md_mp, conn_t *, NULL, void_ip_t *,
24385 		    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *,
24386 		    NULL, int, 0);
24387 
24388 		/*
24389 		 * Record offset and size of header and data of the next packet
24390 		 * in the multidata message.
24391 		 */
24392 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
24393 		PDESC_PLD_INIT(&pdi);
24394 		i1 = MIN(mp->b_wptr - pld_ptr, len);
24395 		ASSERT(i1 > 0);
24396 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
24397 		if (i1 == len) {
24398 			pld_ptr += len;
24399 		} else {
24400 			i1 = len - i1;
24401 			mp = mp->b_cont;
24402 			ASSERT(mp != NULL);
24403 			ASSERT(MBLKL(mp) >= i1);
24404 			/*
24405 			 * Attach the next payload message block to the
24406 			 * multidata message.
24407 			 */
24408 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24409 				goto pbuf_panic;
24410 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
24411 			pld_ptr = mp->b_rptr + i1;
24412 		}
24413 
24414 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
24415 		    KM_NOSLEEP)) == NULL) {
24416 			/*
24417 			 * Any failure other than ENOMEM indicates that we
24418 			 * have passed in invalid pdesc info or parameters
24419 			 * to mmd_addpdesc, which must not happen.
24420 			 *
24421 			 * EINVAL is a result of failure on boundary checks
24422 			 * against the pdesc info contents.  It should not
24423 			 * happen, and we panic because either there's
24424 			 * horrible heap corruption, and/or programming
24425 			 * mistake.
24426 			 */
24427 			if (error != ENOMEM) {
24428 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
24429 				    "pdesc logic error detected for "
24430 				    "mmd %p pinfo %p (%d)\n",
24431 				    (void *)mmd, (void *)&pdi, error);
24432 				/* NOTREACHED */
24433 			}
24434 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
24435 			/* Free unattached payload message blocks as well */
24436 			md_mp->b_cont = mp->b_cont;
24437 			goto free_mmd;
24438 		}
24439 
24440 		/* Advance fragment offset. */
24441 		offset += len;
24442 
24443 		/* Advance to location for next header in the buffer. */
24444 		hdr_ptr += hdr_chunk_len;
24445 
24446 		/* Did we reach the next payload message block? */
24447 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
24448 			mp = mp->b_cont;
24449 			/*
24450 			 * Attach the next message block with payload
24451 			 * data to the multidata message.
24452 			 */
24453 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24454 				goto pbuf_panic;
24455 			pld_ptr = mp->b_rptr;
24456 		}
24457 	}
24458 
24459 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
24460 	ASSERT(mp->b_wptr == pld_ptr);
24461 
24462 	/* Update IP statistics */
24463 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
24464 
24465 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
24466 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
24467 
24468 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
24469 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
24470 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
24471 
24472 	if (pkt_type == OB_PKT) {
24473 		ire->ire_ob_pkt_count += pkts;
24474 		if (ire->ire_ipif != NULL)
24475 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
24476 	} else {
24477 		/* The type is IB_PKT in the forwarding path. */
24478 		ire->ire_ib_pkt_count += pkts;
24479 		ASSERT(!IRE_IS_LOCAL(ire));
24480 		if (ire->ire_type & IRE_BROADCAST) {
24481 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
24482 		} else {
24483 			UPDATE_MIB(ill->ill_ip_mib,
24484 			    ipIfStatsHCOutForwDatagrams, pkts);
24485 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
24486 		}
24487 	}
24488 	ire->ire_last_used_time = lbolt;
24489 	/* Send it down */
24490 	putnext(ire->ire_stq, md_mp);
24491 	return;
24492 
24493 pbuf_panic:
24494 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
24495 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
24496 	    pbuf_idx);
24497 	/* NOTREACHED */
24498 }
24499 
24500 /*
24501  * Outbound IP fragmentation routine.
24502  *
24503  * NOTE : This routine does not ire_refrele the ire that is passed in
24504  * as the argument.
24505  */
24506 static void
24507 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
24508     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst, conn_t *connp)
24509 {
24510 	int		i1;
24511 	mblk_t		*ll_hdr_mp;
24512 	int 		ll_hdr_len;
24513 	int		hdr_len;
24514 	mblk_t		*hdr_mp;
24515 	ipha_t		*ipha;
24516 	int		ip_data_end;
24517 	int		len;
24518 	mblk_t		*mp = mp_orig, *mp1;
24519 	int		offset;
24520 	queue_t		*q;
24521 	uint32_t	v_hlen_tos_len;
24522 	mblk_t		*first_mp;
24523 	boolean_t	mctl_present;
24524 	ill_t		*ill;
24525 	ill_t		*out_ill;
24526 	mblk_t		*xmit_mp;
24527 	mblk_t		*carve_mp;
24528 	ire_t		*ire1 = NULL;
24529 	ire_t		*save_ire = NULL;
24530 	mblk_t  	*next_mp = NULL;
24531 	boolean_t	last_frag = B_FALSE;
24532 	boolean_t	multirt_send = B_FALSE;
24533 	ire_t		*first_ire = NULL;
24534 	irb_t		*irb = NULL;
24535 	mib2_ipIfStatsEntry_t *mibptr = NULL;
24536 
24537 	ill = ire_to_ill(ire);
24538 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
24539 
24540 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
24541 
24542 	if (max_frag == 0) {
24543 		ip1dbg(("ip_wput_frag: ire frag size is 0"
24544 		    " -  dropping packet\n"));
24545 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24546 		freemsg(mp);
24547 		return;
24548 	}
24549 
24550 	/*
24551 	 * IPsec does not allow hw accelerated packets to be fragmented
24552 	 * This check is made in ip_wput_ipsec_out prior to coming here
24553 	 * via ip_wput_ire_fragmentit.
24554 	 *
24555 	 * If at this point we have an ire whose ARP request has not
24556 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24557 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24558 	 * This packet and all fragmentable packets for this ire will
24559 	 * continue to get dropped while ire_nce->nce_state remains in
24560 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24561 	 * ND_REACHABLE, all subsquent large packets for this ire will
24562 	 * get fragemented and sent out by this function.
24563 	 */
24564 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24565 		/* If nce_state is ND_INITIAL, trigger ARP query */
24566 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
24567 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24568 		    " -  dropping packet\n"));
24569 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24570 		freemsg(mp);
24571 		return;
24572 	}
24573 
24574 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24575 	    "ip_wput_frag_start:");
24576 
24577 	if (mp->b_datap->db_type == M_CTL) {
24578 		first_mp = mp;
24579 		mp_orig = mp = mp->b_cont;
24580 		mctl_present = B_TRUE;
24581 	} else {
24582 		first_mp = mp;
24583 		mctl_present = B_FALSE;
24584 	}
24585 
24586 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24587 	ipha = (ipha_t *)mp->b_rptr;
24588 
24589 	/*
24590 	 * If the Don't Fragment flag is on, generate an ICMP destination
24591 	 * unreachable, fragmentation needed.
24592 	 */
24593 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24594 	if (offset & IPH_DF) {
24595 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24596 		if (is_system_labeled()) {
24597 			max_frag = tsol_pmtu_adjust(mp, ire->ire_max_frag,
24598 			    ire->ire_max_frag - max_frag, AF_INET);
24599 		}
24600 		/*
24601 		 * Need to compute hdr checksum if called from ip_wput_ire.
24602 		 * Note that ip_rput_forward verifies the checksum before
24603 		 * calling this routine so in that case this is a noop.
24604 		 */
24605 		ipha->ipha_hdr_checksum = 0;
24606 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24607 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24608 		    ipst);
24609 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24610 		    "ip_wput_frag_end:(%S)",
24611 		    "don't fragment");
24612 		return;
24613 	}
24614 	/*
24615 	 * Labeled systems adjust max_frag if they add a label
24616 	 * to send the correct path mtu.  We need the real mtu since we
24617 	 * are fragmenting the packet after label adjustment.
24618 	 */
24619 	if (is_system_labeled())
24620 		max_frag = ire->ire_max_frag;
24621 	if (mctl_present)
24622 		freeb(first_mp);
24623 	/*
24624 	 * Establish the starting offset.  May not be zero if we are fragging
24625 	 * a fragment that is being forwarded.
24626 	 */
24627 	offset = offset & IPH_OFFSET;
24628 
24629 	/* TODO why is this test needed? */
24630 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24631 	if (((max_frag - LENGTH) & ~7) < 8) {
24632 		/* TODO: notify ulp somehow */
24633 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24634 		freemsg(mp);
24635 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24636 		    "ip_wput_frag_end:(%S)",
24637 		    "len < 8");
24638 		return;
24639 	}
24640 
24641 	hdr_len = (V_HLEN & 0xF) << 2;
24642 
24643 	ipha->ipha_hdr_checksum = 0;
24644 
24645 	/*
24646 	 * Establish the number of bytes maximum per frag, after putting
24647 	 * in the header.
24648 	 */
24649 	len = (max_frag - hdr_len) & ~7;
24650 
24651 	/* Check if we can use MDT to send out the frags. */
24652 	ASSERT(!IRE_IS_LOCAL(ire));
24653 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24654 	    ipst->ips_ip_multidata_outbound &&
24655 	    !(ire->ire_flags & RTF_MULTIRT) &&
24656 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24657 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24658 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24659 		ASSERT(ill->ill_mdt_capab != NULL);
24660 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24661 			/*
24662 			 * If MDT has been previously turned off in the past,
24663 			 * and we currently can do MDT (due to IPQoS policy
24664 			 * removal, etc.) then enable it for this interface.
24665 			 */
24666 			ill->ill_mdt_capab->ill_mdt_on = 1;
24667 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24668 			    ill->ill_name));
24669 		}
24670 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24671 		    offset);
24672 		return;
24673 	}
24674 
24675 	/* Get a copy of the header for the trailing frags */
24676 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst);
24677 	if (!hdr_mp) {
24678 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24679 		freemsg(mp);
24680 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24681 		    "ip_wput_frag_end:(%S)",
24682 		    "couldn't copy hdr");
24683 		return;
24684 	}
24685 	if (DB_CRED(mp) != NULL)
24686 		mblk_setcred(hdr_mp, DB_CRED(mp));
24687 
24688 	/* Store the starting offset, with the MoreFrags flag. */
24689 	i1 = offset | IPH_MF | frag_flag;
24690 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24691 
24692 	/* Establish the ending byte offset, based on the starting offset. */
24693 	offset <<= 3;
24694 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24695 
24696 	/* Store the length of the first fragment in the IP header. */
24697 	i1 = len + hdr_len;
24698 	ASSERT(i1 <= IP_MAXPACKET);
24699 	ipha->ipha_length = htons((uint16_t)i1);
24700 
24701 	/*
24702 	 * Compute the IP header checksum for the first frag.  We have to
24703 	 * watch out that we stop at the end of the header.
24704 	 */
24705 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24706 
24707 	/*
24708 	 * Now carve off the first frag.  Note that this will include the
24709 	 * original IP header.
24710 	 */
24711 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24712 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24713 		freeb(hdr_mp);
24714 		freemsg(mp_orig);
24715 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24716 		    "ip_wput_frag_end:(%S)",
24717 		    "couldn't carve first");
24718 		return;
24719 	}
24720 
24721 	/*
24722 	 * Multirouting case. Each fragment is replicated
24723 	 * via all non-condemned RTF_MULTIRT routes
24724 	 * currently resolved.
24725 	 * We ensure that first_ire is the first RTF_MULTIRT
24726 	 * ire in the bucket.
24727 	 */
24728 	if (ire->ire_flags & RTF_MULTIRT) {
24729 		irb = ire->ire_bucket;
24730 		ASSERT(irb != NULL);
24731 
24732 		multirt_send = B_TRUE;
24733 
24734 		/* Make sure we do not omit any multiroute ire. */
24735 		IRB_REFHOLD(irb);
24736 		for (first_ire = irb->irb_ire;
24737 		    first_ire != NULL;
24738 		    first_ire = first_ire->ire_next) {
24739 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24740 			    (first_ire->ire_addr == ire->ire_addr) &&
24741 			    !(first_ire->ire_marks &
24742 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
24743 				break;
24744 			}
24745 		}
24746 
24747 		if (first_ire != NULL) {
24748 			if (first_ire != ire) {
24749 				IRE_REFHOLD(first_ire);
24750 				/*
24751 				 * Do not release the ire passed in
24752 				 * as the argument.
24753 				 */
24754 				ire = first_ire;
24755 			} else {
24756 				first_ire = NULL;
24757 			}
24758 		}
24759 		IRB_REFRELE(irb);
24760 
24761 		/*
24762 		 * Save the first ire; we will need to restore it
24763 		 * for the trailing frags.
24764 		 * We REFHOLD save_ire, as each iterated ire will be
24765 		 * REFRELEd.
24766 		 */
24767 		save_ire = ire;
24768 		IRE_REFHOLD(save_ire);
24769 	}
24770 
24771 	/*
24772 	 * First fragment emission loop.
24773 	 * In most cases, the emission loop below is entered only
24774 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24775 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24776 	 * bucket, and send the fragment through all crossed
24777 	 * RTF_MULTIRT routes.
24778 	 */
24779 	do {
24780 		if (ire->ire_flags & RTF_MULTIRT) {
24781 			/*
24782 			 * We are in a multiple send case, need to get
24783 			 * the next ire and make a copy of the packet.
24784 			 * ire1 holds here the next ire to process in the
24785 			 * bucket. If multirouting is expected,
24786 			 * any non-RTF_MULTIRT ire that has the
24787 			 * right destination address is ignored.
24788 			 *
24789 			 * We have to take into account the MTU of
24790 			 * each walked ire. max_frag is set by the
24791 			 * the caller and generally refers to
24792 			 * the primary ire entry. Here we ensure that
24793 			 * no route with a lower MTU will be used, as
24794 			 * fragments are carved once for all ires,
24795 			 * then replicated.
24796 			 */
24797 			ASSERT(irb != NULL);
24798 			IRB_REFHOLD(irb);
24799 			for (ire1 = ire->ire_next;
24800 			    ire1 != NULL;
24801 			    ire1 = ire1->ire_next) {
24802 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24803 					continue;
24804 				if (ire1->ire_addr != ire->ire_addr)
24805 					continue;
24806 				if (ire1->ire_marks &
24807 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
24808 					continue;
24809 				/*
24810 				 * Ensure we do not exceed the MTU
24811 				 * of the next route.
24812 				 */
24813 				if (ire1->ire_max_frag < max_frag) {
24814 					ip_multirt_bad_mtu(ire1, max_frag);
24815 					continue;
24816 				}
24817 
24818 				/* Got one. */
24819 				IRE_REFHOLD(ire1);
24820 				break;
24821 			}
24822 			IRB_REFRELE(irb);
24823 
24824 			if (ire1 != NULL) {
24825 				next_mp = copyb(mp);
24826 				if ((next_mp == NULL) ||
24827 				    ((mp->b_cont != NULL) &&
24828 				    ((next_mp->b_cont =
24829 				    dupmsg(mp->b_cont)) == NULL))) {
24830 					freemsg(next_mp);
24831 					next_mp = NULL;
24832 					ire_refrele(ire1);
24833 					ire1 = NULL;
24834 				}
24835 			}
24836 
24837 			/* Last multiroute ire; don't loop anymore. */
24838 			if (ire1 == NULL) {
24839 				multirt_send = B_FALSE;
24840 			}
24841 		}
24842 
24843 		ll_hdr_len = 0;
24844 		LOCK_IRE_FP_MP(ire);
24845 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24846 		if (ll_hdr_mp != NULL) {
24847 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24848 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24849 		} else {
24850 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24851 		}
24852 
24853 		/* If there is a transmit header, get a copy for this frag. */
24854 		/*
24855 		 * TODO: should check db_ref before calling ip_carve_mp since
24856 		 * it might give us a dup.
24857 		 */
24858 		if (!ll_hdr_mp) {
24859 			/* No xmit header. */
24860 			xmit_mp = mp;
24861 
24862 		/* We have a link-layer header that can fit in our mblk. */
24863 		} else if (mp->b_datap->db_ref == 1 &&
24864 		    ll_hdr_len != 0 &&
24865 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24866 			/* M_DATA fastpath */
24867 			mp->b_rptr -= ll_hdr_len;
24868 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24869 			xmit_mp = mp;
24870 
24871 		/* Corner case if copyb has failed */
24872 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24873 			UNLOCK_IRE_FP_MP(ire);
24874 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24875 			freeb(hdr_mp);
24876 			freemsg(mp);
24877 			freemsg(mp_orig);
24878 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24879 			    "ip_wput_frag_end:(%S)",
24880 			    "discard");
24881 
24882 			if (multirt_send) {
24883 				ASSERT(ire1);
24884 				ASSERT(next_mp);
24885 
24886 				freemsg(next_mp);
24887 				ire_refrele(ire1);
24888 			}
24889 			if (save_ire != NULL)
24890 				IRE_REFRELE(save_ire);
24891 
24892 			if (first_ire != NULL)
24893 				ire_refrele(first_ire);
24894 			return;
24895 
24896 		/*
24897 		 * Case of res_mp OR the fastpath mp can't fit
24898 		 * in the mblk
24899 		 */
24900 		} else {
24901 			xmit_mp->b_cont = mp;
24902 			if (DB_CRED(mp) != NULL)
24903 				mblk_setcred(xmit_mp, DB_CRED(mp));
24904 			/*
24905 			 * Get priority marking, if any.
24906 			 * We propagate the CoS marking from the
24907 			 * original packet that went to QoS processing
24908 			 * in ip_wput_ire to the newly carved mp.
24909 			 */
24910 			if (DB_TYPE(xmit_mp) == M_DATA)
24911 				xmit_mp->b_band = mp->b_band;
24912 		}
24913 		UNLOCK_IRE_FP_MP(ire);
24914 
24915 		q = ire->ire_stq;
24916 		out_ill = (ill_t *)q->q_ptr;
24917 
24918 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24919 
24920 		DTRACE_PROBE4(ip4__physical__out__start,
24921 		    ill_t *, NULL, ill_t *, out_ill,
24922 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24923 
24924 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24925 		    ipst->ips_ipv4firewall_physical_out,
24926 		    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24927 
24928 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24929 
24930 		if (xmit_mp != NULL) {
24931 			DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *, NULL,
24932 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
24933 			    ipha_t *, ipha, ip6_t *, NULL, int, 0);
24934 
24935 			ILL_SEND_TX(out_ill, ire, connp, xmit_mp, 0);
24936 
24937 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24938 			UPDATE_MIB(out_ill->ill_ip_mib,
24939 			    ipIfStatsHCOutOctets, i1);
24940 
24941 			if (pkt_type != OB_PKT) {
24942 				/*
24943 				 * Update the packet count and MIB stats
24944 				 * of trailing RTF_MULTIRT ires.
24945 				 */
24946 				UPDATE_OB_PKT_COUNT(ire);
24947 				BUMP_MIB(out_ill->ill_ip_mib,
24948 				    ipIfStatsOutFragReqds);
24949 			}
24950 		}
24951 
24952 		if (multirt_send) {
24953 			/*
24954 			 * We are in a multiple send case; look for
24955 			 * the next ire and re-enter the loop.
24956 			 */
24957 			ASSERT(ire1);
24958 			ASSERT(next_mp);
24959 			/* REFRELE the current ire before looping */
24960 			ire_refrele(ire);
24961 			ire = ire1;
24962 			ire1 = NULL;
24963 			mp = next_mp;
24964 			next_mp = NULL;
24965 		}
24966 	} while (multirt_send);
24967 
24968 	ASSERT(ire1 == NULL);
24969 
24970 	/* Restore the original ire; we need it for the trailing frags */
24971 	if (save_ire != NULL) {
24972 		/* REFRELE the last iterated ire */
24973 		ire_refrele(ire);
24974 		/* save_ire has been REFHOLDed */
24975 		ire = save_ire;
24976 		save_ire = NULL;
24977 		q = ire->ire_stq;
24978 	}
24979 
24980 	if (pkt_type == OB_PKT) {
24981 		UPDATE_OB_PKT_COUNT(ire);
24982 	} else {
24983 		out_ill = (ill_t *)q->q_ptr;
24984 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24985 		UPDATE_IB_PKT_COUNT(ire);
24986 	}
24987 
24988 	/* Advance the offset to the second frag starting point. */
24989 	offset += len;
24990 	/*
24991 	 * Update hdr_len from the copied header - there might be less options
24992 	 * in the later fragments.
24993 	 */
24994 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24995 	/* Loop until done. */
24996 	for (;;) {
24997 		uint16_t	offset_and_flags;
24998 		uint16_t	ip_len;
24999 
25000 		if (ip_data_end - offset > len) {
25001 			/*
25002 			 * Carve off the appropriate amount from the original
25003 			 * datagram.
25004 			 */
25005 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
25006 				mp = NULL;
25007 				break;
25008 			}
25009 			/*
25010 			 * More frags after this one.  Get another copy
25011 			 * of the header.
25012 			 */
25013 			if (carve_mp->b_datap->db_ref == 1 &&
25014 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
25015 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
25016 				/* Inline IP header */
25017 				carve_mp->b_rptr -= hdr_mp->b_wptr -
25018 				    hdr_mp->b_rptr;
25019 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
25020 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
25021 				mp = carve_mp;
25022 			} else {
25023 				if (!(mp = copyb(hdr_mp))) {
25024 					freemsg(carve_mp);
25025 					break;
25026 				}
25027 				/* Get priority marking, if any. */
25028 				mp->b_band = carve_mp->b_band;
25029 				mp->b_cont = carve_mp;
25030 			}
25031 			ipha = (ipha_t *)mp->b_rptr;
25032 			offset_and_flags = IPH_MF;
25033 		} else {
25034 			/*
25035 			 * Last frag.  Consume the header. Set len to
25036 			 * the length of this last piece.
25037 			 */
25038 			len = ip_data_end - offset;
25039 
25040 			/*
25041 			 * Carve off the appropriate amount from the original
25042 			 * datagram.
25043 			 */
25044 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
25045 				mp = NULL;
25046 				break;
25047 			}
25048 			if (carve_mp->b_datap->db_ref == 1 &&
25049 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
25050 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
25051 				/* Inline IP header */
25052 				carve_mp->b_rptr -= hdr_mp->b_wptr -
25053 				    hdr_mp->b_rptr;
25054 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
25055 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
25056 				mp = carve_mp;
25057 				freeb(hdr_mp);
25058 				hdr_mp = mp;
25059 			} else {
25060 				mp = hdr_mp;
25061 				/* Get priority marking, if any. */
25062 				mp->b_band = carve_mp->b_band;
25063 				mp->b_cont = carve_mp;
25064 			}
25065 			ipha = (ipha_t *)mp->b_rptr;
25066 			/* A frag of a frag might have IPH_MF non-zero */
25067 			offset_and_flags =
25068 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
25069 			    IPH_MF;
25070 		}
25071 		offset_and_flags |= (uint16_t)(offset >> 3);
25072 		offset_and_flags |= (uint16_t)frag_flag;
25073 		/* Store the offset and flags in the IP header. */
25074 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
25075 
25076 		/* Store the length in the IP header. */
25077 		ip_len = (uint16_t)(len + hdr_len);
25078 		ipha->ipha_length = htons(ip_len);
25079 
25080 		/*
25081 		 * Set the IP header checksum.	Note that mp is just
25082 		 * the header, so this is easy to pass to ip_csum.
25083 		 */
25084 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
25085 
25086 		/* Attach a transmit header, if any, and ship it. */
25087 		if (pkt_type == OB_PKT) {
25088 			UPDATE_OB_PKT_COUNT(ire);
25089 		} else {
25090 			out_ill = (ill_t *)q->q_ptr;
25091 			BUMP_MIB(out_ill->ill_ip_mib,
25092 			    ipIfStatsHCOutForwDatagrams);
25093 			UPDATE_IB_PKT_COUNT(ire);
25094 		}
25095 
25096 		if (ire->ire_flags & RTF_MULTIRT) {
25097 			irb = ire->ire_bucket;
25098 			ASSERT(irb != NULL);
25099 
25100 			multirt_send = B_TRUE;
25101 
25102 			/*
25103 			 * Save the original ire; we will need to restore it
25104 			 * for the tailing frags.
25105 			 */
25106 			save_ire = ire;
25107 			IRE_REFHOLD(save_ire);
25108 		}
25109 		/*
25110 		 * Emission loop for this fragment, similar
25111 		 * to what is done for the first fragment.
25112 		 */
25113 		do {
25114 			if (multirt_send) {
25115 				/*
25116 				 * We are in a multiple send case, need to get
25117 				 * the next ire and make a copy of the packet.
25118 				 */
25119 				ASSERT(irb != NULL);
25120 				IRB_REFHOLD(irb);
25121 				for (ire1 = ire->ire_next;
25122 				    ire1 != NULL;
25123 				    ire1 = ire1->ire_next) {
25124 					if (!(ire1->ire_flags & RTF_MULTIRT))
25125 						continue;
25126 					if (ire1->ire_addr != ire->ire_addr)
25127 						continue;
25128 					if (ire1->ire_marks &
25129 					    (IRE_MARK_CONDEMNED|
25130 					    IRE_MARK_HIDDEN)) {
25131 						continue;
25132 					}
25133 					/*
25134 					 * Ensure we do not exceed the MTU
25135 					 * of the next route.
25136 					 */
25137 					if (ire1->ire_max_frag < max_frag) {
25138 						ip_multirt_bad_mtu(ire1,
25139 						    max_frag);
25140 						continue;
25141 					}
25142 
25143 					/* Got one. */
25144 					IRE_REFHOLD(ire1);
25145 					break;
25146 				}
25147 				IRB_REFRELE(irb);
25148 
25149 				if (ire1 != NULL) {
25150 					next_mp = copyb(mp);
25151 					if ((next_mp == NULL) ||
25152 					    ((mp->b_cont != NULL) &&
25153 					    ((next_mp->b_cont =
25154 					    dupmsg(mp->b_cont)) == NULL))) {
25155 						freemsg(next_mp);
25156 						next_mp = NULL;
25157 						ire_refrele(ire1);
25158 						ire1 = NULL;
25159 					}
25160 				}
25161 
25162 				/* Last multiroute ire; don't loop anymore. */
25163 				if (ire1 == NULL) {
25164 					multirt_send = B_FALSE;
25165 				}
25166 			}
25167 
25168 			/* Update transmit header */
25169 			ll_hdr_len = 0;
25170 			LOCK_IRE_FP_MP(ire);
25171 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
25172 			if (ll_hdr_mp != NULL) {
25173 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
25174 				ll_hdr_len = MBLKL(ll_hdr_mp);
25175 			} else {
25176 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
25177 			}
25178 
25179 			if (!ll_hdr_mp) {
25180 				xmit_mp = mp;
25181 
25182 			/*
25183 			 * We have link-layer header that can fit in
25184 			 * our mblk.
25185 			 */
25186 			} else if (mp->b_datap->db_ref == 1 &&
25187 			    ll_hdr_len != 0 &&
25188 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
25189 				/* M_DATA fastpath */
25190 				mp->b_rptr -= ll_hdr_len;
25191 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
25192 				    ll_hdr_len);
25193 				xmit_mp = mp;
25194 
25195 			/*
25196 			 * Case of res_mp OR the fastpath mp can't fit
25197 			 * in the mblk
25198 			 */
25199 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
25200 				xmit_mp->b_cont = mp;
25201 				if (DB_CRED(mp) != NULL)
25202 					mblk_setcred(xmit_mp, DB_CRED(mp));
25203 				/* Get priority marking, if any. */
25204 				if (DB_TYPE(xmit_mp) == M_DATA)
25205 					xmit_mp->b_band = mp->b_band;
25206 
25207 			/* Corner case if copyb failed */
25208 			} else {
25209 				/*
25210 				 * Exit both the replication and
25211 				 * fragmentation loops.
25212 				 */
25213 				UNLOCK_IRE_FP_MP(ire);
25214 				goto drop_pkt;
25215 			}
25216 			UNLOCK_IRE_FP_MP(ire);
25217 
25218 			mp1 = mp;
25219 			out_ill = (ill_t *)q->q_ptr;
25220 
25221 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
25222 
25223 			DTRACE_PROBE4(ip4__physical__out__start,
25224 			    ill_t *, NULL, ill_t *, out_ill,
25225 			    ipha_t *, ipha, mblk_t *, xmit_mp);
25226 
25227 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
25228 			    ipst->ips_ipv4firewall_physical_out,
25229 			    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
25230 
25231 			DTRACE_PROBE1(ip4__physical__out__end,
25232 			    mblk_t *, xmit_mp);
25233 
25234 			if (mp != mp1 && hdr_mp == mp1)
25235 				hdr_mp = mp;
25236 			if (mp != mp1 && mp_orig == mp1)
25237 				mp_orig = mp;
25238 
25239 			if (xmit_mp != NULL) {
25240 				DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *,
25241 				    NULL, void_ip_t *, ipha,
25242 				    __dtrace_ipsr_ill_t *, out_ill, ipha_t *,
25243 				    ipha, ip6_t *, NULL, int, 0);
25244 
25245 				ILL_SEND_TX(out_ill, ire, connp, xmit_mp, 0);
25246 
25247 				BUMP_MIB(out_ill->ill_ip_mib,
25248 				    ipIfStatsHCOutTransmits);
25249 				UPDATE_MIB(out_ill->ill_ip_mib,
25250 				    ipIfStatsHCOutOctets, ip_len);
25251 
25252 				if (pkt_type != OB_PKT) {
25253 					/*
25254 					 * Update the packet count of trailing
25255 					 * RTF_MULTIRT ires.
25256 					 */
25257 					UPDATE_OB_PKT_COUNT(ire);
25258 				}
25259 			}
25260 
25261 			/* All done if we just consumed the hdr_mp. */
25262 			if (mp == hdr_mp) {
25263 				last_frag = B_TRUE;
25264 				BUMP_MIB(out_ill->ill_ip_mib,
25265 				    ipIfStatsOutFragOKs);
25266 			}
25267 
25268 			if (multirt_send) {
25269 				/*
25270 				 * We are in a multiple send case; look for
25271 				 * the next ire and re-enter the loop.
25272 				 */
25273 				ASSERT(ire1);
25274 				ASSERT(next_mp);
25275 				/* REFRELE the current ire before looping */
25276 				ire_refrele(ire);
25277 				ire = ire1;
25278 				ire1 = NULL;
25279 				q = ire->ire_stq;
25280 				mp = next_mp;
25281 				next_mp = NULL;
25282 			}
25283 		} while (multirt_send);
25284 		/*
25285 		 * Restore the original ire; we need it for the
25286 		 * trailing frags
25287 		 */
25288 		if (save_ire != NULL) {
25289 			ASSERT(ire1 == NULL);
25290 			/* REFRELE the last iterated ire */
25291 			ire_refrele(ire);
25292 			/* save_ire has been REFHOLDed */
25293 			ire = save_ire;
25294 			q = ire->ire_stq;
25295 			save_ire = NULL;
25296 		}
25297 
25298 		if (last_frag) {
25299 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
25300 			    "ip_wput_frag_end:(%S)",
25301 			    "consumed hdr_mp");
25302 
25303 			if (first_ire != NULL)
25304 				ire_refrele(first_ire);
25305 			return;
25306 		}
25307 		/* Otherwise, advance and loop. */
25308 		offset += len;
25309 	}
25310 
25311 drop_pkt:
25312 	/* Clean up following allocation failure. */
25313 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
25314 	freemsg(mp);
25315 	if (mp != hdr_mp)
25316 		freeb(hdr_mp);
25317 	if (mp != mp_orig)
25318 		freemsg(mp_orig);
25319 
25320 	if (save_ire != NULL)
25321 		IRE_REFRELE(save_ire);
25322 	if (first_ire != NULL)
25323 		ire_refrele(first_ire);
25324 
25325 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
25326 	    "ip_wput_frag_end:(%S)",
25327 	    "end--alloc failure");
25328 }
25329 
25330 /*
25331  * Copy the header plus those options which have the copy bit set
25332  */
25333 static mblk_t *
25334 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst)
25335 {
25336 	mblk_t	*mp;
25337 	uchar_t	*up;
25338 
25339 	/*
25340 	 * Quick check if we need to look for options without the copy bit
25341 	 * set
25342 	 */
25343 	mp = allocb(ipst->ips_ip_wroff_extra + hdr_len, BPRI_HI);
25344 	if (!mp)
25345 		return (mp);
25346 	mp->b_rptr += ipst->ips_ip_wroff_extra;
25347 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
25348 		bcopy(rptr, mp->b_rptr, hdr_len);
25349 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
25350 		return (mp);
25351 	}
25352 	up  = mp->b_rptr;
25353 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
25354 	up += IP_SIMPLE_HDR_LENGTH;
25355 	rptr += IP_SIMPLE_HDR_LENGTH;
25356 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
25357 	while (hdr_len > 0) {
25358 		uint32_t optval;
25359 		uint32_t optlen;
25360 
25361 		optval = *rptr;
25362 		if (optval == IPOPT_EOL)
25363 			break;
25364 		if (optval == IPOPT_NOP)
25365 			optlen = 1;
25366 		else
25367 			optlen = rptr[1];
25368 		if (optval & IPOPT_COPY) {
25369 			bcopy(rptr, up, optlen);
25370 			up += optlen;
25371 		}
25372 		rptr += optlen;
25373 		hdr_len -= optlen;
25374 	}
25375 	/*
25376 	 * Make sure that we drop an even number of words by filling
25377 	 * with EOL to the next word boundary.
25378 	 */
25379 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
25380 	    hdr_len & 0x3; hdr_len++)
25381 		*up++ = IPOPT_EOL;
25382 	mp->b_wptr = up;
25383 	/* Update header length */
25384 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
25385 	return (mp);
25386 }
25387 
25388 /*
25389  * Delivery to local recipients including fanout to multiple recipients.
25390  * Does not do checksumming of UDP/TCP.
25391  * Note: q should be the read side queue for either the ill or conn.
25392  * Note: rq should be the read side q for the lower (ill) stream.
25393  * We don't send packets to IPPF processing, thus the last argument
25394  * to all the fanout calls are B_FALSE.
25395  */
25396 void
25397 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
25398     int fanout_flags, zoneid_t zoneid)
25399 {
25400 	uint32_t	protocol;
25401 	mblk_t		*first_mp;
25402 	boolean_t	mctl_present;
25403 	int		ire_type;
25404 #define	rptr	((uchar_t *)ipha)
25405 	ip_stack_t	*ipst = ill->ill_ipst;
25406 
25407 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
25408 	    "ip_wput_local_start: q %p", q);
25409 
25410 	if (ire != NULL) {
25411 		ire_type = ire->ire_type;
25412 	} else {
25413 		/*
25414 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
25415 		 * packet is not multicast, we can't tell the ire type.
25416 		 */
25417 		ASSERT(CLASSD(ipha->ipha_dst));
25418 		ire_type = IRE_BROADCAST;
25419 	}
25420 
25421 	first_mp = mp;
25422 	if (first_mp->b_datap->db_type == M_CTL) {
25423 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
25424 		if (!io->ipsec_out_secure) {
25425 			/*
25426 			 * This ipsec_out_t was allocated in ip_wput
25427 			 * for multicast packets to store the ill_index.
25428 			 * As this is being delivered locally, we don't
25429 			 * need this anymore.
25430 			 */
25431 			mp = first_mp->b_cont;
25432 			freeb(first_mp);
25433 			first_mp = mp;
25434 			mctl_present = B_FALSE;
25435 		} else {
25436 			/*
25437 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
25438 			 * security properties for the looped-back packet.
25439 			 */
25440 			mctl_present = B_TRUE;
25441 			mp = first_mp->b_cont;
25442 			ASSERT(mp != NULL);
25443 			ipsec_out_to_in(first_mp);
25444 		}
25445 	} else {
25446 		mctl_present = B_FALSE;
25447 	}
25448 
25449 	DTRACE_PROBE4(ip4__loopback__in__start,
25450 	    ill_t *, ill, ill_t *, NULL,
25451 	    ipha_t *, ipha, mblk_t *, first_mp);
25452 
25453 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
25454 	    ipst->ips_ipv4firewall_loopback_in,
25455 	    ill, NULL, ipha, first_mp, mp, 0, ipst);
25456 
25457 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
25458 
25459 	if (first_mp == NULL)
25460 		return;
25461 
25462 	if (ipst->ips_ipobs_enabled) {
25463 		zoneid_t szone, dzone, lookup_zoneid = ALL_ZONES;
25464 		zoneid_t stackzoneid = netstackid_to_zoneid(
25465 		    ipst->ips_netstack->netstack_stackid);
25466 
25467 		dzone = (stackzoneid == GLOBAL_ZONEID) ? zoneid : stackzoneid;
25468 		/*
25469 		 * 127.0.0.1 is special, as we cannot lookup its zoneid by
25470 		 * address.  Restrict the lookup below to the destination zone.
25471 		 */
25472 		if (ipha->ipha_src == ntohl(INADDR_LOOPBACK))
25473 			lookup_zoneid = zoneid;
25474 		szone = ip_get_zoneid_v4(ipha->ipha_src, mp, ipst,
25475 		    lookup_zoneid);
25476 		ipobs_hook(mp, IPOBS_HOOK_LOCAL, szone, dzone, ill,
25477 		    IPV4_VERSION, 0, ipst);
25478 	}
25479 
25480 	DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL, void_ip_t *,
25481 	    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *, NULL,
25482 	    int, 1);
25483 
25484 	ipst->ips_loopback_packets++;
25485 
25486 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
25487 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
25488 	if (!IS_SIMPLE_IPH(ipha)) {
25489 		ip_wput_local_options(ipha, ipst);
25490 	}
25491 
25492 	protocol = ipha->ipha_protocol;
25493 	switch (protocol) {
25494 	case IPPROTO_ICMP: {
25495 		ire_t		*ire_zone;
25496 		ilm_t		*ilm;
25497 		mblk_t		*mp1;
25498 		zoneid_t	last_zoneid;
25499 
25500 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(ill)) {
25501 			ASSERT(ire_type == IRE_BROADCAST);
25502 			/*
25503 			 * In the multicast case, applications may have joined
25504 			 * the group from different zones, so we need to deliver
25505 			 * the packet to each of them. Loop through the
25506 			 * multicast memberships structures (ilm) on the receive
25507 			 * ill and send a copy of the packet up each matching
25508 			 * one. However, we don't do this for multicasts sent on
25509 			 * the loopback interface (PHYI_LOOPBACK flag set) as
25510 			 * they must stay in the sender's zone.
25511 			 *
25512 			 * ilm_add_v6() ensures that ilms in the same zone are
25513 			 * contiguous in the ill_ilm list. We use this property
25514 			 * to avoid sending duplicates needed when two
25515 			 * applications in the same zone join the same group on
25516 			 * different logical interfaces: we ignore the ilm if
25517 			 * it's zoneid is the same as the last matching one.
25518 			 * In addition, the sending of the packet for
25519 			 * ire_zoneid is delayed until all of the other ilms
25520 			 * have been exhausted.
25521 			 */
25522 			last_zoneid = -1;
25523 			ILM_WALKER_HOLD(ill);
25524 			for (ilm = ill->ill_ilm; ilm != NULL;
25525 			    ilm = ilm->ilm_next) {
25526 				if ((ilm->ilm_flags & ILM_DELETED) ||
25527 				    ipha->ipha_dst != ilm->ilm_addr ||
25528 				    ilm->ilm_zoneid == last_zoneid ||
25529 				    ilm->ilm_zoneid == zoneid ||
25530 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
25531 					continue;
25532 				mp1 = ip_copymsg(first_mp);
25533 				if (mp1 == NULL)
25534 					continue;
25535 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25536 				    mctl_present, B_FALSE, ill,
25537 				    ilm->ilm_zoneid);
25538 				last_zoneid = ilm->ilm_zoneid;
25539 			}
25540 			ILM_WALKER_RELE(ill);
25541 			/*
25542 			 * Loopback case: the sending endpoint has
25543 			 * IP_MULTICAST_LOOP disabled, therefore we don't
25544 			 * dispatch the multicast packet to the sending zone.
25545 			 */
25546 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
25547 				freemsg(first_mp);
25548 				return;
25549 			}
25550 		} else if (ire_type == IRE_BROADCAST) {
25551 			/*
25552 			 * In the broadcast case, there may be many zones
25553 			 * which need a copy of the packet delivered to them.
25554 			 * There is one IRE_BROADCAST per broadcast address
25555 			 * and per zone; we walk those using a helper function.
25556 			 * In addition, the sending of the packet for zoneid is
25557 			 * delayed until all of the other ires have been
25558 			 * processed.
25559 			 */
25560 			IRB_REFHOLD(ire->ire_bucket);
25561 			ire_zone = NULL;
25562 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25563 			    ire)) != NULL) {
25564 				mp1 = ip_copymsg(first_mp);
25565 				if (mp1 == NULL)
25566 					continue;
25567 
25568 				UPDATE_IB_PKT_COUNT(ire_zone);
25569 				ire_zone->ire_last_used_time = lbolt;
25570 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25571 				    mctl_present, B_FALSE, ill,
25572 				    ire_zone->ire_zoneid);
25573 			}
25574 			IRB_REFRELE(ire->ire_bucket);
25575 		}
25576 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25577 		    0, mctl_present, B_FALSE, ill, zoneid);
25578 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25579 		    "ip_wput_local_end: q %p (%S)",
25580 		    q, "icmp");
25581 		return;
25582 	}
25583 	case IPPROTO_IGMP:
25584 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25585 			/* Bad packet - discarded by igmp_input */
25586 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25587 			    "ip_wput_local_end: q %p (%S)",
25588 			    q, "igmp_input--bad packet");
25589 			if (mctl_present)
25590 				freeb(first_mp);
25591 			return;
25592 		}
25593 		/*
25594 		 * igmp_input() may have returned the pulled up message.
25595 		 * So first_mp and ipha need to be reinitialized.
25596 		 */
25597 		ipha = (ipha_t *)mp->b_rptr;
25598 		if (mctl_present)
25599 			first_mp->b_cont = mp;
25600 		else
25601 			first_mp = mp;
25602 		/* deliver to local raw users */
25603 		break;
25604 	case IPPROTO_ENCAP:
25605 		/*
25606 		 * This case is covered by either ip_fanout_proto, or by
25607 		 * the above security processing for self-tunneled packets.
25608 		 */
25609 		break;
25610 	case IPPROTO_UDP: {
25611 		uint16_t	*up;
25612 		uint32_t	ports;
25613 
25614 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25615 		    UDP_PORTS_OFFSET);
25616 		/* Force a 'valid' checksum. */
25617 		up[3] = 0;
25618 
25619 		ports = *(uint32_t *)up;
25620 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25621 		    (ire_type == IRE_BROADCAST),
25622 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25623 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25624 		    ill, zoneid);
25625 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25626 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25627 		return;
25628 	}
25629 	case IPPROTO_TCP: {
25630 
25631 		/*
25632 		 * For TCP, discard broadcast packets.
25633 		 */
25634 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25635 			freemsg(first_mp);
25636 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25637 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25638 			return;
25639 		}
25640 
25641 		if (mp->b_datap->db_type == M_DATA) {
25642 			/*
25643 			 * M_DATA mblk, so init mblk (chain) for no struio().
25644 			 */
25645 			mblk_t	*mp1 = mp;
25646 
25647 			do {
25648 				mp1->b_datap->db_struioflag = 0;
25649 			} while ((mp1 = mp1->b_cont) != NULL);
25650 		}
25651 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25652 		    <= mp->b_wptr);
25653 		ip_fanout_tcp(q, first_mp, ill, ipha,
25654 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25655 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25656 		    mctl_present, B_FALSE, zoneid);
25657 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25658 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25659 		return;
25660 	}
25661 	case IPPROTO_SCTP:
25662 	{
25663 		uint32_t	ports;
25664 
25665 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25666 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25667 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25668 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25669 		return;
25670 	}
25671 
25672 	default:
25673 		break;
25674 	}
25675 	/*
25676 	 * Find a client for some other protocol.  We give
25677 	 * copies to multiple clients, if more than one is
25678 	 * bound.
25679 	 */
25680 	ip_fanout_proto(q, first_mp, ill, ipha,
25681 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25682 	    mctl_present, B_FALSE, ill, zoneid);
25683 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25684 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25685 #undef	rptr
25686 }
25687 
25688 /*
25689  * Update any source route, record route, or timestamp options.
25690  * Check that we are at end of strict source route.
25691  * The options have been sanity checked by ip_wput_options().
25692  */
25693 static void
25694 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25695 {
25696 	ipoptp_t	opts;
25697 	uchar_t		*opt;
25698 	uint8_t		optval;
25699 	uint8_t		optlen;
25700 	ipaddr_t	dst;
25701 	uint32_t	ts;
25702 	ire_t		*ire;
25703 	timestruc_t	now;
25704 
25705 	ip2dbg(("ip_wput_local_options\n"));
25706 	for (optval = ipoptp_first(&opts, ipha);
25707 	    optval != IPOPT_EOL;
25708 	    optval = ipoptp_next(&opts)) {
25709 		opt = opts.ipoptp_cur;
25710 		optlen = opts.ipoptp_len;
25711 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25712 		switch (optval) {
25713 			uint32_t off;
25714 		case IPOPT_SSRR:
25715 		case IPOPT_LSRR:
25716 			off = opt[IPOPT_OFFSET];
25717 			off--;
25718 			if (optlen < IP_ADDR_LEN ||
25719 			    off > optlen - IP_ADDR_LEN) {
25720 				/* End of source route */
25721 				break;
25722 			}
25723 			/*
25724 			 * This will only happen if two consecutive entries
25725 			 * in the source route contains our address or if
25726 			 * it is a packet with a loose source route which
25727 			 * reaches us before consuming the whole source route
25728 			 */
25729 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25730 			if (optval == IPOPT_SSRR) {
25731 				return;
25732 			}
25733 			/*
25734 			 * Hack: instead of dropping the packet truncate the
25735 			 * source route to what has been used by filling the
25736 			 * rest with IPOPT_NOP.
25737 			 */
25738 			opt[IPOPT_OLEN] = (uint8_t)off;
25739 			while (off < optlen) {
25740 				opt[off++] = IPOPT_NOP;
25741 			}
25742 			break;
25743 		case IPOPT_RR:
25744 			off = opt[IPOPT_OFFSET];
25745 			off--;
25746 			if (optlen < IP_ADDR_LEN ||
25747 			    off > optlen - IP_ADDR_LEN) {
25748 				/* No more room - ignore */
25749 				ip1dbg((
25750 				    "ip_wput_forward_options: end of RR\n"));
25751 				break;
25752 			}
25753 			dst = htonl(INADDR_LOOPBACK);
25754 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25755 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25756 			break;
25757 		case IPOPT_TS:
25758 			/* Insert timestamp if there is romm */
25759 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25760 			case IPOPT_TS_TSONLY:
25761 				off = IPOPT_TS_TIMELEN;
25762 				break;
25763 			case IPOPT_TS_PRESPEC:
25764 			case IPOPT_TS_PRESPEC_RFC791:
25765 				/* Verify that the address matched */
25766 				off = opt[IPOPT_OFFSET] - 1;
25767 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25768 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25769 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25770 				    ipst);
25771 				if (ire == NULL) {
25772 					/* Not for us */
25773 					break;
25774 				}
25775 				ire_refrele(ire);
25776 				/* FALLTHRU */
25777 			case IPOPT_TS_TSANDADDR:
25778 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25779 				break;
25780 			default:
25781 				/*
25782 				 * ip_*put_options should have already
25783 				 * dropped this packet.
25784 				 */
25785 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25786 				    "unknown IT - bug in ip_wput_options?\n");
25787 				return;	/* Keep "lint" happy */
25788 			}
25789 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25790 				/* Increase overflow counter */
25791 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25792 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25793 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25794 				    (off << 4);
25795 				break;
25796 			}
25797 			off = opt[IPOPT_OFFSET] - 1;
25798 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25799 			case IPOPT_TS_PRESPEC:
25800 			case IPOPT_TS_PRESPEC_RFC791:
25801 			case IPOPT_TS_TSANDADDR:
25802 				dst = htonl(INADDR_LOOPBACK);
25803 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25804 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25805 				/* FALLTHRU */
25806 			case IPOPT_TS_TSONLY:
25807 				off = opt[IPOPT_OFFSET] - 1;
25808 				/* Compute # of milliseconds since midnight */
25809 				gethrestime(&now);
25810 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25811 				    now.tv_nsec / (NANOSEC / MILLISEC);
25812 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25813 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25814 				break;
25815 			}
25816 			break;
25817 		}
25818 	}
25819 }
25820 
25821 /*
25822  * Send out a multicast packet on interface ipif.
25823  * The sender does not have an conn.
25824  * Caller verifies that this isn't a PHYI_LOOPBACK.
25825  */
25826 void
25827 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25828 {
25829 	ipha_t	*ipha;
25830 	ire_t	*ire;
25831 	ipaddr_t	dst;
25832 	mblk_t		*first_mp;
25833 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25834 
25835 	/* igmp_sendpkt always allocates a ipsec_out_t */
25836 	ASSERT(mp->b_datap->db_type == M_CTL);
25837 	ASSERT(!ipif->ipif_isv6);
25838 	ASSERT(!IS_LOOPBACK(ipif->ipif_ill));
25839 
25840 	first_mp = mp;
25841 	mp = first_mp->b_cont;
25842 	ASSERT(mp->b_datap->db_type == M_DATA);
25843 	ipha = (ipha_t *)mp->b_rptr;
25844 
25845 	/*
25846 	 * Find an IRE which matches the destination and the outgoing
25847 	 * queue (i.e. the outgoing interface.)
25848 	 */
25849 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25850 		dst = ipif->ipif_pp_dst_addr;
25851 	else
25852 		dst = ipha->ipha_dst;
25853 	/*
25854 	 * The source address has already been initialized by the
25855 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25856 	 * be sufficient rather than MATCH_IRE_IPIF.
25857 	 *
25858 	 * This function is used for sending IGMP packets. We need
25859 	 * to make sure that we send the packet out of the interface
25860 	 * (ipif->ipif_ill) where we joined the group. This is to
25861 	 * prevent from switches doing IGMP snooping to send us multicast
25862 	 * packets for a given group on the interface we have joined.
25863 	 * If we can't find an ire, igmp_sendpkt has already initialized
25864 	 * ipsec_out_attach_if so that this will not be load spread in
25865 	 * ip_newroute_ipif.
25866 	 */
25867 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25868 	    MATCH_IRE_ILL, ipst);
25869 	if (!ire) {
25870 		/*
25871 		 * Mark this packet to make it be delivered to
25872 		 * ip_wput_ire after the new ire has been
25873 		 * created.
25874 		 */
25875 		mp->b_prev = NULL;
25876 		mp->b_next = NULL;
25877 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25878 		    zoneid, &zero_info);
25879 		return;
25880 	}
25881 
25882 	/*
25883 	 * Honor the RTF_SETSRC flag; this is the only case
25884 	 * where we force this addr whatever the current src addr is,
25885 	 * because this address is set by igmp_sendpkt(), and
25886 	 * cannot be specified by any user.
25887 	 */
25888 	if (ire->ire_flags & RTF_SETSRC) {
25889 		ipha->ipha_src = ire->ire_src_addr;
25890 	}
25891 
25892 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25893 }
25894 
25895 /*
25896  * NOTE : This function does not ire_refrele the ire argument passed in.
25897  *
25898  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25899  * failure. The nce_fp_mp can vanish any time in the case of
25900  * IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25901  * the ire_lock to access the nce_fp_mp in this case.
25902  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25903  * prepending a fastpath message IPQoS processing must precede it, we also set
25904  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25905  * (IPQoS might have set the b_band for CoS marking).
25906  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25907  * must follow it so that IPQoS can mark the dl_priority field for CoS
25908  * marking, if needed.
25909  */
25910 static mblk_t *
25911 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc,
25912     uint32_t ill_index, ipha_t **iphap)
25913 {
25914 	uint_t	hlen;
25915 	ipha_t *ipha;
25916 	mblk_t *mp1;
25917 	boolean_t qos_done = B_FALSE;
25918 	uchar_t	*ll_hdr;
25919 	ip_stack_t	*ipst = ire->ire_ipst;
25920 
25921 #define	rptr	((uchar_t *)ipha)
25922 
25923 	ipha = (ipha_t *)mp->b_rptr;
25924 	hlen = 0;
25925 	LOCK_IRE_FP_MP(ire);
25926 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25927 		ASSERT(DB_TYPE(mp1) == M_DATA);
25928 		/* Initiate IPPF processing */
25929 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25930 			UNLOCK_IRE_FP_MP(ire);
25931 			ip_process(proc, &mp, ill_index);
25932 			if (mp == NULL)
25933 				return (NULL);
25934 
25935 			ipha = (ipha_t *)mp->b_rptr;
25936 			LOCK_IRE_FP_MP(ire);
25937 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25938 				qos_done = B_TRUE;
25939 				goto no_fp_mp;
25940 			}
25941 			ASSERT(DB_TYPE(mp1) == M_DATA);
25942 		}
25943 		hlen = MBLKL(mp1);
25944 		/*
25945 		 * Check if we have enough room to prepend fastpath
25946 		 * header
25947 		 */
25948 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25949 			ll_hdr = rptr - hlen;
25950 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25951 			/*
25952 			 * Set the b_rptr to the start of the link layer
25953 			 * header
25954 			 */
25955 			mp->b_rptr = ll_hdr;
25956 			mp1 = mp;
25957 		} else {
25958 			mp1 = copyb(mp1);
25959 			if (mp1 == NULL)
25960 				goto unlock_err;
25961 			mp1->b_band = mp->b_band;
25962 			mp1->b_cont = mp;
25963 			/*
25964 			 * certain system generated traffic may not
25965 			 * have cred/label in ip header block. This
25966 			 * is true even for a labeled system. But for
25967 			 * labeled traffic, inherit the label in the
25968 			 * new header.
25969 			 */
25970 			if (DB_CRED(mp) != NULL)
25971 				mblk_setcred(mp1, DB_CRED(mp));
25972 			/*
25973 			 * XXX disable ICK_VALID and compute checksum
25974 			 * here; can happen if nce_fp_mp changes and
25975 			 * it can't be copied now due to insufficient
25976 			 * space. (unlikely, fp mp can change, but it
25977 			 * does not increase in length)
25978 			 */
25979 		}
25980 		UNLOCK_IRE_FP_MP(ire);
25981 	} else {
25982 no_fp_mp:
25983 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25984 		if (mp1 == NULL) {
25985 unlock_err:
25986 			UNLOCK_IRE_FP_MP(ire);
25987 			freemsg(mp);
25988 			return (NULL);
25989 		}
25990 		UNLOCK_IRE_FP_MP(ire);
25991 		mp1->b_cont = mp;
25992 		/*
25993 		 * certain system generated traffic may not
25994 		 * have cred/label in ip header block. This
25995 		 * is true even for a labeled system. But for
25996 		 * labeled traffic, inherit the label in the
25997 		 * new header.
25998 		 */
25999 		if (DB_CRED(mp) != NULL)
26000 			mblk_setcred(mp1, DB_CRED(mp));
26001 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
26002 			ip_process(proc, &mp1, ill_index);
26003 			if (mp1 == NULL)
26004 				return (NULL);
26005 
26006 			if (mp1->b_cont == NULL)
26007 				ipha = NULL;
26008 			else
26009 				ipha = (ipha_t *)mp1->b_cont->b_rptr;
26010 		}
26011 	}
26012 
26013 	*iphap = ipha;
26014 	return (mp1);
26015 #undef rptr
26016 }
26017 
26018 /*
26019  * Finish the outbound IPsec processing for an IPv6 packet. This function
26020  * is called from ipsec_out_process() if the IPsec packet was processed
26021  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
26022  * asynchronously.
26023  */
26024 void
26025 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
26026     ire_t *ire_arg)
26027 {
26028 	in6_addr_t *v6dstp;
26029 	ire_t *ire;
26030 	mblk_t *mp;
26031 	ip6_t *ip6h1;
26032 	uint_t	ill_index;
26033 	ipsec_out_t *io;
26034 	boolean_t attach_if, hwaccel;
26035 	uint32_t flags = IP6_NO_IPPOLICY;
26036 	int match_flags;
26037 	zoneid_t zoneid;
26038 	boolean_t ill_need_rele = B_FALSE;
26039 	boolean_t ire_need_rele = B_FALSE;
26040 	ip_stack_t	*ipst;
26041 
26042 	mp = ipsec_mp->b_cont;
26043 	ip6h1 = (ip6_t *)mp->b_rptr;
26044 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26045 	ASSERT(io->ipsec_out_ns != NULL);
26046 	ipst = io->ipsec_out_ns->netstack_ip;
26047 	ill_index = io->ipsec_out_ill_index;
26048 	if (io->ipsec_out_reachable) {
26049 		flags |= IPV6_REACHABILITY_CONFIRMATION;
26050 	}
26051 	attach_if = io->ipsec_out_attach_if;
26052 	hwaccel = io->ipsec_out_accelerated;
26053 	zoneid = io->ipsec_out_zoneid;
26054 	ASSERT(zoneid != ALL_ZONES);
26055 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
26056 	/* Multicast addresses should have non-zero ill_index. */
26057 	v6dstp = &ip6h->ip6_dst;
26058 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
26059 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
26060 	ASSERT(!attach_if || ill_index != 0);
26061 	if (ill_index != 0) {
26062 		if (ill == NULL) {
26063 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
26064 			    B_TRUE, ipst);
26065 
26066 			/* Failure case frees things for us. */
26067 			if (ill == NULL)
26068 				return;
26069 
26070 			ill_need_rele = B_TRUE;
26071 		}
26072 		/*
26073 		 * If this packet needs to go out on a particular interface
26074 		 * honor it.
26075 		 */
26076 		if (attach_if) {
26077 			match_flags = MATCH_IRE_ILL;
26078 
26079 			/*
26080 			 * Check if we need an ire that will not be
26081 			 * looked up by anybody else i.e. HIDDEN.
26082 			 */
26083 			if (ill_is_probeonly(ill)) {
26084 				match_flags |= MATCH_IRE_MARK_HIDDEN;
26085 			}
26086 		}
26087 	}
26088 	ASSERT(mp != NULL);
26089 
26090 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
26091 		boolean_t unspec_src;
26092 		ipif_t	*ipif;
26093 
26094 		/*
26095 		 * Use the ill_index to get the right ill.
26096 		 */
26097 		unspec_src = io->ipsec_out_unspec_src;
26098 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
26099 		if (ipif == NULL) {
26100 			if (ill_need_rele)
26101 				ill_refrele(ill);
26102 			freemsg(ipsec_mp);
26103 			return;
26104 		}
26105 
26106 		if (ire_arg != NULL) {
26107 			ire = ire_arg;
26108 		} else {
26109 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
26110 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
26111 			ire_need_rele = B_TRUE;
26112 		}
26113 		if (ire != NULL) {
26114 			ipif_refrele(ipif);
26115 			/*
26116 			 * XXX Do the multicast forwarding now, as the IPsec
26117 			 * processing has been done.
26118 			 */
26119 			goto send;
26120 		}
26121 
26122 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
26123 		mp->b_prev = NULL;
26124 		mp->b_next = NULL;
26125 
26126 		/*
26127 		 * If the IPsec packet was processed asynchronously,
26128 		 * drop it now.
26129 		 */
26130 		if (q == NULL) {
26131 			if (ill_need_rele)
26132 				ill_refrele(ill);
26133 			freemsg(ipsec_mp);
26134 			return;
26135 		}
26136 
26137 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
26138 		    unspec_src, zoneid);
26139 		ipif_refrele(ipif);
26140 	} else {
26141 		if (attach_if) {
26142 			ipif_t	*ipif;
26143 
26144 			ipif = ipif_get_next_ipif(NULL, ill);
26145 			if (ipif == NULL) {
26146 				if (ill_need_rele)
26147 					ill_refrele(ill);
26148 				freemsg(ipsec_mp);
26149 				return;
26150 			}
26151 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
26152 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
26153 			ire_need_rele = B_TRUE;
26154 			ipif_refrele(ipif);
26155 		} else {
26156 			if (ire_arg != NULL) {
26157 				ire = ire_arg;
26158 			} else {
26159 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL,
26160 				    ipst);
26161 				ire_need_rele = B_TRUE;
26162 			}
26163 		}
26164 		if (ire != NULL)
26165 			goto send;
26166 		/*
26167 		 * ire disappeared underneath.
26168 		 *
26169 		 * What we need to do here is the ip_newroute
26170 		 * logic to get the ire without doing the IPsec
26171 		 * processing. Follow the same old path. But this
26172 		 * time, ip_wput or ire_add_then_send will call us
26173 		 * directly as all the IPsec operations are done.
26174 		 */
26175 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
26176 		mp->b_prev = NULL;
26177 		mp->b_next = NULL;
26178 
26179 		/*
26180 		 * If the IPsec packet was processed asynchronously,
26181 		 * drop it now.
26182 		 */
26183 		if (q == NULL) {
26184 			if (ill_need_rele)
26185 				ill_refrele(ill);
26186 			freemsg(ipsec_mp);
26187 			return;
26188 		}
26189 
26190 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
26191 		    zoneid, ipst);
26192 	}
26193 	if (ill != NULL && ill_need_rele)
26194 		ill_refrele(ill);
26195 	return;
26196 send:
26197 	if (ill != NULL && ill_need_rele)
26198 		ill_refrele(ill);
26199 
26200 	/* Local delivery */
26201 	if (ire->ire_stq == NULL) {
26202 		ill_t	*out_ill;
26203 		ASSERT(q != NULL);
26204 
26205 		/* PFHooks: LOOPBACK_OUT */
26206 		out_ill = ire_to_ill(ire);
26207 
26208 		/*
26209 		 * DTrace this as ip:::send.  A blocked packet will fire the
26210 		 * send probe, but not the receive probe.
26211 		 */
26212 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
26213 		    void_ip_t *, ip6h, __dtrace_ipsr_ill_t *, out_ill,
26214 		    ipha_t *, NULL, ip6_t *, ip6h, int, 1);
26215 
26216 		DTRACE_PROBE4(ip6__loopback__out__start,
26217 		    ill_t *, NULL, ill_t *, out_ill,
26218 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
26219 
26220 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
26221 		    ipst->ips_ipv6firewall_loopback_out,
26222 		    NULL, out_ill, ip6h1, ipsec_mp, mp, 0, ipst);
26223 
26224 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
26225 
26226 		if (ipsec_mp != NULL) {
26227 			ip_wput_local_v6(RD(q), out_ill,
26228 			    ip6h, ipsec_mp, ire, 0, zoneid);
26229 		}
26230 		if (ire_need_rele)
26231 			ire_refrele(ire);
26232 		return;
26233 	}
26234 	/*
26235 	 * Everything is done. Send it out on the wire.
26236 	 * We force the insertion of a fragment header using the
26237 	 * IPH_FRAG_HDR flag in two cases:
26238 	 * - after reception of an ICMPv6 "packet too big" message
26239 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
26240 	 * - for multirouted IPv6 packets, so that the receiver can
26241 	 *   discard duplicates according to their fragment identifier
26242 	 */
26243 	/* XXX fix flow control problems. */
26244 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
26245 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
26246 		if (hwaccel) {
26247 			/*
26248 			 * hardware acceleration does not handle these
26249 			 * "slow path" cases.
26250 			 */
26251 			/* IPsec KSTATS: should bump bean counter here. */
26252 			if (ire_need_rele)
26253 				ire_refrele(ire);
26254 			freemsg(ipsec_mp);
26255 			return;
26256 		}
26257 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
26258 		    (mp->b_cont ? msgdsize(mp) :
26259 		    mp->b_wptr - (uchar_t *)ip6h)) {
26260 			/* IPsec KSTATS: should bump bean counter here. */
26261 			ip0dbg(("Packet length mismatch: %d, %ld\n",
26262 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
26263 			    msgdsize(mp)));
26264 			if (ire_need_rele)
26265 				ire_refrele(ire);
26266 			freemsg(ipsec_mp);
26267 			return;
26268 		}
26269 		ASSERT(mp->b_prev == NULL);
26270 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
26271 		    ntohs(ip6h->ip6_plen) +
26272 		    IPV6_HDR_LEN, ire->ire_max_frag));
26273 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
26274 		    ire->ire_max_frag);
26275 	} else {
26276 		UPDATE_OB_PKT_COUNT(ire);
26277 		ire->ire_last_used_time = lbolt;
26278 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
26279 	}
26280 	if (ire_need_rele)
26281 		ire_refrele(ire);
26282 	freeb(ipsec_mp);
26283 }
26284 
26285 void
26286 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
26287 {
26288 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
26289 	da_ipsec_t *hada;	/* data attributes */
26290 	ill_t *ill = (ill_t *)q->q_ptr;
26291 
26292 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
26293 
26294 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
26295 		/* IPsec KSTATS: Bump lose counter here! */
26296 		freemsg(mp);
26297 		return;
26298 	}
26299 
26300 	/*
26301 	 * It's an IPsec packet that must be
26302 	 * accelerated by the Provider, and the
26303 	 * outbound ill is IPsec acceleration capable.
26304 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
26305 	 * to the ill.
26306 	 * IPsec KSTATS: should bump packet counter here.
26307 	 */
26308 
26309 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
26310 	if (hada_mp == NULL) {
26311 		/* IPsec KSTATS: should bump packet counter here. */
26312 		freemsg(mp);
26313 		return;
26314 	}
26315 
26316 	hada_mp->b_datap->db_type = M_CTL;
26317 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
26318 	hada_mp->b_cont = mp;
26319 
26320 	hada = (da_ipsec_t *)hada_mp->b_rptr;
26321 	bzero(hada, sizeof (da_ipsec_t));
26322 	hada->da_type = IPHADA_M_CTL;
26323 
26324 	putnext(q, hada_mp);
26325 }
26326 
26327 /*
26328  * Finish the outbound IPsec processing. This function is called from
26329  * ipsec_out_process() if the IPsec packet was processed
26330  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
26331  * asynchronously.
26332  */
26333 void
26334 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
26335     ire_t *ire_arg)
26336 {
26337 	uint32_t v_hlen_tos_len;
26338 	ipaddr_t	dst;
26339 	ipif_t	*ipif = NULL;
26340 	ire_t *ire;
26341 	ire_t *ire1 = NULL;
26342 	mblk_t *next_mp = NULL;
26343 	uint32_t max_frag;
26344 	boolean_t multirt_send = B_FALSE;
26345 	mblk_t *mp;
26346 	ipha_t *ipha1;
26347 	uint_t	ill_index;
26348 	ipsec_out_t *io;
26349 	boolean_t attach_if;
26350 	int match_flags;
26351 	irb_t *irb = NULL;
26352 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
26353 	zoneid_t zoneid;
26354 	ipxmit_state_t	pktxmit_state;
26355 	ip_stack_t	*ipst;
26356 
26357 #ifdef	_BIG_ENDIAN
26358 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
26359 #else
26360 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
26361 #endif
26362 
26363 	mp = ipsec_mp->b_cont;
26364 	ipha1 = (ipha_t *)mp->b_rptr;
26365 	ASSERT(mp != NULL);
26366 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
26367 	dst = ipha->ipha_dst;
26368 
26369 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26370 	ill_index = io->ipsec_out_ill_index;
26371 	attach_if = io->ipsec_out_attach_if;
26372 	zoneid = io->ipsec_out_zoneid;
26373 	ASSERT(zoneid != ALL_ZONES);
26374 	ipst = io->ipsec_out_ns->netstack_ip;
26375 	ASSERT(io->ipsec_out_ns != NULL);
26376 
26377 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
26378 	if (ill_index != 0) {
26379 		if (ill == NULL) {
26380 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
26381 			    ill_index, B_FALSE, ipst);
26382 
26383 			/* Failure case frees things for us. */
26384 			if (ill == NULL)
26385 				return;
26386 
26387 			ill_need_rele = B_TRUE;
26388 		}
26389 		/*
26390 		 * If this packet needs to go out on a particular interface
26391 		 * honor it.
26392 		 */
26393 		if (attach_if) {
26394 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
26395 
26396 			/*
26397 			 * Check if we need an ire that will not be
26398 			 * looked up by anybody else i.e. HIDDEN.
26399 			 */
26400 			if (ill_is_probeonly(ill)) {
26401 				match_flags |= MATCH_IRE_MARK_HIDDEN;
26402 			}
26403 		}
26404 	}
26405 
26406 	if (CLASSD(dst)) {
26407 		boolean_t conn_dontroute;
26408 		/*
26409 		 * Use the ill_index to get the right ipif.
26410 		 */
26411 		conn_dontroute = io->ipsec_out_dontroute;
26412 		if (ill_index == 0)
26413 			ipif = ipif_lookup_group(dst, zoneid, ipst);
26414 		else
26415 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
26416 		if (ipif == NULL) {
26417 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
26418 			    " multicast\n"));
26419 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
26420 			freemsg(ipsec_mp);
26421 			goto done;
26422 		}
26423 		/*
26424 		 * ipha_src has already been intialized with the
26425 		 * value of the ipif in ip_wput. All we need now is
26426 		 * an ire to send this downstream.
26427 		 */
26428 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
26429 		    MBLK_GETLABEL(mp), match_flags, ipst);
26430 		if (ire != NULL) {
26431 			ill_t *ill1;
26432 			/*
26433 			 * Do the multicast forwarding now, as the IPsec
26434 			 * processing has been done.
26435 			 */
26436 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
26437 			    (ill1 = ire_to_ill(ire))) {
26438 				if (ip_mforward(ill1, ipha, mp)) {
26439 					freemsg(ipsec_mp);
26440 					ip1dbg(("ip_wput_ipsec_out: mforward "
26441 					    "failed\n"));
26442 					ire_refrele(ire);
26443 					goto done;
26444 				}
26445 			}
26446 			goto send;
26447 		}
26448 
26449 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
26450 		mp->b_prev = NULL;
26451 		mp->b_next = NULL;
26452 
26453 		/*
26454 		 * If the IPsec packet was processed asynchronously,
26455 		 * drop it now.
26456 		 */
26457 		if (q == NULL) {
26458 			freemsg(ipsec_mp);
26459 			goto done;
26460 		}
26461 
26462 		/*
26463 		 * We may be using a wrong ipif to create the ire.
26464 		 * But it is okay as the source address is assigned
26465 		 * for the packet already. Next outbound packet would
26466 		 * create the IRE with the right IPIF in ip_wput.
26467 		 *
26468 		 * Also handle RTF_MULTIRT routes.
26469 		 */
26470 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
26471 		    zoneid, &zero_info);
26472 	} else {
26473 		if (attach_if) {
26474 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
26475 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
26476 		} else {
26477 			if (ire_arg != NULL) {
26478 				ire = ire_arg;
26479 				ire_need_rele = B_FALSE;
26480 			} else {
26481 				ire = ire_cache_lookup(dst, zoneid,
26482 				    MBLK_GETLABEL(mp), ipst);
26483 			}
26484 		}
26485 		if (ire != NULL) {
26486 			goto send;
26487 		}
26488 
26489 		/*
26490 		 * ire disappeared underneath.
26491 		 *
26492 		 * What we need to do here is the ip_newroute
26493 		 * logic to get the ire without doing the IPsec
26494 		 * processing. Follow the same old path. But this
26495 		 * time, ip_wput or ire_add_then_put will call us
26496 		 * directly as all the IPsec operations are done.
26497 		 */
26498 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
26499 		mp->b_prev = NULL;
26500 		mp->b_next = NULL;
26501 
26502 		/*
26503 		 * If the IPsec packet was processed asynchronously,
26504 		 * drop it now.
26505 		 */
26506 		if (q == NULL) {
26507 			freemsg(ipsec_mp);
26508 			goto done;
26509 		}
26510 
26511 		/*
26512 		 * Since we're going through ip_newroute() again, we
26513 		 * need to make sure we don't:
26514 		 *
26515 		 *	1.) Trigger the ASSERT() with the ipha_ident
26516 		 *	    overloading.
26517 		 *	2.) Redo transport-layer checksumming, since we've
26518 		 *	    already done all that to get this far.
26519 		 *
26520 		 * The easiest way not do either of the above is to set
26521 		 * the ipha_ident field to IP_HDR_INCLUDED.
26522 		 */
26523 		ipha->ipha_ident = IP_HDR_INCLUDED;
26524 		ip_newroute(q, ipsec_mp, dst, (CONN_Q(q) ? Q_TO_CONN(q) : NULL),
26525 		    zoneid, ipst);
26526 	}
26527 	goto done;
26528 send:
26529 	if (ire->ire_stq == NULL) {
26530 		ill_t	*out_ill;
26531 		/*
26532 		 * Loopbacks go through ip_wput_local except for one case.
26533 		 * We come here if we generate a icmp_frag_needed message
26534 		 * after IPsec processing is over. When this function calls
26535 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
26536 		 * icmp_frag_needed. The message generated comes back here
26537 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
26538 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
26539 		 * source address as it is usually set in ip_wput_ire. As
26540 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
26541 		 * and we end up here. We can't enter ip_wput_ire once the
26542 		 * IPsec processing is over and hence we need to do it here.
26543 		 */
26544 		ASSERT(q != NULL);
26545 		UPDATE_OB_PKT_COUNT(ire);
26546 		ire->ire_last_used_time = lbolt;
26547 		if (ipha->ipha_src == 0)
26548 			ipha->ipha_src = ire->ire_src_addr;
26549 
26550 		/* PFHooks: LOOPBACK_OUT */
26551 		out_ill = ire_to_ill(ire);
26552 
26553 		/*
26554 		 * DTrace this as ip:::send.  A blocked packet will fire the
26555 		 * send probe, but not the receive probe.
26556 		 */
26557 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
26558 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
26559 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
26560 
26561 		DTRACE_PROBE4(ip4__loopback__out__start,
26562 		    ill_t *, NULL, ill_t *, out_ill,
26563 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
26564 
26565 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
26566 		    ipst->ips_ipv4firewall_loopback_out,
26567 		    NULL, out_ill, ipha1, ipsec_mp, mp, 0, ipst);
26568 
26569 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
26570 
26571 		if (ipsec_mp != NULL)
26572 			ip_wput_local(RD(q), out_ill,
26573 			    ipha, ipsec_mp, ire, 0, zoneid);
26574 		if (ire_need_rele)
26575 			ire_refrele(ire);
26576 		goto done;
26577 	}
26578 
26579 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
26580 		/*
26581 		 * We are through with IPsec processing.
26582 		 * Fragment this and send it on the wire.
26583 		 */
26584 		if (io->ipsec_out_accelerated) {
26585 			/*
26586 			 * The packet has been accelerated but must
26587 			 * be fragmented. This should not happen
26588 			 * since AH and ESP must not accelerate
26589 			 * packets that need fragmentation, however
26590 			 * the configuration could have changed
26591 			 * since the AH or ESP processing.
26592 			 * Drop packet.
26593 			 * IPsec KSTATS: bump bean counter here.
26594 			 */
26595 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
26596 			    "fragmented accelerated packet!\n"));
26597 			freemsg(ipsec_mp);
26598 		} else {
26599 			ip_wput_ire_fragmentit(ipsec_mp, ire,
26600 			    zoneid, ipst, NULL);
26601 		}
26602 		if (ire_need_rele)
26603 			ire_refrele(ire);
26604 		goto done;
26605 	}
26606 
26607 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
26608 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
26609 	    (void *)ire->ire_ipif, (void *)ipif));
26610 
26611 	/*
26612 	 * Multiroute the secured packet, unless IPsec really
26613 	 * requires the packet to go out only through a particular
26614 	 * interface.
26615 	 */
26616 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
26617 		ire_t *first_ire;
26618 		irb = ire->ire_bucket;
26619 		ASSERT(irb != NULL);
26620 		/*
26621 		 * This ire has been looked up as the one that
26622 		 * goes through the given ipif;
26623 		 * make sure we do not omit any other multiroute ire
26624 		 * that may be present in the bucket before this one.
26625 		 */
26626 		IRB_REFHOLD(irb);
26627 		for (first_ire = irb->irb_ire;
26628 		    first_ire != NULL;
26629 		    first_ire = first_ire->ire_next) {
26630 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
26631 			    (first_ire->ire_addr == ire->ire_addr) &&
26632 			    !(first_ire->ire_marks &
26633 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
26634 				break;
26635 			}
26636 		}
26637 
26638 		if ((first_ire != NULL) && (first_ire != ire)) {
26639 			/*
26640 			 * Don't change the ire if the packet must
26641 			 * be fragmented if sent via this new one.
26642 			 */
26643 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26644 				IRE_REFHOLD(first_ire);
26645 				if (ire_need_rele)
26646 					ire_refrele(ire);
26647 				else
26648 					ire_need_rele = B_TRUE;
26649 				ire = first_ire;
26650 			}
26651 		}
26652 		IRB_REFRELE(irb);
26653 
26654 		multirt_send = B_TRUE;
26655 		max_frag = ire->ire_max_frag;
26656 	} else {
26657 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
26658 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
26659 			    "flag, attach_if %d\n", attach_if));
26660 		}
26661 	}
26662 
26663 	/*
26664 	 * In most cases, the emission loop below is entered only once.
26665 	 * Only in the case where the ire holds the RTF_MULTIRT
26666 	 * flag, we loop to process all RTF_MULTIRT ires in the
26667 	 * bucket, and send the packet through all crossed
26668 	 * RTF_MULTIRT routes.
26669 	 */
26670 	do {
26671 		if (multirt_send) {
26672 			/*
26673 			 * ire1 holds here the next ire to process in the
26674 			 * bucket. If multirouting is expected,
26675 			 * any non-RTF_MULTIRT ire that has the
26676 			 * right destination address is ignored.
26677 			 */
26678 			ASSERT(irb != NULL);
26679 			IRB_REFHOLD(irb);
26680 			for (ire1 = ire->ire_next;
26681 			    ire1 != NULL;
26682 			    ire1 = ire1->ire_next) {
26683 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26684 					continue;
26685 				if (ire1->ire_addr != ire->ire_addr)
26686 					continue;
26687 				if (ire1->ire_marks &
26688 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
26689 					continue;
26690 				/* No loopback here */
26691 				if (ire1->ire_stq == NULL)
26692 					continue;
26693 				/*
26694 				 * Ensure we do not exceed the MTU
26695 				 * of the next route.
26696 				 */
26697 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26698 					ip_multirt_bad_mtu(ire1, max_frag);
26699 					continue;
26700 				}
26701 
26702 				IRE_REFHOLD(ire1);
26703 				break;
26704 			}
26705 			IRB_REFRELE(irb);
26706 			if (ire1 != NULL) {
26707 				/*
26708 				 * We are in a multiple send case, need to
26709 				 * make a copy of the packet.
26710 				 */
26711 				next_mp = copymsg(ipsec_mp);
26712 				if (next_mp == NULL) {
26713 					ire_refrele(ire1);
26714 					ire1 = NULL;
26715 				}
26716 			}
26717 		}
26718 		/*
26719 		 * Everything is done. Send it out on the wire
26720 		 *
26721 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26722 		 * either send it on the wire or, in the case of
26723 		 * HW acceleration, call ipsec_hw_putnext.
26724 		 */
26725 		if (ire->ire_nce &&
26726 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26727 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26728 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26729 			/*
26730 			 * If ire's link-layer is unresolved (this
26731 			 * would only happen if the incomplete ire
26732 			 * was added to cachetable via forwarding path)
26733 			 * don't bother going to ip_xmit_v4. Just drop the
26734 			 * packet.
26735 			 * There is a slight risk here, in that, if we
26736 			 * have the forwarding path create an incomplete
26737 			 * IRE, then until the IRE is completed, any
26738 			 * transmitted IPsec packets will be dropped
26739 			 * instead of being queued waiting for resolution.
26740 			 *
26741 			 * But the likelihood of a forwarding packet and a wput
26742 			 * packet sending to the same dst at the same time
26743 			 * and there not yet be an ARP entry for it is small.
26744 			 * Furthermore, if this actually happens, it might
26745 			 * be likely that wput would generate multiple
26746 			 * packets (and forwarding would also have a train
26747 			 * of packets) for that destination. If this is
26748 			 * the case, some of them would have been dropped
26749 			 * anyway, since ARP only queues a few packets while
26750 			 * waiting for resolution
26751 			 *
26752 			 * NOTE: We should really call ip_xmit_v4,
26753 			 * and let it queue the packet and send the
26754 			 * ARP query and have ARP come back thus:
26755 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26756 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26757 			 * hw accel work. But it's too complex to get
26758 			 * the IPsec hw  acceleration approach to fit
26759 			 * well with ip_xmit_v4 doing ARP without
26760 			 * doing IPsec simplification. For now, we just
26761 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26762 			 * that we can continue with the send on the next
26763 			 * attempt.
26764 			 *
26765 			 * XXX THis should be revisited, when
26766 			 * the IPsec/IP interaction is cleaned up
26767 			 */
26768 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26769 			    " - dropping packet\n"));
26770 			freemsg(ipsec_mp);
26771 			/*
26772 			 * Call ip_xmit_v4() to trigger ARP query
26773 			 * in case the nce_state is ND_INITIAL
26774 			 */
26775 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
26776 			goto drop_pkt;
26777 		}
26778 
26779 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26780 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26781 		    mblk_t *, ipsec_mp);
26782 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26783 		    ipst->ips_ipv4firewall_physical_out, NULL,
26784 		    ire->ire_ipif->ipif_ill, ipha1, ipsec_mp, mp, 0, ipst);
26785 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, ipsec_mp);
26786 		if (ipsec_mp == NULL)
26787 			goto drop_pkt;
26788 
26789 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26790 		pktxmit_state = ip_xmit_v4(mp, ire,
26791 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE, NULL);
26792 
26793 		if ((pktxmit_state ==  SEND_FAILED) ||
26794 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26795 
26796 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26797 drop_pkt:
26798 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26799 			    ipIfStatsOutDiscards);
26800 			if (ire_need_rele)
26801 				ire_refrele(ire);
26802 			if (ire1 != NULL) {
26803 				ire_refrele(ire1);
26804 				freemsg(next_mp);
26805 			}
26806 			goto done;
26807 		}
26808 
26809 		freeb(ipsec_mp);
26810 		if (ire_need_rele)
26811 			ire_refrele(ire);
26812 
26813 		if (ire1 != NULL) {
26814 			ire = ire1;
26815 			ire_need_rele = B_TRUE;
26816 			ASSERT(next_mp);
26817 			ipsec_mp = next_mp;
26818 			mp = ipsec_mp->b_cont;
26819 			ire1 = NULL;
26820 			next_mp = NULL;
26821 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26822 		} else {
26823 			multirt_send = B_FALSE;
26824 		}
26825 	} while (multirt_send);
26826 done:
26827 	if (ill != NULL && ill_need_rele)
26828 		ill_refrele(ill);
26829 	if (ipif != NULL)
26830 		ipif_refrele(ipif);
26831 }
26832 
26833 /*
26834  * Get the ill corresponding to the specified ire, and compare its
26835  * capabilities with the protocol and algorithms specified by the
26836  * the SA obtained from ipsec_out. If they match, annotate the
26837  * ipsec_out structure to indicate that the packet needs acceleration.
26838  *
26839  *
26840  * A packet is eligible for outbound hardware acceleration if the
26841  * following conditions are satisfied:
26842  *
26843  * 1. the packet will not be fragmented
26844  * 2. the provider supports the algorithm
26845  * 3. there is no pending control message being exchanged
26846  * 4. snoop is not attached
26847  * 5. the destination address is not a broadcast or multicast address.
26848  *
26849  * Rationale:
26850  *	- Hardware drivers do not support fragmentation with
26851  *	  the current interface.
26852  *	- snoop, multicast, and broadcast may result in exposure of
26853  *	  a cleartext datagram.
26854  * We check all five of these conditions here.
26855  *
26856  * XXX would like to nuke "ire_t *" parameter here; problem is that
26857  * IRE is only way to figure out if a v4 address is a broadcast and
26858  * thus ineligible for acceleration...
26859  */
26860 static void
26861 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26862 {
26863 	ipsec_out_t *io;
26864 	mblk_t *data_mp;
26865 	uint_t plen, overhead;
26866 	ip_stack_t	*ipst;
26867 
26868 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26869 		return;
26870 
26871 	if (ill == NULL)
26872 		return;
26873 	ipst = ill->ill_ipst;
26874 	/*
26875 	 * Destination address is a broadcast or multicast.  Punt.
26876 	 */
26877 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26878 	    IRE_LOCAL)))
26879 		return;
26880 
26881 	data_mp = ipsec_mp->b_cont;
26882 
26883 	if (ill->ill_isv6) {
26884 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26885 
26886 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26887 			return;
26888 
26889 		plen = ip6h->ip6_plen;
26890 	} else {
26891 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26892 
26893 		if (CLASSD(ipha->ipha_dst))
26894 			return;
26895 
26896 		plen = ipha->ipha_length;
26897 	}
26898 	/*
26899 	 * Is there a pending DLPI control message being exchanged
26900 	 * between IP/IPsec and the DLS Provider? If there is, it
26901 	 * could be a SADB update, and the state of the DLS Provider
26902 	 * SADB might not be in sync with the SADB maintained by
26903 	 * IPsec. To avoid dropping packets or using the wrong keying
26904 	 * material, we do not accelerate this packet.
26905 	 */
26906 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26907 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26908 		    "ill_dlpi_pending! don't accelerate packet\n"));
26909 		return;
26910 	}
26911 
26912 	/*
26913 	 * Is the Provider in promiscous mode? If it does, we don't
26914 	 * accelerate the packet since it will bounce back up to the
26915 	 * listeners in the clear.
26916 	 */
26917 	if (ill->ill_promisc_on_phys) {
26918 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26919 		    "ill in promiscous mode, don't accelerate packet\n"));
26920 		return;
26921 	}
26922 
26923 	/*
26924 	 * Will the packet require fragmentation?
26925 	 */
26926 
26927 	/*
26928 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26929 	 * as is used elsewhere.
26930 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26931 	 *	+ 2-byte trailer
26932 	 */
26933 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26934 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26935 
26936 	if ((plen + overhead) > ill->ill_max_mtu)
26937 		return;
26938 
26939 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26940 
26941 	/*
26942 	 * Can the ill accelerate this IPsec protocol and algorithm
26943 	 * specified by the SA?
26944 	 */
26945 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26946 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26947 		return;
26948 	}
26949 
26950 	/*
26951 	 * Tell AH or ESP that the outbound ill is capable of
26952 	 * accelerating this packet.
26953 	 */
26954 	io->ipsec_out_is_capab_ill = B_TRUE;
26955 }
26956 
26957 /*
26958  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26959  *
26960  * If this function returns B_TRUE, the requested SA's have been filled
26961  * into the ipsec_out_*_sa pointers.
26962  *
26963  * If the function returns B_FALSE, the packet has been "consumed", most
26964  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26965  *
26966  * The SA references created by the protocol-specific "select"
26967  * function will be released when the ipsec_mp is freed, thanks to the
26968  * ipsec_out_free destructor -- see spd.c.
26969  */
26970 static boolean_t
26971 ipsec_out_select_sa(mblk_t *ipsec_mp)
26972 {
26973 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26974 	ipsec_out_t *io;
26975 	ipsec_policy_t *pp;
26976 	ipsec_action_t *ap;
26977 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26978 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26979 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26980 
26981 	if (!io->ipsec_out_secure) {
26982 		/*
26983 		 * We came here by mistake.
26984 		 * Don't bother with ipsec processing
26985 		 * We should "discourage" this path in the future.
26986 		 */
26987 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26988 		return (B_FALSE);
26989 	}
26990 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26991 	ASSERT((io->ipsec_out_policy != NULL) ||
26992 	    (io->ipsec_out_act != NULL));
26993 
26994 	ASSERT(io->ipsec_out_failed == B_FALSE);
26995 
26996 	/*
26997 	 * IPsec processing has started.
26998 	 */
26999 	io->ipsec_out_proc_begin = B_TRUE;
27000 	ap = io->ipsec_out_act;
27001 	if (ap == NULL) {
27002 		pp = io->ipsec_out_policy;
27003 		ASSERT(pp != NULL);
27004 		ap = pp->ipsp_act;
27005 		ASSERT(ap != NULL);
27006 	}
27007 
27008 	/*
27009 	 * We have an action.  now, let's select SA's.
27010 	 * (In the future, we can cache this in the conn_t..)
27011 	 */
27012 	if (ap->ipa_want_esp) {
27013 		if (io->ipsec_out_esp_sa == NULL) {
27014 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
27015 			    IPPROTO_ESP);
27016 		}
27017 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
27018 	}
27019 
27020 	if (ap->ipa_want_ah) {
27021 		if (io->ipsec_out_ah_sa == NULL) {
27022 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
27023 			    IPPROTO_AH);
27024 		}
27025 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
27026 		/*
27027 		 * The ESP and AH processing order needs to be preserved
27028 		 * when both protocols are required (ESP should be applied
27029 		 * before AH for an outbound packet). Force an ESP ACQUIRE
27030 		 * when both ESP and AH are required, and an AH ACQUIRE
27031 		 * is needed.
27032 		 */
27033 		if (ap->ipa_want_esp && need_ah_acquire)
27034 			need_esp_acquire = B_TRUE;
27035 	}
27036 
27037 	/*
27038 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
27039 	 * Release SAs that got referenced, but will not be used until we
27040 	 * acquire _all_ of the SAs we need.
27041 	 */
27042 	if (need_ah_acquire || need_esp_acquire) {
27043 		if (io->ipsec_out_ah_sa != NULL) {
27044 			IPSA_REFRELE(io->ipsec_out_ah_sa);
27045 			io->ipsec_out_ah_sa = NULL;
27046 		}
27047 		if (io->ipsec_out_esp_sa != NULL) {
27048 			IPSA_REFRELE(io->ipsec_out_esp_sa);
27049 			io->ipsec_out_esp_sa = NULL;
27050 		}
27051 
27052 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
27053 		return (B_FALSE);
27054 	}
27055 
27056 	return (B_TRUE);
27057 }
27058 
27059 /*
27060  * Process an IPSEC_OUT message and see what you can
27061  * do with it.
27062  * IPQoS Notes:
27063  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
27064  * IPsec.
27065  * XXX would like to nuke ire_t.
27066  * XXX ill_index better be "real"
27067  */
27068 void
27069 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
27070 {
27071 	ipsec_out_t *io;
27072 	ipsec_policy_t *pp;
27073 	ipsec_action_t *ap;
27074 	ipha_t *ipha;
27075 	ip6_t *ip6h;
27076 	mblk_t *mp;
27077 	ill_t *ill;
27078 	zoneid_t zoneid;
27079 	ipsec_status_t ipsec_rc;
27080 	boolean_t ill_need_rele = B_FALSE;
27081 	ip_stack_t	*ipst;
27082 	ipsec_stack_t	*ipss;
27083 
27084 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
27085 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
27086 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
27087 	ipst = io->ipsec_out_ns->netstack_ip;
27088 	mp = ipsec_mp->b_cont;
27089 
27090 	/*
27091 	 * Initiate IPPF processing. We do it here to account for packets
27092 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
27093 	 * We can check for ipsec_out_proc_begin even for such packets, as
27094 	 * they will always be false (asserted below).
27095 	 */
27096 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
27097 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
27098 		    io->ipsec_out_ill_index : ill_index);
27099 		if (mp == NULL) {
27100 			ip2dbg(("ipsec_out_process: packet dropped "\
27101 			    "during IPPF processing\n"));
27102 			freeb(ipsec_mp);
27103 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
27104 			return;
27105 		}
27106 	}
27107 
27108 	if (!io->ipsec_out_secure) {
27109 		/*
27110 		 * We came here by mistake.
27111 		 * Don't bother with ipsec processing
27112 		 * Should "discourage" this path in the future.
27113 		 */
27114 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
27115 		goto done;
27116 	}
27117 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
27118 	ASSERT((io->ipsec_out_policy != NULL) ||
27119 	    (io->ipsec_out_act != NULL));
27120 	ASSERT(io->ipsec_out_failed == B_FALSE);
27121 
27122 	ipss = ipst->ips_netstack->netstack_ipsec;
27123 	if (!ipsec_loaded(ipss)) {
27124 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
27125 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
27126 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
27127 		} else {
27128 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
27129 		}
27130 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
27131 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
27132 		    &ipss->ipsec_dropper);
27133 		return;
27134 	}
27135 
27136 	/*
27137 	 * IPsec processing has started.
27138 	 */
27139 	io->ipsec_out_proc_begin = B_TRUE;
27140 	ap = io->ipsec_out_act;
27141 	if (ap == NULL) {
27142 		pp = io->ipsec_out_policy;
27143 		ASSERT(pp != NULL);
27144 		ap = pp->ipsp_act;
27145 		ASSERT(ap != NULL);
27146 	}
27147 
27148 	/*
27149 	 * Save the outbound ill index. When the packet comes back
27150 	 * from IPsec, we make sure the ill hasn't changed or disappeared
27151 	 * before sending it the accelerated packet.
27152 	 */
27153 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
27154 		int ifindex;
27155 		ill = ire_to_ill(ire);
27156 		ifindex = ill->ill_phyint->phyint_ifindex;
27157 		io->ipsec_out_capab_ill_index = ifindex;
27158 	}
27159 
27160 	/*
27161 	 * The order of processing is first insert a IP header if needed.
27162 	 * Then insert the ESP header and then the AH header.
27163 	 */
27164 	if ((io->ipsec_out_se_done == B_FALSE) &&
27165 	    (ap->ipa_want_se)) {
27166 		/*
27167 		 * First get the outer IP header before sending
27168 		 * it to ESP.
27169 		 */
27170 		ipha_t *oipha, *iipha;
27171 		mblk_t *outer_mp, *inner_mp;
27172 
27173 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
27174 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
27175 			    "ipsec_out_process: "
27176 			    "Self-Encapsulation failed: Out of memory\n");
27177 			freemsg(ipsec_mp);
27178 			if (ill != NULL) {
27179 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
27180 			} else {
27181 				BUMP_MIB(&ipst->ips_ip_mib,
27182 				    ipIfStatsOutDiscards);
27183 			}
27184 			return;
27185 		}
27186 		inner_mp = ipsec_mp->b_cont;
27187 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
27188 		oipha = (ipha_t *)outer_mp->b_rptr;
27189 		iipha = (ipha_t *)inner_mp->b_rptr;
27190 		*oipha = *iipha;
27191 		outer_mp->b_wptr += sizeof (ipha_t);
27192 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
27193 		    sizeof (ipha_t));
27194 		oipha->ipha_protocol = IPPROTO_ENCAP;
27195 		oipha->ipha_version_and_hdr_length =
27196 		    IP_SIMPLE_HDR_VERSION;
27197 		oipha->ipha_hdr_checksum = 0;
27198 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
27199 		outer_mp->b_cont = inner_mp;
27200 		ipsec_mp->b_cont = outer_mp;
27201 
27202 		io->ipsec_out_se_done = B_TRUE;
27203 		io->ipsec_out_tunnel = B_TRUE;
27204 	}
27205 
27206 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
27207 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
27208 	    !ipsec_out_select_sa(ipsec_mp))
27209 		return;
27210 
27211 	/*
27212 	 * By now, we know what SA's to use.  Toss over to ESP & AH
27213 	 * to do the heavy lifting.
27214 	 */
27215 	zoneid = io->ipsec_out_zoneid;
27216 	ASSERT(zoneid != ALL_ZONES);
27217 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
27218 		ASSERT(io->ipsec_out_esp_sa != NULL);
27219 		io->ipsec_out_esp_done = B_TRUE;
27220 		/*
27221 		 * Note that since hw accel can only apply one transform,
27222 		 * not two, we skip hw accel for ESP if we also have AH
27223 		 * This is an design limitation of the interface
27224 		 * which should be revisited.
27225 		 */
27226 		ASSERT(ire != NULL);
27227 		if (io->ipsec_out_ah_sa == NULL) {
27228 			ill = (ill_t *)ire->ire_stq->q_ptr;
27229 			ipsec_out_is_accelerated(ipsec_mp,
27230 			    io->ipsec_out_esp_sa, ill, ire);
27231 		}
27232 
27233 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
27234 		switch (ipsec_rc) {
27235 		case IPSEC_STATUS_SUCCESS:
27236 			break;
27237 		case IPSEC_STATUS_FAILED:
27238 			if (ill != NULL) {
27239 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
27240 			} else {
27241 				BUMP_MIB(&ipst->ips_ip_mib,
27242 				    ipIfStatsOutDiscards);
27243 			}
27244 			/* FALLTHRU */
27245 		case IPSEC_STATUS_PENDING:
27246 			return;
27247 		}
27248 	}
27249 
27250 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
27251 		ASSERT(io->ipsec_out_ah_sa != NULL);
27252 		io->ipsec_out_ah_done = B_TRUE;
27253 		if (ire == NULL) {
27254 			int idx = io->ipsec_out_capab_ill_index;
27255 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
27256 			    NULL, NULL, NULL, NULL, ipst);
27257 			ill_need_rele = B_TRUE;
27258 		} else {
27259 			ill = (ill_t *)ire->ire_stq->q_ptr;
27260 		}
27261 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
27262 		    ire);
27263 
27264 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
27265 		switch (ipsec_rc) {
27266 		case IPSEC_STATUS_SUCCESS:
27267 			break;
27268 		case IPSEC_STATUS_FAILED:
27269 			if (ill != NULL) {
27270 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
27271 			} else {
27272 				BUMP_MIB(&ipst->ips_ip_mib,
27273 				    ipIfStatsOutDiscards);
27274 			}
27275 			/* FALLTHRU */
27276 		case IPSEC_STATUS_PENDING:
27277 			if (ill != NULL && ill_need_rele)
27278 				ill_refrele(ill);
27279 			return;
27280 		}
27281 	}
27282 	/*
27283 	 * We are done with IPsec processing. Send it over
27284 	 * the wire.
27285 	 */
27286 done:
27287 	mp = ipsec_mp->b_cont;
27288 	ipha = (ipha_t *)mp->b_rptr;
27289 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
27290 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
27291 	} else {
27292 		ip6h = (ip6_t *)ipha;
27293 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
27294 	}
27295 	if (ill != NULL && ill_need_rele)
27296 		ill_refrele(ill);
27297 }
27298 
27299 /* ARGSUSED */
27300 void
27301 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
27302 {
27303 	opt_restart_t	*or;
27304 	int	err;
27305 	conn_t	*connp;
27306 
27307 	ASSERT(CONN_Q(q));
27308 	connp = Q_TO_CONN(q);
27309 
27310 	ASSERT(first_mp->b_datap->db_type == M_CTL);
27311 	or = (opt_restart_t *)first_mp->b_rptr;
27312 	/*
27313 	 * We don't need to pass any credentials here since this is just
27314 	 * a restart. The credentials are passed in when svr4_optcom_req
27315 	 * is called the first time (from ip_wput_nondata).
27316 	 */
27317 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
27318 		err = svr4_optcom_req(q, first_mp, NULL,
27319 		    &ip_opt_obj, B_FALSE);
27320 	} else {
27321 		ASSERT(or->or_type == T_OPTMGMT_REQ);
27322 		err = tpi_optcom_req(q, first_mp, NULL,
27323 		    &ip_opt_obj, B_FALSE);
27324 	}
27325 	if (err != EINPROGRESS) {
27326 		/* operation is done */
27327 		CONN_OPER_PENDING_DONE(connp);
27328 	}
27329 }
27330 
27331 /*
27332  * ioctls that go through a down/up sequence may need to wait for the down
27333  * to complete. This involves waiting for the ire and ipif refcnts to go down
27334  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
27335  */
27336 /* ARGSUSED */
27337 void
27338 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27339 {
27340 	struct iocblk *iocp;
27341 	mblk_t *mp1;
27342 	ip_ioctl_cmd_t *ipip;
27343 	int err;
27344 	sin_t	*sin;
27345 	struct lifreq *lifr;
27346 	struct ifreq *ifr;
27347 
27348 	iocp = (struct iocblk *)mp->b_rptr;
27349 	ASSERT(ipsq != NULL);
27350 	/* Existence of mp1 verified in ip_wput_nondata */
27351 	mp1 = mp->b_cont->b_cont;
27352 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27353 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
27354 		/*
27355 		 * Special case where ipsq_current_ipif is not set:
27356 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
27357 		 * ill could also have become part of a ipmp group in the
27358 		 * process, we are here as were not able to complete the
27359 		 * operation in ipif_set_values because we could not become
27360 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
27361 		 * will not be set so we need to set it.
27362 		 */
27363 		ill_t *ill = q->q_ptr;
27364 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
27365 	}
27366 	ASSERT(ipsq->ipsq_current_ipif != NULL);
27367 
27368 	if (ipip->ipi_cmd_type == IF_CMD) {
27369 		/* This a old style SIOC[GS]IF* command */
27370 		ifr = (struct ifreq *)mp1->b_rptr;
27371 		sin = (sin_t *)&ifr->ifr_addr;
27372 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
27373 		/* This a new style SIOC[GS]LIF* command */
27374 		lifr = (struct lifreq *)mp1->b_rptr;
27375 		sin = (sin_t *)&lifr->lifr_addr;
27376 	} else {
27377 		sin = NULL;
27378 	}
27379 
27380 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_current_ipif, sin, q, mp,
27381 	    ipip, mp1->b_rptr);
27382 
27383 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27384 }
27385 
27386 /*
27387  * ioctl processing
27388  *
27389  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
27390  * the ioctl command in the ioctl tables, determines the copyin data size
27391  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
27392  *
27393  * ioctl processing then continues when the M_IOCDATA makes its way down to
27394  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
27395  * associated 'conn' is refheld till the end of the ioctl and the general
27396  * ioctl processing function ip_process_ioctl() is called to extract the
27397  * arguments and process the ioctl.  To simplify extraction, ioctl commands
27398  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
27399  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
27400  * is used to extract the ioctl's arguments.
27401  *
27402  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
27403  * so goes thru the serialization primitive ipsq_try_enter. Then the
27404  * appropriate function to handle the ioctl is called based on the entry in
27405  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
27406  * which also refreleases the 'conn' that was refheld at the start of the
27407  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
27408  *
27409  * Many exclusive ioctls go thru an internal down up sequence as part of
27410  * the operation. For example an attempt to change the IP address of an
27411  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
27412  * does all the cleanup such as deleting all ires that use this address.
27413  * Then we need to wait till all references to the interface go away.
27414  */
27415 void
27416 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
27417 {
27418 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
27419 	ip_ioctl_cmd_t *ipip = arg;
27420 	ip_extract_func_t *extract_funcp;
27421 	cmd_info_t ci;
27422 	int err;
27423 
27424 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
27425 
27426 	if (ipip == NULL)
27427 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27428 
27429 	/*
27430 	 * SIOCLIFADDIF needs to go thru a special path since the
27431 	 * ill may not exist yet. This happens in the case of lo0
27432 	 * which is created using this ioctl.
27433 	 */
27434 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
27435 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
27436 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27437 		return;
27438 	}
27439 
27440 	ci.ci_ipif = NULL;
27441 	if (ipip->ipi_cmd_type == MISC_CMD) {
27442 		/*
27443 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
27444 		 */
27445 		if (ipip->ipi_cmd == IF_UNITSEL) {
27446 			/* ioctl comes down the ill */
27447 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
27448 			ipif_refhold(ci.ci_ipif);
27449 		}
27450 		err = 0;
27451 		ci.ci_sin = NULL;
27452 		ci.ci_sin6 = NULL;
27453 		ci.ci_lifr = NULL;
27454 	} else {
27455 		switch (ipip->ipi_cmd_type) {
27456 		case IF_CMD:
27457 		case LIF_CMD:
27458 			extract_funcp = ip_extract_lifreq;
27459 			break;
27460 
27461 		case ARP_CMD:
27462 		case XARP_CMD:
27463 			extract_funcp = ip_extract_arpreq;
27464 			break;
27465 
27466 		case TUN_CMD:
27467 			extract_funcp = ip_extract_tunreq;
27468 			break;
27469 
27470 		case MSFILT_CMD:
27471 			extract_funcp = ip_extract_msfilter;
27472 			break;
27473 
27474 		default:
27475 			ASSERT(0);
27476 		}
27477 
27478 		err = (*extract_funcp)(q, mp, ipip, &ci, ip_process_ioctl);
27479 		if (err != 0) {
27480 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27481 			return;
27482 		}
27483 
27484 		/*
27485 		 * All of the extraction functions return a refheld ipif.
27486 		 */
27487 		ASSERT(ci.ci_ipif != NULL);
27488 	}
27489 
27490 	if (!(ipip->ipi_flags & IPI_WR)) {
27491 		/*
27492 		 * A return value of EINPROGRESS means the ioctl is
27493 		 * either queued and waiting for some reason or has
27494 		 * already completed.
27495 		 */
27496 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
27497 		    ci.ci_lifr);
27498 		if (ci.ci_ipif != NULL)
27499 			ipif_refrele(ci.ci_ipif);
27500 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27501 		return;
27502 	}
27503 
27504 	/*
27505 	 * If ipsq is non-null, we are already being called exclusively on an
27506 	 * ill but in the case of a failover in progress it is the "from" ill,
27507 	 *  rather than the "to" ill (which is the ill ptr passed in).
27508 	 * In order to ensure we are exclusive on both ILLs we rerun
27509 	 * ipsq_try_enter() here, ipsq's support recursive entry.
27510 	 */
27511 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
27512 	ASSERT(ci.ci_ipif != NULL);
27513 
27514 	ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp, ip_process_ioctl,
27515 	    NEW_OP, B_TRUE);
27516 
27517 	/*
27518 	 * Release the ipif so that ipif_down and friends that wait for
27519 	 * references to go away are not misled about the current ipif_refcnt
27520 	 * values. We are writer so we can access the ipif even after releasing
27521 	 * the ipif.
27522 	 */
27523 	ipif_refrele(ci.ci_ipif);
27524 	if (ipsq == NULL)
27525 		return;
27526 
27527 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
27528 
27529 	/*
27530 	 * For most set ioctls that come here, this serves as a single point
27531 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
27532 	 * be any new references to the ipif. This helps functions that go
27533 	 * through this path and end up trying to wait for the refcnts
27534 	 * associated with the ipif to go down to zero. Some exceptions are
27535 	 * Failover, Failback, and Groupname commands that operate on more than
27536 	 * just the ci.ci_ipif. These commands internally determine the
27537 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
27538 	 * flags on that set. Another exception is the Removeif command that
27539 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
27540 	 * ipif to operate on.
27541 	 */
27542 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
27543 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
27544 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
27545 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
27546 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
27547 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
27548 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
27549 
27550 	/*
27551 	 * A return value of EINPROGRESS means the ioctl is
27552 	 * either queued and waiting for some reason or has
27553 	 * already completed.
27554 	 */
27555 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
27556 
27557 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27558 
27559 	ipsq_exit(ipsq);
27560 }
27561 
27562 /*
27563  * Complete the ioctl. Typically ioctls use the mi package and need to
27564  * do mi_copyout/mi_copy_done.
27565  */
27566 void
27567 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
27568 {
27569 	conn_t	*connp = NULL;
27570 
27571 	if (err == EINPROGRESS)
27572 		return;
27573 
27574 	if (CONN_Q(q)) {
27575 		connp = Q_TO_CONN(q);
27576 		ASSERT(connp->conn_ref >= 2);
27577 	}
27578 
27579 	switch (mode) {
27580 	case COPYOUT:
27581 		if (err == 0)
27582 			mi_copyout(q, mp);
27583 		else
27584 			mi_copy_done(q, mp, err);
27585 		break;
27586 
27587 	case NO_COPYOUT:
27588 		mi_copy_done(q, mp, err);
27589 		break;
27590 
27591 	default:
27592 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
27593 		break;
27594 	}
27595 
27596 	/*
27597 	 * The refhold placed at the start of the ioctl is released here.
27598 	 */
27599 	if (connp != NULL)
27600 		CONN_OPER_PENDING_DONE(connp);
27601 
27602 	if (ipsq != NULL)
27603 		ipsq_current_finish(ipsq);
27604 }
27605 
27606 /* Called from ip_wput for all non data messages */
27607 /* ARGSUSED */
27608 void
27609 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27610 {
27611 	mblk_t		*mp1;
27612 	ire_t		*ire, *fake_ire;
27613 	ill_t		*ill;
27614 	struct iocblk	*iocp;
27615 	ip_ioctl_cmd_t	*ipip;
27616 	cred_t		*cr;
27617 	conn_t		*connp;
27618 	int		err;
27619 	nce_t		*nce;
27620 	ipif_t		*ipif;
27621 	ip_stack_t	*ipst;
27622 	char		*proto_str;
27623 
27624 	if (CONN_Q(q)) {
27625 		connp = Q_TO_CONN(q);
27626 		ipst = connp->conn_netstack->netstack_ip;
27627 	} else {
27628 		connp = NULL;
27629 		ipst = ILLQ_TO_IPST(q);
27630 	}
27631 
27632 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
27633 
27634 	switch (DB_TYPE(mp)) {
27635 	case M_IOCTL:
27636 		/*
27637 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
27638 		 * will arrange to copy in associated control structures.
27639 		 */
27640 		ip_sioctl_copyin_setup(q, mp);
27641 		return;
27642 	case M_IOCDATA:
27643 		/*
27644 		 * Ensure that this is associated with one of our trans-
27645 		 * parent ioctls.  If it's not ours, discard it if we're
27646 		 * running as a driver, or pass it on if we're a module.
27647 		 */
27648 		iocp = (struct iocblk *)mp->b_rptr;
27649 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27650 		if (ipip == NULL) {
27651 			if (q->q_next == NULL) {
27652 				goto nak;
27653 			} else {
27654 				putnext(q, mp);
27655 			}
27656 			return;
27657 		}
27658 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
27659 			/*
27660 			 * the ioctl is one we recognise, but is not
27661 			 * consumed by IP as a module, pass M_IOCDATA
27662 			 * for processing downstream, but only for
27663 			 * common Streams ioctls.
27664 			 */
27665 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27666 				putnext(q, mp);
27667 				return;
27668 			} else {
27669 				goto nak;
27670 			}
27671 		}
27672 
27673 		/* IOCTL continuation following copyin or copyout. */
27674 		if (mi_copy_state(q, mp, NULL) == -1) {
27675 			/*
27676 			 * The copy operation failed.  mi_copy_state already
27677 			 * cleaned up, so we're out of here.
27678 			 */
27679 			return;
27680 		}
27681 		/*
27682 		 * If we just completed a copy in, we become writer and
27683 		 * continue processing in ip_sioctl_copyin_done.  If it
27684 		 * was a copy out, we call mi_copyout again.  If there is
27685 		 * nothing more to copy out, it will complete the IOCTL.
27686 		 */
27687 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27688 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27689 				mi_copy_done(q, mp, EPROTO);
27690 				return;
27691 			}
27692 			/*
27693 			 * Check for cases that need more copying.  A return
27694 			 * value of 0 means a second copyin has been started,
27695 			 * so we return; a return value of 1 means no more
27696 			 * copying is needed, so we continue.
27697 			 */
27698 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
27699 			    MI_COPY_COUNT(mp) == 1) {
27700 				if (ip_copyin_msfilter(q, mp) == 0)
27701 					return;
27702 			}
27703 			/*
27704 			 * Refhold the conn, till the ioctl completes. This is
27705 			 * needed in case the ioctl ends up in the pending mp
27706 			 * list. Every mp in the ill_pending_mp list and
27707 			 * the ipsq_pending_mp must have a refhold on the conn
27708 			 * to resume processing. The refhold is released when
27709 			 * the ioctl completes. (normally or abnormally)
27710 			 * In all cases ip_ioctl_finish is called to finish
27711 			 * the ioctl.
27712 			 */
27713 			if (connp != NULL) {
27714 				/* This is not a reentry */
27715 				ASSERT(ipsq == NULL);
27716 				CONN_INC_REF(connp);
27717 			} else {
27718 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27719 					mi_copy_done(q, mp, EINVAL);
27720 					return;
27721 				}
27722 			}
27723 
27724 			ip_process_ioctl(ipsq, q, mp, ipip);
27725 
27726 		} else {
27727 			mi_copyout(q, mp);
27728 		}
27729 		return;
27730 nak:
27731 		iocp->ioc_error = EINVAL;
27732 		mp->b_datap->db_type = M_IOCNAK;
27733 		iocp->ioc_count = 0;
27734 		qreply(q, mp);
27735 		return;
27736 
27737 	case M_IOCNAK:
27738 		/*
27739 		 * The only way we could get here is if a resolver didn't like
27740 		 * an IOCTL we sent it.	 This shouldn't happen.
27741 		 */
27742 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27743 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27744 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27745 		freemsg(mp);
27746 		return;
27747 	case M_IOCACK:
27748 		/* /dev/ip shouldn't see this */
27749 		if (CONN_Q(q))
27750 			goto nak;
27751 
27752 		/* Finish socket ioctls passed through to ARP. */
27753 		ip_sioctl_iocack(q, mp);
27754 		return;
27755 	case M_FLUSH:
27756 		if (*mp->b_rptr & FLUSHW)
27757 			flushq(q, FLUSHALL);
27758 		if (q->q_next) {
27759 			putnext(q, mp);
27760 			return;
27761 		}
27762 		if (*mp->b_rptr & FLUSHR) {
27763 			*mp->b_rptr &= ~FLUSHW;
27764 			qreply(q, mp);
27765 			return;
27766 		}
27767 		freemsg(mp);
27768 		return;
27769 	case IRE_DB_REQ_TYPE:
27770 		if (connp == NULL) {
27771 			proto_str = "IRE_DB_REQ_TYPE";
27772 			goto protonak;
27773 		}
27774 		/* An Upper Level Protocol wants a copy of an IRE. */
27775 		ip_ire_req(q, mp);
27776 		return;
27777 	case M_CTL:
27778 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27779 			break;
27780 
27781 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27782 		    TUN_HELLO) {
27783 			ASSERT(connp != NULL);
27784 			connp->conn_flags |= IPCL_IPTUN;
27785 			freeb(mp);
27786 			return;
27787 		}
27788 
27789 		/* M_CTL messages are used by ARP to tell us things. */
27790 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27791 			break;
27792 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27793 		case AR_ENTRY_SQUERY:
27794 			ip_wput_ctl(q, mp);
27795 			return;
27796 		case AR_CLIENT_NOTIFY:
27797 			ip_arp_news(q, mp);
27798 			return;
27799 		case AR_DLPIOP_DONE:
27800 			ASSERT(q->q_next != NULL);
27801 			ill = (ill_t *)q->q_ptr;
27802 			/* qwriter_ip releases the refhold */
27803 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27804 			ill_refhold(ill);
27805 			qwriter_ip(ill, q, mp, ip_arp_done, CUR_OP, B_FALSE);
27806 			return;
27807 		case AR_ARP_CLOSING:
27808 			/*
27809 			 * ARP (above us) is closing. If no ARP bringup is
27810 			 * currently pending, ack the message so that ARP
27811 			 * can complete its close. Also mark ill_arp_closing
27812 			 * so that new ARP bringups will fail. If any
27813 			 * ARP bringup is currently in progress, we will
27814 			 * ack this when the current ARP bringup completes.
27815 			 */
27816 			ASSERT(q->q_next != NULL);
27817 			ill = (ill_t *)q->q_ptr;
27818 			mutex_enter(&ill->ill_lock);
27819 			ill->ill_arp_closing = 1;
27820 			if (!ill->ill_arp_bringup_pending) {
27821 				mutex_exit(&ill->ill_lock);
27822 				qreply(q, mp);
27823 			} else {
27824 				mutex_exit(&ill->ill_lock);
27825 				freemsg(mp);
27826 			}
27827 			return;
27828 		case AR_ARP_EXTEND:
27829 			/*
27830 			 * The ARP module above us is capable of duplicate
27831 			 * address detection.  Old ATM drivers will not send
27832 			 * this message.
27833 			 */
27834 			ASSERT(q->q_next != NULL);
27835 			ill = (ill_t *)q->q_ptr;
27836 			ill->ill_arp_extend = B_TRUE;
27837 			freemsg(mp);
27838 			return;
27839 		default:
27840 			break;
27841 		}
27842 		break;
27843 	case M_PROTO:
27844 	case M_PCPROTO:
27845 		/*
27846 		 * The only PROTO messages we expect are copies of option
27847 		 * negotiation acknowledgements, AH and ESP bind requests
27848 		 * are also expected.
27849 		 */
27850 		switch (((union T_primitives *)mp->b_rptr)->type) {
27851 		case O_T_BIND_REQ:
27852 		case T_BIND_REQ: {
27853 			/* Request can get queued in bind */
27854 			if (connp == NULL) {
27855 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27856 				goto protonak;
27857 			}
27858 			/*
27859 			 * The transports except SCTP call ip_bind_{v4,v6}()
27860 			 * directly instead of a a putnext. SCTP doesn't
27861 			 * generate any T_BIND_REQ since it has its own
27862 			 * fanout data structures. However, ESP and AH
27863 			 * come in for regular binds; all other cases are
27864 			 * bind retries.
27865 			 */
27866 			ASSERT(!IPCL_IS_SCTP(connp));
27867 
27868 			/* Don't increment refcnt if this is a re-entry */
27869 			if (ipsq == NULL)
27870 				CONN_INC_REF(connp);
27871 
27872 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27873 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27874 			ASSERT(mp != NULL);
27875 
27876 			ASSERT(!IPCL_IS_TCP(connp));
27877 			ASSERT(!IPCL_IS_UDP(connp));
27878 			ASSERT(!IPCL_IS_RAWIP(connp));
27879 
27880 			/* The case of AH and ESP */
27881 			qreply(q, mp);
27882 			CONN_OPER_PENDING_DONE(connp);
27883 			return;
27884 		}
27885 		case T_SVR4_OPTMGMT_REQ:
27886 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27887 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27888 
27889 			if (connp == NULL) {
27890 				proto_str = "T_SVR4_OPTMGMT_REQ";
27891 				goto protonak;
27892 			}
27893 
27894 			if (!snmpcom_req(q, mp, ip_snmp_set,
27895 			    ip_snmp_get, cr)) {
27896 				/*
27897 				 * Call svr4_optcom_req so that it can
27898 				 * generate the ack. We don't come here
27899 				 * if this operation is being restarted.
27900 				 * ip_restart_optmgmt will drop the conn ref.
27901 				 * In the case of ipsec option after the ipsec
27902 				 * load is complete conn_restart_ipsec_waiter
27903 				 * drops the conn ref.
27904 				 */
27905 				ASSERT(ipsq == NULL);
27906 				CONN_INC_REF(connp);
27907 				if (ip_check_for_ipsec_opt(q, mp))
27908 					return;
27909 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj,
27910 				    B_FALSE);
27911 				if (err != EINPROGRESS) {
27912 					/* Operation is done */
27913 					CONN_OPER_PENDING_DONE(connp);
27914 				}
27915 			}
27916 			return;
27917 		case T_OPTMGMT_REQ:
27918 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27919 			/*
27920 			 * Note: No snmpcom_req support through new
27921 			 * T_OPTMGMT_REQ.
27922 			 * Call tpi_optcom_req so that it can
27923 			 * generate the ack.
27924 			 */
27925 			if (connp == NULL) {
27926 				proto_str = "T_OPTMGMT_REQ";
27927 				goto protonak;
27928 			}
27929 
27930 			ASSERT(ipsq == NULL);
27931 			/*
27932 			 * We don't come here for restart. ip_restart_optmgmt
27933 			 * will drop the conn ref. In the case of ipsec option
27934 			 * after the ipsec load is complete
27935 			 * conn_restart_ipsec_waiter drops the conn ref.
27936 			 */
27937 			CONN_INC_REF(connp);
27938 			if (ip_check_for_ipsec_opt(q, mp))
27939 				return;
27940 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj, B_FALSE);
27941 			if (err != EINPROGRESS) {
27942 				/* Operation is done */
27943 				CONN_OPER_PENDING_DONE(connp);
27944 			}
27945 			return;
27946 		case T_UNBIND_REQ:
27947 			if (connp == NULL) {
27948 				proto_str = "T_UNBIND_REQ";
27949 				goto protonak;
27950 			}
27951 			ip_unbind(Q_TO_CONN(q));
27952 			mp = mi_tpi_ok_ack_alloc(mp);
27953 			qreply(q, mp);
27954 			return;
27955 		default:
27956 			/*
27957 			 * Have to drop any DLPI messages coming down from
27958 			 * arp (such as an info_req which would cause ip
27959 			 * to receive an extra info_ack if it was passed
27960 			 * through.
27961 			 */
27962 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27963 			    (int)*(uint_t *)mp->b_rptr));
27964 			freemsg(mp);
27965 			return;
27966 		}
27967 		/* NOTREACHED */
27968 	case IRE_DB_TYPE: {
27969 		nce_t		*nce;
27970 		ill_t		*ill;
27971 		in6_addr_t	gw_addr_v6;
27972 
27973 
27974 		/*
27975 		 * This is a response back from a resolver.  It
27976 		 * consists of a message chain containing:
27977 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27978 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27979 		 * The LL_HDR_MBLK is the DLPI header to use to get
27980 		 * the attached packet, and subsequent ones for the
27981 		 * same destination, transmitted.
27982 		 */
27983 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27984 			break;
27985 		/*
27986 		 * First, check to make sure the resolution succeeded.
27987 		 * If it failed, the second mblk will be empty.
27988 		 * If it is, free the chain, dropping the packet.
27989 		 * (We must ire_delete the ire; that frees the ire mblk)
27990 		 * We're doing this now to support PVCs for ATM; it's
27991 		 * a partial xresolv implementation. When we fully implement
27992 		 * xresolv interfaces, instead of freeing everything here
27993 		 * we'll initiate neighbor discovery.
27994 		 *
27995 		 * For v4 (ARP and other external resolvers) the resolver
27996 		 * frees the message, so no check is needed. This check
27997 		 * is required, though, for a full xresolve implementation.
27998 		 * Including this code here now both shows how external
27999 		 * resolvers can NACK a resolution request using an
28000 		 * existing design that has no specific provisions for NACKs,
28001 		 * and also takes into account that the current non-ARP
28002 		 * external resolver has been coded to use this method of
28003 		 * NACKing for all IPv6 (xresolv) cases,
28004 		 * whether our xresolv implementation is complete or not.
28005 		 *
28006 		 */
28007 		ire = (ire_t *)mp->b_rptr;
28008 		ill = ire_to_ill(ire);
28009 		mp1 = mp->b_cont;		/* dl_unitdata_req */
28010 		if (mp1->b_rptr == mp1->b_wptr) {
28011 			if (ire->ire_ipversion == IPV6_VERSION) {
28012 				/*
28013 				 * XRESOLV interface.
28014 				 */
28015 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
28016 				mutex_enter(&ire->ire_lock);
28017 				gw_addr_v6 = ire->ire_gateway_addr_v6;
28018 				mutex_exit(&ire->ire_lock);
28019 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
28020 					nce = ndp_lookup_v6(ill,
28021 					    &ire->ire_addr_v6, B_FALSE);
28022 				} else {
28023 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
28024 					    B_FALSE);
28025 				}
28026 				if (nce != NULL) {
28027 					nce_resolv_failed(nce);
28028 					ndp_delete(nce);
28029 					NCE_REFRELE(nce);
28030 				}
28031 			}
28032 			mp->b_cont = NULL;
28033 			freemsg(mp1);		/* frees the pkt as well */
28034 			ASSERT(ire->ire_nce == NULL);
28035 			ire_delete((ire_t *)mp->b_rptr);
28036 			return;
28037 		}
28038 
28039 		/*
28040 		 * Split them into IRE_MBLK and pkt and feed it into
28041 		 * ire_add_then_send. Then in ire_add_then_send
28042 		 * the IRE will be added, and then the packet will be
28043 		 * run back through ip_wput. This time it will make
28044 		 * it to the wire.
28045 		 */
28046 		mp->b_cont = NULL;
28047 		mp = mp1->b_cont;		/* now, mp points to pkt */
28048 		mp1->b_cont = NULL;
28049 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
28050 		if (ire->ire_ipversion == IPV6_VERSION) {
28051 			/*
28052 			 * XRESOLV interface. Find the nce and put a copy
28053 			 * of the dl_unitdata_req in nce_res_mp
28054 			 */
28055 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
28056 			mutex_enter(&ire->ire_lock);
28057 			gw_addr_v6 = ire->ire_gateway_addr_v6;
28058 			mutex_exit(&ire->ire_lock);
28059 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
28060 				nce = ndp_lookup_v6(ill, &ire->ire_addr_v6,
28061 				    B_FALSE);
28062 			} else {
28063 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
28064 			}
28065 			if (nce != NULL) {
28066 				/*
28067 				 * We have to protect nce_res_mp here
28068 				 * from being accessed by other threads
28069 				 * while we change the mblk pointer.
28070 				 * Other functions will also lock the nce when
28071 				 * accessing nce_res_mp.
28072 				 *
28073 				 * The reason we change the mblk pointer
28074 				 * here rather than copying the resolved address
28075 				 * into the template is that, unlike with
28076 				 * ethernet, we have no guarantee that the
28077 				 * resolved address length will be
28078 				 * smaller than or equal to the lla length
28079 				 * with which the template was allocated,
28080 				 * (for ethernet, they're equal)
28081 				 * so we have to use the actual resolved
28082 				 * address mblk - which holds the real
28083 				 * dl_unitdata_req with the resolved address.
28084 				 *
28085 				 * Doing this is the same behavior as was
28086 				 * previously used in the v4 ARP case.
28087 				 */
28088 				mutex_enter(&nce->nce_lock);
28089 				if (nce->nce_res_mp != NULL)
28090 					freemsg(nce->nce_res_mp);
28091 				nce->nce_res_mp = mp1;
28092 				mutex_exit(&nce->nce_lock);
28093 				/*
28094 				 * We do a fastpath probe here because
28095 				 * we have resolved the address without
28096 				 * using Neighbor Discovery.
28097 				 * In the non-XRESOLV v6 case, the fastpath
28098 				 * probe is done right after neighbor
28099 				 * discovery completes.
28100 				 */
28101 				if (nce->nce_res_mp != NULL) {
28102 					int res;
28103 					nce_fastpath_list_add(nce);
28104 					res = ill_fastpath_probe(ill,
28105 					    nce->nce_res_mp);
28106 					if (res != 0 && res != EAGAIN)
28107 						nce_fastpath_list_delete(nce);
28108 				}
28109 
28110 				ire_add_then_send(q, ire, mp);
28111 				/*
28112 				 * Now we have to clean out any packets
28113 				 * that may have been queued on the nce
28114 				 * while it was waiting for address resolution
28115 				 * to complete.
28116 				 */
28117 				mutex_enter(&nce->nce_lock);
28118 				mp1 = nce->nce_qd_mp;
28119 				nce->nce_qd_mp = NULL;
28120 				mutex_exit(&nce->nce_lock);
28121 				while (mp1 != NULL) {
28122 					mblk_t *nxt_mp;
28123 					queue_t *fwdq = NULL;
28124 					ill_t   *inbound_ill;
28125 					uint_t ifindex;
28126 
28127 					nxt_mp = mp1->b_next;
28128 					mp1->b_next = NULL;
28129 					/*
28130 					 * Retrieve ifindex stored in
28131 					 * ip_rput_data_v6()
28132 					 */
28133 					ifindex =
28134 					    (uint_t)(uintptr_t)mp1->b_prev;
28135 					inbound_ill =
28136 					    ill_lookup_on_ifindex(ifindex,
28137 					    B_TRUE, NULL, NULL, NULL,
28138 					    NULL, ipst);
28139 					mp1->b_prev = NULL;
28140 					if (inbound_ill != NULL)
28141 						fwdq = inbound_ill->ill_rq;
28142 
28143 					if (fwdq != NULL) {
28144 						put(fwdq, mp1);
28145 						ill_refrele(inbound_ill);
28146 					} else
28147 						put(WR(ill->ill_rq), mp1);
28148 					mp1 = nxt_mp;
28149 				}
28150 				NCE_REFRELE(nce);
28151 			} else {	/* nce is NULL; clean up */
28152 				ire_delete(ire);
28153 				freemsg(mp);
28154 				freemsg(mp1);
28155 				return;
28156 			}
28157 		} else {
28158 			nce_t *arpce;
28159 			/*
28160 			 * Link layer resolution succeeded. Recompute the
28161 			 * ire_nce.
28162 			 */
28163 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
28164 			if ((arpce = ndp_lookup_v4(ill,
28165 			    (ire->ire_gateway_addr != INADDR_ANY ?
28166 			    &ire->ire_gateway_addr : &ire->ire_addr),
28167 			    B_FALSE)) == NULL) {
28168 				freeb(ire->ire_mp);
28169 				freeb(mp1);
28170 				freemsg(mp);
28171 				return;
28172 			}
28173 			mutex_enter(&arpce->nce_lock);
28174 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
28175 			if (arpce->nce_state == ND_REACHABLE) {
28176 				/*
28177 				 * Someone resolved this before us;
28178 				 * cleanup the res_mp. Since ire has
28179 				 * not been added yet, the call to ire_add_v4
28180 				 * from ire_add_then_send (when a dup is
28181 				 * detected) will clean up the ire.
28182 				 */
28183 				freeb(mp1);
28184 			} else {
28185 				ASSERT(arpce->nce_res_mp == NULL);
28186 				arpce->nce_res_mp = mp1;
28187 				arpce->nce_state = ND_REACHABLE;
28188 			}
28189 			mutex_exit(&arpce->nce_lock);
28190 			if (ire->ire_marks & IRE_MARK_NOADD) {
28191 				/*
28192 				 * this ire will not be added to the ire
28193 				 * cache table, so we can set the ire_nce
28194 				 * here, as there are no atomicity constraints.
28195 				 */
28196 				ire->ire_nce = arpce;
28197 				/*
28198 				 * We are associating this nce with the ire
28199 				 * so change the nce ref taken in
28200 				 * ndp_lookup_v4() from
28201 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
28202 				 */
28203 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
28204 			} else {
28205 				NCE_REFRELE(arpce);
28206 			}
28207 			ire_add_then_send(q, ire, mp);
28208 		}
28209 		return;	/* All is well, the packet has been sent. */
28210 	}
28211 	case IRE_ARPRESOLVE_TYPE: {
28212 
28213 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
28214 			break;
28215 		mp1 = mp->b_cont;		/* dl_unitdata_req */
28216 		mp->b_cont = NULL;
28217 		/*
28218 		 * First, check to make sure the resolution succeeded.
28219 		 * If it failed, the second mblk will be empty.
28220 		 */
28221 		if (mp1->b_rptr == mp1->b_wptr) {
28222 			/* cleanup  the incomplete ire, free queued packets */
28223 			freemsg(mp); /* fake ire */
28224 			freeb(mp1);  /* dl_unitdata response */
28225 			return;
28226 		}
28227 
28228 		/*
28229 		 * Update any incomplete nce_t found. We search the ctable
28230 		 * and find the nce from the ire->ire_nce because we need
28231 		 * to pass the ire to ip_xmit_v4 later, and can find both
28232 		 * ire and nce in one lookup.
28233 		 */
28234 		fake_ire = (ire_t *)mp->b_rptr;
28235 
28236 		/*
28237 		 * By the time we come back here from ARP the incomplete ire
28238 		 * created in ire_forward() could have been removed. We use
28239 		 * the parameters stored in the fake_ire to specify the real
28240 		 * ire as explicitly as possible. This avoids problems when
28241 		 * IPMP groups are configured as an ipif can 'float'
28242 		 * across several ill queues. We can be confident that the
28243 		 * the inability to find an ire is because it no longer exists.
28244 		 */
28245 		ill = ill_lookup_on_ifindex(fake_ire->ire_ipif_ifindex, B_FALSE,
28246 		    NULL, NULL, NULL, NULL, ipst);
28247 		if (ill == NULL) {
28248 			ip1dbg(("ill for incomplete ire vanished\n"));
28249 			freemsg(mp); /* fake ire */
28250 			freeb(mp1);  /* dl_unitdata response */
28251 			return;
28252 		}
28253 
28254 		/* Get the outgoing ipif */
28255 		mutex_enter(&ill->ill_lock);
28256 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
28257 		if (ipif == NULL) {
28258 			mutex_exit(&ill->ill_lock);
28259 			ill_refrele(ill);
28260 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
28261 			freemsg(mp); /* fake_ire */
28262 			freeb(mp1);  /* dl_unitdata response */
28263 			return;
28264 		}
28265 
28266 		ipif_refhold_locked(ipif);
28267 		mutex_exit(&ill->ill_lock);
28268 		ill_refrele(ill);
28269 		ire = ire_arpresolve_lookup(fake_ire->ire_addr,
28270 		    fake_ire->ire_gateway_addr, ipif, fake_ire->ire_zoneid,
28271 		    ipst, ((ill_t *)q->q_ptr)->ill_wq);
28272 		ipif_refrele(ipif);
28273 		if (ire == NULL) {
28274 			/*
28275 			 * no ire was found; check if there is an nce
28276 			 * for this lookup; if it has no ire's pointing at it
28277 			 * cleanup.
28278 			 */
28279 			if ((nce = ndp_lookup_v4(q->q_ptr,
28280 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
28281 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
28282 			    B_FALSE)) != NULL) {
28283 				/*
28284 				 * cleanup:
28285 				 * We check for refcnt 2 (one for the nce
28286 				 * hash list + 1 for the ref taken by
28287 				 * ndp_lookup_v4) to check that there are
28288 				 * no ire's pointing at the nce.
28289 				 */
28290 				if (nce->nce_refcnt == 2)
28291 					ndp_delete(nce);
28292 				NCE_REFRELE(nce);
28293 			}
28294 			freeb(mp1);  /* dl_unitdata response */
28295 			freemsg(mp); /* fake ire */
28296 			return;
28297 		}
28298 		nce = ire->ire_nce;
28299 		DTRACE_PROBE2(ire__arpresolve__type,
28300 		    ire_t *, ire, nce_t *, nce);
28301 		ASSERT(nce->nce_state != ND_INITIAL);
28302 		mutex_enter(&nce->nce_lock);
28303 		nce->nce_last = TICK_TO_MSEC(lbolt64);
28304 		if (nce->nce_state == ND_REACHABLE) {
28305 			/*
28306 			 * Someone resolved this before us;
28307 			 * our response is not needed any more.
28308 			 */
28309 			mutex_exit(&nce->nce_lock);
28310 			freeb(mp1);  /* dl_unitdata response */
28311 		} else {
28312 			ASSERT(nce->nce_res_mp == NULL);
28313 			nce->nce_res_mp = mp1;
28314 			nce->nce_state = ND_REACHABLE;
28315 			mutex_exit(&nce->nce_lock);
28316 			nce_fastpath(nce);
28317 		}
28318 		/*
28319 		 * The cached nce_t has been updated to be reachable;
28320 		 * Clear the IRE_MARK_UNCACHED flag and free the fake_ire.
28321 		 */
28322 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
28323 		freemsg(mp);
28324 		/*
28325 		 * send out queued packets.
28326 		 */
28327 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
28328 
28329 		IRE_REFRELE(ire);
28330 		return;
28331 	}
28332 	default:
28333 		break;
28334 	}
28335 	if (q->q_next) {
28336 		putnext(q, mp);
28337 	} else
28338 		freemsg(mp);
28339 	return;
28340 
28341 protonak:
28342 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
28343 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
28344 		qreply(q, mp);
28345 }
28346 
28347 /*
28348  * Process IP options in an outbound packet.  Modify the destination if there
28349  * is a source route option.
28350  * Returns non-zero if something fails in which case an ICMP error has been
28351  * sent and mp freed.
28352  */
28353 static int
28354 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
28355     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
28356 {
28357 	ipoptp_t	opts;
28358 	uchar_t		*opt;
28359 	uint8_t		optval;
28360 	uint8_t		optlen;
28361 	ipaddr_t	dst;
28362 	intptr_t	code = 0;
28363 	mblk_t		*mp;
28364 	ire_t		*ire = NULL;
28365 
28366 	ip2dbg(("ip_wput_options\n"));
28367 	mp = ipsec_mp;
28368 	if (mctl_present) {
28369 		mp = ipsec_mp->b_cont;
28370 	}
28371 
28372 	dst = ipha->ipha_dst;
28373 	for (optval = ipoptp_first(&opts, ipha);
28374 	    optval != IPOPT_EOL;
28375 	    optval = ipoptp_next(&opts)) {
28376 		opt = opts.ipoptp_cur;
28377 		optlen = opts.ipoptp_len;
28378 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
28379 		    optval, optlen));
28380 		switch (optval) {
28381 			uint32_t off;
28382 		case IPOPT_SSRR:
28383 		case IPOPT_LSRR:
28384 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28385 				ip1dbg((
28386 				    "ip_wput_options: bad option offset\n"));
28387 				code = (char *)&opt[IPOPT_OLEN] -
28388 				    (char *)ipha;
28389 				goto param_prob;
28390 			}
28391 			off = opt[IPOPT_OFFSET];
28392 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
28393 			    ntohl(dst)));
28394 			/*
28395 			 * For strict: verify that dst is directly
28396 			 * reachable.
28397 			 */
28398 			if (optval == IPOPT_SSRR) {
28399 				ire = ire_ftable_lookup(dst, 0, 0,
28400 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
28401 				    MBLK_GETLABEL(mp),
28402 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
28403 				if (ire == NULL) {
28404 					ip1dbg(("ip_wput_options: SSRR not"
28405 					    " directly reachable: 0x%x\n",
28406 					    ntohl(dst)));
28407 					goto bad_src_route;
28408 				}
28409 				ire_refrele(ire);
28410 			}
28411 			break;
28412 		case IPOPT_RR:
28413 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28414 				ip1dbg((
28415 				    "ip_wput_options: bad option offset\n"));
28416 				code = (char *)&opt[IPOPT_OLEN] -
28417 				    (char *)ipha;
28418 				goto param_prob;
28419 			}
28420 			break;
28421 		case IPOPT_TS:
28422 			/*
28423 			 * Verify that length >=5 and that there is either
28424 			 * room for another timestamp or that the overflow
28425 			 * counter is not maxed out.
28426 			 */
28427 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
28428 			if (optlen < IPOPT_MINLEN_IT) {
28429 				goto param_prob;
28430 			}
28431 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28432 				ip1dbg((
28433 				    "ip_wput_options: bad option offset\n"));
28434 				code = (char *)&opt[IPOPT_OFFSET] -
28435 				    (char *)ipha;
28436 				goto param_prob;
28437 			}
28438 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
28439 			case IPOPT_TS_TSONLY:
28440 				off = IPOPT_TS_TIMELEN;
28441 				break;
28442 			case IPOPT_TS_TSANDADDR:
28443 			case IPOPT_TS_PRESPEC:
28444 			case IPOPT_TS_PRESPEC_RFC791:
28445 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
28446 				break;
28447 			default:
28448 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
28449 				    (char *)ipha;
28450 				goto param_prob;
28451 			}
28452 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
28453 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
28454 				/*
28455 				 * No room and the overflow counter is 15
28456 				 * already.
28457 				 */
28458 				goto param_prob;
28459 			}
28460 			break;
28461 		}
28462 	}
28463 
28464 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
28465 		return (0);
28466 
28467 	ip1dbg(("ip_wput_options: error processing IP options."));
28468 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
28469 
28470 param_prob:
28471 	/*
28472 	 * Since ip_wput() isn't close to finished, we fill
28473 	 * in enough of the header for credible error reporting.
28474 	 */
28475 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28476 		/* Failed */
28477 		freemsg(ipsec_mp);
28478 		return (-1);
28479 	}
28480 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
28481 	return (-1);
28482 
28483 bad_src_route:
28484 	/*
28485 	 * Since ip_wput() isn't close to finished, we fill
28486 	 * in enough of the header for credible error reporting.
28487 	 */
28488 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28489 		/* Failed */
28490 		freemsg(ipsec_mp);
28491 		return (-1);
28492 	}
28493 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
28494 	return (-1);
28495 }
28496 
28497 /*
28498  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
28499  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
28500  * thru /etc/system.
28501  */
28502 #define	CONN_MAXDRAINCNT	64
28503 
28504 static void
28505 conn_drain_init(ip_stack_t *ipst)
28506 {
28507 	int i;
28508 
28509 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
28510 
28511 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
28512 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
28513 		/*
28514 		 * Default value of the number of drainers is the
28515 		 * number of cpus, subject to maximum of 8 drainers.
28516 		 */
28517 		if (boot_max_ncpus != -1)
28518 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
28519 		else
28520 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
28521 	}
28522 
28523 	ipst->ips_conn_drain_list = kmem_zalloc(ipst->ips_conn_drain_list_cnt *
28524 	    sizeof (idl_t), KM_SLEEP);
28525 
28526 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28527 		mutex_init(&ipst->ips_conn_drain_list[i].idl_lock, NULL,
28528 		    MUTEX_DEFAULT, NULL);
28529 	}
28530 }
28531 
28532 static void
28533 conn_drain_fini(ip_stack_t *ipst)
28534 {
28535 	int i;
28536 
28537 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++)
28538 		mutex_destroy(&ipst->ips_conn_drain_list[i].idl_lock);
28539 	kmem_free(ipst->ips_conn_drain_list,
28540 	    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
28541 	ipst->ips_conn_drain_list = NULL;
28542 }
28543 
28544 /*
28545  * Note: For an overview of how flowcontrol is handled in IP please see the
28546  * IP Flowcontrol notes at the top of this file.
28547  *
28548  * Flow control has blocked us from proceeding. Insert the given conn in one
28549  * of the conn drain lists. These conn wq's will be qenabled later on when
28550  * STREAMS flow control does a backenable. conn_walk_drain will enable
28551  * the first conn in each of these drain lists. Each of these qenabled conns
28552  * in turn enables the next in the list, after it runs, or when it closes,
28553  * thus sustaining the drain process.
28554  *
28555  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
28556  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
28557  * running at any time, on a given conn, since there can be only 1 service proc
28558  * running on a queue at any time.
28559  */
28560 void
28561 conn_drain_insert(conn_t *connp)
28562 {
28563 	idl_t	*idl;
28564 	uint_t	index;
28565 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28566 
28567 	mutex_enter(&connp->conn_lock);
28568 	if (connp->conn_state_flags & CONN_CLOSING) {
28569 		/*
28570 		 * The conn is closing as a result of which CONN_CLOSING
28571 		 * is set. Return.
28572 		 */
28573 		mutex_exit(&connp->conn_lock);
28574 		return;
28575 	} else if (connp->conn_idl == NULL) {
28576 		/*
28577 		 * Assign the next drain list round robin. We dont' use
28578 		 * a lock, and thus it may not be strictly round robin.
28579 		 * Atomicity of load/stores is enough to make sure that
28580 		 * conn_drain_list_index is always within bounds.
28581 		 */
28582 		index = ipst->ips_conn_drain_list_index;
28583 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
28584 		connp->conn_idl = &ipst->ips_conn_drain_list[index];
28585 		index++;
28586 		if (index == ipst->ips_conn_drain_list_cnt)
28587 			index = 0;
28588 		ipst->ips_conn_drain_list_index = index;
28589 	}
28590 	mutex_exit(&connp->conn_lock);
28591 
28592 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28593 	if ((connp->conn_drain_prev != NULL) ||
28594 	    (connp->conn_state_flags & CONN_CLOSING)) {
28595 		/*
28596 		 * The conn is already in the drain list, OR
28597 		 * the conn is closing. We need to check again for
28598 		 * the closing case again since close can happen
28599 		 * after we drop the conn_lock, and before we
28600 		 * acquire the CONN_DRAIN_LIST_LOCK.
28601 		 */
28602 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28603 		return;
28604 	} else {
28605 		idl = connp->conn_idl;
28606 	}
28607 
28608 	/*
28609 	 * The conn is not in the drain list. Insert it at the
28610 	 * tail of the drain list. The drain list is circular
28611 	 * and doubly linked. idl_conn points to the 1st element
28612 	 * in the list.
28613 	 */
28614 	if (idl->idl_conn == NULL) {
28615 		idl->idl_conn = connp;
28616 		connp->conn_drain_next = connp;
28617 		connp->conn_drain_prev = connp;
28618 	} else {
28619 		conn_t *head = idl->idl_conn;
28620 
28621 		connp->conn_drain_next = head;
28622 		connp->conn_drain_prev = head->conn_drain_prev;
28623 		head->conn_drain_prev->conn_drain_next = connp;
28624 		head->conn_drain_prev = connp;
28625 	}
28626 	/*
28627 	 * For non streams based sockets assert flow control.
28628 	 */
28629 	(*connp->conn_upcalls->su_txq_full)
28630 	    (connp->conn_upper_handle, B_TRUE);
28631 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28632 }
28633 
28634 /*
28635  * This conn is closing, and we are called from ip_close. OR
28636  * This conn has been serviced by ip_wsrv, and we need to do the tail
28637  * processing.
28638  * If this conn is part of the drain list, we may need to sustain the drain
28639  * process by qenabling the next conn in the drain list. We may also need to
28640  * remove this conn from the list, if it is done.
28641  */
28642 static void
28643 conn_drain_tail(conn_t *connp, boolean_t closing)
28644 {
28645 	idl_t *idl;
28646 
28647 	/*
28648 	 * connp->conn_idl is stable at this point, and no lock is needed
28649 	 * to check it. If we are called from ip_close, close has already
28650 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28651 	 * called us only because conn_idl is non-null. If we are called thru
28652 	 * service, conn_idl could be null, but it cannot change because
28653 	 * service is single-threaded per queue, and there cannot be another
28654 	 * instance of service trying to call conn_drain_insert on this conn
28655 	 * now.
28656 	 */
28657 	ASSERT(!closing || (connp->conn_idl != NULL));
28658 
28659 	/*
28660 	 * If connp->conn_idl is null, the conn has not been inserted into any
28661 	 * drain list even once since creation of the conn. Just return.
28662 	 */
28663 	if (connp->conn_idl == NULL)
28664 		return;
28665 
28666 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28667 
28668 	if (connp->conn_drain_prev == NULL) {
28669 		/* This conn is currently not in the drain list.  */
28670 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28671 		return;
28672 	}
28673 	idl = connp->conn_idl;
28674 	if (idl->idl_conn_draining == connp) {
28675 		/*
28676 		 * This conn is the current drainer. If this is the last conn
28677 		 * in the drain list, we need to do more checks, in the 'if'
28678 		 * below. Otherwwise we need to just qenable the next conn,
28679 		 * to sustain the draining, and is handled in the 'else'
28680 		 * below.
28681 		 */
28682 		if (connp->conn_drain_next == idl->idl_conn) {
28683 			/*
28684 			 * This conn is the last in this list. This round
28685 			 * of draining is complete. If idl_repeat is set,
28686 			 * it means another flow enabling has happened from
28687 			 * the driver/streams and we need to another round
28688 			 * of draining.
28689 			 * If there are more than 2 conns in the drain list,
28690 			 * do a left rotate by 1, so that all conns except the
28691 			 * conn at the head move towards the head by 1, and the
28692 			 * the conn at the head goes to the tail. This attempts
28693 			 * a more even share for all queues that are being
28694 			 * drained.
28695 			 */
28696 			if ((connp->conn_drain_next != connp) &&
28697 			    (idl->idl_conn->conn_drain_next != connp)) {
28698 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28699 			}
28700 			if (idl->idl_repeat) {
28701 				qenable(idl->idl_conn->conn_wq);
28702 				idl->idl_conn_draining = idl->idl_conn;
28703 				idl->idl_repeat = 0;
28704 			} else {
28705 				idl->idl_conn_draining = NULL;
28706 			}
28707 		} else {
28708 			/*
28709 			 * If the next queue that we are now qenable'ing,
28710 			 * is closing, it will remove itself from this list
28711 			 * and qenable the subsequent queue in ip_close().
28712 			 * Serialization is acheived thru idl_lock.
28713 			 */
28714 			qenable(connp->conn_drain_next->conn_wq);
28715 			idl->idl_conn_draining = connp->conn_drain_next;
28716 		}
28717 	}
28718 	if (!connp->conn_did_putbq || closing) {
28719 		/*
28720 		 * Remove ourself from the drain list, if we did not do
28721 		 * a putbq, or if the conn is closing.
28722 		 * Note: It is possible that q->q_first is non-null. It means
28723 		 * that these messages landed after we did a enableok() in
28724 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28725 		 * service them.
28726 		 */
28727 		if (connp->conn_drain_next == connp) {
28728 			/* Singleton in the list */
28729 			ASSERT(connp->conn_drain_prev == connp);
28730 			idl->idl_conn = NULL;
28731 			idl->idl_conn_draining = NULL;
28732 		} else {
28733 			connp->conn_drain_prev->conn_drain_next =
28734 			    connp->conn_drain_next;
28735 			connp->conn_drain_next->conn_drain_prev =
28736 			    connp->conn_drain_prev;
28737 			if (idl->idl_conn == connp)
28738 				idl->idl_conn = connp->conn_drain_next;
28739 			ASSERT(idl->idl_conn_draining != connp);
28740 
28741 		}
28742 		connp->conn_drain_next = NULL;
28743 		connp->conn_drain_prev = NULL;
28744 
28745 		/*
28746 		 * For non streams based sockets open up flow control.
28747 		 */
28748 		if (IPCL_IS_NONSTR(connp)) {
28749 			(*connp->conn_upcalls->su_txq_full)
28750 			    (connp->conn_upper_handle, B_FALSE);
28751 		}
28752 	}
28753 
28754 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28755 }
28756 
28757 /*
28758  * Write service routine. Shared perimeter entry point.
28759  * ip_wsrv can be called in any of the following ways.
28760  * 1. The device queue's messages has fallen below the low water mark
28761  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28762  *    the drain lists and backenable the first conn in each list.
28763  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28764  *    qenabled non-tcp upper layers. We start dequeing messages and call
28765  *    ip_wput for each message.
28766  */
28767 
28768 void
28769 ip_wsrv(queue_t *q)
28770 {
28771 	conn_t	*connp;
28772 	ill_t	*ill;
28773 	mblk_t	*mp;
28774 
28775 	if (q->q_next) {
28776 		ill = (ill_t *)q->q_ptr;
28777 		if (ill->ill_state_flags == 0) {
28778 			/*
28779 			 * The device flow control has opened up.
28780 			 * Walk through conn drain lists and qenable the
28781 			 * first conn in each list. This makes sense only
28782 			 * if the stream is fully plumbed and setup.
28783 			 * Hence the if check above.
28784 			 */
28785 			ip1dbg(("ip_wsrv: walking\n"));
28786 			conn_walk_drain(ill->ill_ipst);
28787 		}
28788 		return;
28789 	}
28790 
28791 	connp = Q_TO_CONN(q);
28792 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28793 
28794 	/*
28795 	 * 1. Set conn_draining flag to signal that service is active.
28796 	 *
28797 	 * 2. ip_output determines whether it has been called from service,
28798 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28799 	 *    has been called from service.
28800 	 *
28801 	 * 3. Message ordering is preserved by the following logic.
28802 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28803 	 *    the message at the tail, if conn_draining is set (i.e. service
28804 	 *    is running) or if q->q_first is non-null.
28805 	 *
28806 	 *    ii. If ip_output is called from service, and if ip_output cannot
28807 	 *    putnext due to flow control, it does a putbq.
28808 	 *
28809 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28810 	 *    (causing an infinite loop).
28811 	 */
28812 	ASSERT(!connp->conn_did_putbq);
28813 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28814 		connp->conn_draining = 1;
28815 		noenable(q);
28816 		while ((mp = getq(q)) != NULL) {
28817 			ASSERT(CONN_Q(q));
28818 
28819 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28820 			if (connp->conn_did_putbq) {
28821 				/* ip_wput did a putbq */
28822 				break;
28823 			}
28824 		}
28825 		/*
28826 		 * At this point, a thread coming down from top, calling
28827 		 * ip_wput, may end up queueing the message. We have not yet
28828 		 * enabled the queue, so ip_wsrv won't be called again.
28829 		 * To avoid this race, check q->q_first again (in the loop)
28830 		 * If the other thread queued the message before we call
28831 		 * enableok(), we will catch it in the q->q_first check.
28832 		 * If the other thread queues the message after we call
28833 		 * enableok(), ip_wsrv will be called again by STREAMS.
28834 		 */
28835 		connp->conn_draining = 0;
28836 		enableok(q);
28837 
28838 	}
28839 
28840 	/* Enable the next conn for draining */
28841 	conn_drain_tail(connp, B_FALSE);
28842 
28843 	connp->conn_did_putbq = 0;
28844 }
28845 
28846 /*
28847  * Callback to disable flow control in IP.
28848  *
28849  * This is a mac client callback added when the DLD_CAPAB_DIRECT capability
28850  * is enabled.
28851  *
28852  * When MAC_TX() is not able to send any more packets, dld sets its queue
28853  * to QFULL and enable the STREAMS flow control. Later, when the underlying
28854  * driver is able to continue to send packets, it calls mac_tx_(ring_)update()
28855  * function and wakes up corresponding mac worker threads, which in turn
28856  * calls this callback function, and disables flow control.
28857  */
28858 /* ARGSUSED */
28859 void
28860 ill_flow_enable(void *ill, ip_mac_tx_cookie_t cookie)
28861 {
28862 	qenable(((ill_t *)ill)->ill_wq);
28863 }
28864 
28865 /*
28866  * Walk the list of all conn's calling the function provided with the
28867  * specified argument for each.	 Note that this only walks conn's that
28868  * have been bound.
28869  * Applies to both IPv4 and IPv6.
28870  */
28871 static void
28872 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid, ip_stack_t *ipst)
28873 {
28874 	conn_walk_fanout_table(ipst->ips_ipcl_udp_fanout,
28875 	    ipst->ips_ipcl_udp_fanout_size,
28876 	    func, arg, zoneid);
28877 	conn_walk_fanout_table(ipst->ips_ipcl_conn_fanout,
28878 	    ipst->ips_ipcl_conn_fanout_size,
28879 	    func, arg, zoneid);
28880 	conn_walk_fanout_table(ipst->ips_ipcl_bind_fanout,
28881 	    ipst->ips_ipcl_bind_fanout_size,
28882 	    func, arg, zoneid);
28883 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout,
28884 	    IPPROTO_MAX, func, arg, zoneid);
28885 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout_v6,
28886 	    IPPROTO_MAX, func, arg, zoneid);
28887 }
28888 
28889 /*
28890  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28891  * of conns that need to be drained, check if drain is already in progress.
28892  * If so set the idl_repeat bit, indicating that the last conn in the list
28893  * needs to reinitiate the drain once again, for the list. If drain is not
28894  * in progress for the list, initiate the draining, by qenabling the 1st
28895  * conn in the list. The drain is self-sustaining, each qenabled conn will
28896  * in turn qenable the next conn, when it is done/blocked/closing.
28897  */
28898 static void
28899 conn_walk_drain(ip_stack_t *ipst)
28900 {
28901 	int i;
28902 	idl_t *idl;
28903 
28904 	IP_STAT(ipst, ip_conn_walk_drain);
28905 
28906 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28907 		idl = &ipst->ips_conn_drain_list[i];
28908 		mutex_enter(&idl->idl_lock);
28909 		if (idl->idl_conn == NULL) {
28910 			mutex_exit(&idl->idl_lock);
28911 			continue;
28912 		}
28913 		/*
28914 		 * If this list is not being drained currently by
28915 		 * an ip_wsrv thread, start the process.
28916 		 */
28917 		if (idl->idl_conn_draining == NULL) {
28918 			ASSERT(idl->idl_repeat == 0);
28919 			qenable(idl->idl_conn->conn_wq);
28920 			idl->idl_conn_draining = idl->idl_conn;
28921 		} else {
28922 			idl->idl_repeat = 1;
28923 		}
28924 		mutex_exit(&idl->idl_lock);
28925 	}
28926 }
28927 
28928 /*
28929  * Walk an conn hash table of `count' buckets, calling func for each entry.
28930  */
28931 static void
28932 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
28933     zoneid_t zoneid)
28934 {
28935 	conn_t	*connp;
28936 
28937 	while (count-- > 0) {
28938 		mutex_enter(&connfp->connf_lock);
28939 		for (connp = connfp->connf_head; connp != NULL;
28940 		    connp = connp->conn_next) {
28941 			if (zoneid == GLOBAL_ZONEID ||
28942 			    zoneid == connp->conn_zoneid) {
28943 				CONN_INC_REF(connp);
28944 				mutex_exit(&connfp->connf_lock);
28945 				(*func)(connp, arg);
28946 				mutex_enter(&connfp->connf_lock);
28947 				CONN_DEC_REF(connp);
28948 			}
28949 		}
28950 		mutex_exit(&connfp->connf_lock);
28951 		connfp++;
28952 	}
28953 }
28954 
28955 /* conn_walk_fanout routine invoked for ip_conn_report for each conn. */
28956 static void
28957 conn_report1(conn_t *connp, void *mp)
28958 {
28959 	char	buf1[INET6_ADDRSTRLEN];
28960 	char	buf2[INET6_ADDRSTRLEN];
28961 	uint_t	print_len, buf_len;
28962 
28963 	ASSERT(connp != NULL);
28964 
28965 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
28966 	if (buf_len <= 0)
28967 		return;
28968 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1));
28969 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2));
28970 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
28971 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
28972 	    "%5d %s/%05d %s/%05d\n",
28973 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
28974 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
28975 	    buf1, connp->conn_lport,
28976 	    buf2, connp->conn_fport);
28977 	if (print_len < buf_len) {
28978 		((mblk_t *)mp)->b_wptr += print_len;
28979 	} else {
28980 		((mblk_t *)mp)->b_wptr += buf_len;
28981 	}
28982 }
28983 
28984 /*
28985  * Named Dispatch routine to produce a formatted report on all conns
28986  * that are listed in one of the fanout tables.
28987  * This report is accessed by using the ndd utility to "get" ND variable
28988  * "ip_conn_status".
28989  */
28990 /* ARGSUSED */
28991 static int
28992 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
28993 {
28994 	conn_t *connp = Q_TO_CONN(q);
28995 
28996 	(void) mi_mpprintf(mp,
28997 	    "CONN      " MI_COL_HDRPAD_STR
28998 	    "rfq      " MI_COL_HDRPAD_STR
28999 	    "stq      " MI_COL_HDRPAD_STR
29000 	    " zone local		 remote");
29001 
29002 	/*
29003 	 * Because of the ndd constraint, at most we can have 64K buffer
29004 	 * to put in all conn info.  So to be more efficient, just
29005 	 * allocate a 64K buffer here, assuming we need that large buffer.
29006 	 * This should be OK as only privileged processes can do ndd /dev/ip.
29007 	 */
29008 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
29009 		/* The following may work even if we cannot get a large buf. */
29010 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
29011 		return (0);
29012 	}
29013 
29014 	conn_walk_fanout(conn_report1, mp->b_cont, connp->conn_zoneid,
29015 	    connp->conn_netstack->netstack_ip);
29016 	return (0);
29017 }
29018 
29019 /*
29020  * Determine if the ill and multicast aspects of that packets
29021  * "matches" the conn.
29022  */
29023 boolean_t
29024 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
29025     zoneid_t zoneid)
29026 {
29027 	ill_t *in_ill;
29028 	boolean_t found;
29029 	ipif_t *ipif;
29030 	ire_t *ire;
29031 	ipaddr_t dst, src;
29032 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
29033 
29034 	dst = ipha->ipha_dst;
29035 	src = ipha->ipha_src;
29036 
29037 	/*
29038 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
29039 	 * unicast, broadcast and multicast reception to
29040 	 * conn_incoming_ill. conn_wantpacket itself is called
29041 	 * only for BROADCAST and multicast.
29042 	 *
29043 	 * 1) ip_rput supresses duplicate broadcasts if the ill
29044 	 *    is part of a group. Hence, we should be receiving
29045 	 *    just one copy of broadcast for the whole group.
29046 	 *    Thus, if it is part of the group the packet could
29047 	 *    come on any ill of the group and hence we need a
29048 	 *    match on the group. Otherwise, match on ill should
29049 	 *    be sufficient.
29050 	 *
29051 	 * 2) ip_rput does not suppress duplicate multicast packets.
29052 	 *    If there are two interfaces in a ill group and we have
29053 	 *    2 applications (conns) joined a multicast group G on
29054 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
29055 	 *    will give us two packets because we join G on both the
29056 	 *    interfaces rather than nominating just one interface
29057 	 *    for receiving multicast like broadcast above. So,
29058 	 *    we have to call ilg_lookup_ill to filter out duplicate
29059 	 *    copies, if ill is part of a group.
29060 	 */
29061 	in_ill = connp->conn_incoming_ill;
29062 	if (in_ill != NULL) {
29063 		if (in_ill->ill_group == NULL) {
29064 			if (in_ill != ill)
29065 				return (B_FALSE);
29066 		} else if (in_ill->ill_group != ill->ill_group) {
29067 			return (B_FALSE);
29068 		}
29069 	}
29070 
29071 	if (!CLASSD(dst)) {
29072 		if (IPCL_ZONE_MATCH(connp, zoneid))
29073 			return (B_TRUE);
29074 		/*
29075 		 * The conn is in a different zone; we need to check that this
29076 		 * broadcast address is configured in the application's zone and
29077 		 * on one ill in the group.
29078 		 */
29079 		ipif = ipif_get_next_ipif(NULL, ill);
29080 		if (ipif == NULL)
29081 			return (B_FALSE);
29082 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
29083 		    connp->conn_zoneid, NULL,
29084 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
29085 		ipif_refrele(ipif);
29086 		if (ire != NULL) {
29087 			ire_refrele(ire);
29088 			return (B_TRUE);
29089 		} else {
29090 			return (B_FALSE);
29091 		}
29092 	}
29093 
29094 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
29095 	    connp->conn_zoneid == zoneid) {
29096 		/*
29097 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
29098 		 * disabled, therefore we don't dispatch the multicast packet to
29099 		 * the sending zone.
29100 		 */
29101 		return (B_FALSE);
29102 	}
29103 
29104 	if (IS_LOOPBACK(ill) && connp->conn_zoneid != zoneid) {
29105 		/*
29106 		 * Multicast packet on the loopback interface: we only match
29107 		 * conns who joined the group in the specified zone.
29108 		 */
29109 		return (B_FALSE);
29110 	}
29111 
29112 	if (connp->conn_multi_router) {
29113 		/* multicast packet and multicast router socket: send up */
29114 		return (B_TRUE);
29115 	}
29116 
29117 	mutex_enter(&connp->conn_lock);
29118 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
29119 	mutex_exit(&connp->conn_lock);
29120 	return (found);
29121 }
29122 
29123 /*
29124  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
29125  */
29126 /* ARGSUSED */
29127 static void
29128 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
29129 {
29130 	ill_t *ill = (ill_t *)q->q_ptr;
29131 	mblk_t	*mp1, *mp2;
29132 	ipif_t  *ipif;
29133 	int err = 0;
29134 	conn_t *connp = NULL;
29135 	ipsq_t	*ipsq;
29136 	arc_t	*arc;
29137 
29138 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
29139 
29140 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
29141 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
29142 
29143 	ASSERT(IAM_WRITER_ILL(ill));
29144 	mp2 = mp->b_cont;
29145 	mp->b_cont = NULL;
29146 
29147 	/*
29148 	 * We have now received the arp bringup completion message
29149 	 * from ARP. Mark the arp bringup as done. Also if the arp
29150 	 * stream has already started closing, send up the AR_ARP_CLOSING
29151 	 * ack now since ARP is waiting in close for this ack.
29152 	 */
29153 	mutex_enter(&ill->ill_lock);
29154 	ill->ill_arp_bringup_pending = 0;
29155 	if (ill->ill_arp_closing) {
29156 		mutex_exit(&ill->ill_lock);
29157 		/* Let's reuse the mp for sending the ack */
29158 		arc = (arc_t *)mp->b_rptr;
29159 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
29160 		arc->arc_cmd = AR_ARP_CLOSING;
29161 		qreply(q, mp);
29162 	} else {
29163 		mutex_exit(&ill->ill_lock);
29164 		freeb(mp);
29165 	}
29166 
29167 	ipsq = ill->ill_phyint->phyint_ipsq;
29168 	ipif = ipsq->ipsq_pending_ipif;
29169 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
29170 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
29171 	if (mp1 == NULL) {
29172 		/* bringup was aborted by the user */
29173 		freemsg(mp2);
29174 		return;
29175 	}
29176 
29177 	/*
29178 	 * If an IOCTL is waiting on this (ipsq_current_ioctl != 0), then we
29179 	 * must have an associated conn_t.  Otherwise, we're bringing this
29180 	 * interface back up as part of handling an asynchronous event (e.g.,
29181 	 * physical address change).
29182 	 */
29183 	if (ipsq->ipsq_current_ioctl != 0) {
29184 		ASSERT(connp != NULL);
29185 		q = CONNP_TO_WQ(connp);
29186 	} else {
29187 		ASSERT(connp == NULL);
29188 		q = ill->ill_rq;
29189 	}
29190 
29191 	/*
29192 	 * If the DL_BIND_REQ fails, it is noted
29193 	 * in arc_name_offset.
29194 	 */
29195 	err = *((int *)mp2->b_rptr);
29196 	if (err == 0) {
29197 		if (ipif->ipif_isv6) {
29198 			if ((err = ipif_up_done_v6(ipif)) != 0)
29199 				ip0dbg(("ip_arp_done: init failed\n"));
29200 		} else {
29201 			if ((err = ipif_up_done(ipif)) != 0)
29202 				ip0dbg(("ip_arp_done: init failed\n"));
29203 		}
29204 	} else {
29205 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
29206 	}
29207 
29208 	freemsg(mp2);
29209 
29210 	if ((err == 0) && (ill->ill_up_ipifs)) {
29211 		err = ill_up_ipifs(ill, q, mp1);
29212 		if (err == EINPROGRESS)
29213 			return;
29214 	}
29215 
29216 	if (ill->ill_up_ipifs)
29217 		ill_group_cleanup(ill);
29218 
29219 	/*
29220 	 * The operation must complete without EINPROGRESS since
29221 	 * ipsq_pending_mp_get() has removed the mblk from ipsq_pending_mp.
29222 	 * Otherwise, the operation will be stuck forever in the ipsq.
29223 	 */
29224 	ASSERT(err != EINPROGRESS);
29225 	if (ipsq->ipsq_current_ioctl != 0)
29226 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
29227 	else
29228 		ipsq_current_finish(ipsq);
29229 }
29230 
29231 /* Allocate the private structure */
29232 static int
29233 ip_priv_alloc(void **bufp)
29234 {
29235 	void	*buf;
29236 
29237 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
29238 		return (ENOMEM);
29239 
29240 	*bufp = buf;
29241 	return (0);
29242 }
29243 
29244 /* Function to delete the private structure */
29245 void
29246 ip_priv_free(void *buf)
29247 {
29248 	ASSERT(buf != NULL);
29249 	kmem_free(buf, sizeof (ip_priv_t));
29250 }
29251 
29252 /*
29253  * The entry point for IPPF processing.
29254  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
29255  * routine just returns.
29256  *
29257  * When called, ip_process generates an ipp_packet_t structure
29258  * which holds the state information for this packet and invokes the
29259  * the classifier (via ipp_packet_process). The classification, depending on
29260  * configured filters, results in a list of actions for this packet. Invoking
29261  * an action may cause the packet to be dropped, in which case the resulting
29262  * mblk (*mpp) is NULL. proc indicates the callout position for
29263  * this packet and ill_index is the interface this packet on or will leave
29264  * on (inbound and outbound resp.).
29265  */
29266 void
29267 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
29268 {
29269 	mblk_t		*mp;
29270 	ip_priv_t	*priv;
29271 	ipp_action_id_t	aid;
29272 	int		rc = 0;
29273 	ipp_packet_t	*pp;
29274 #define	IP_CLASS	"ip"
29275 
29276 	/* If the classifier is not loaded, return  */
29277 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
29278 		return;
29279 	}
29280 
29281 	mp = *mpp;
29282 	ASSERT(mp != NULL);
29283 
29284 	/* Allocate the packet structure */
29285 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
29286 	if (rc != 0) {
29287 		*mpp = NULL;
29288 		freemsg(mp);
29289 		return;
29290 	}
29291 
29292 	/* Allocate the private structure */
29293 	rc = ip_priv_alloc((void **)&priv);
29294 	if (rc != 0) {
29295 		*mpp = NULL;
29296 		freemsg(mp);
29297 		ipp_packet_free(pp);
29298 		return;
29299 	}
29300 	priv->proc = proc;
29301 	priv->ill_index = ill_index;
29302 	ipp_packet_set_private(pp, priv, ip_priv_free);
29303 	ipp_packet_set_data(pp, mp);
29304 
29305 	/* Invoke the classifier */
29306 	rc = ipp_packet_process(&pp);
29307 	if (pp != NULL) {
29308 		mp = ipp_packet_get_data(pp);
29309 		ipp_packet_free(pp);
29310 		if (rc != 0) {
29311 			freemsg(mp);
29312 			*mpp = NULL;
29313 		}
29314 	} else {
29315 		*mpp = NULL;
29316 	}
29317 #undef	IP_CLASS
29318 }
29319 
29320 /*
29321  * Propagate a multicast group membership operation (add/drop) on
29322  * all the interfaces crossed by the related multirt routes.
29323  * The call is considered successful if the operation succeeds
29324  * on at least one interface.
29325  */
29326 static int
29327 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
29328     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
29329     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
29330     mblk_t *first_mp)
29331 {
29332 	ire_t		*ire_gw;
29333 	irb_t		*irb;
29334 	int		error = 0;
29335 	opt_restart_t	*or;
29336 	ip_stack_t	*ipst = ire->ire_ipst;
29337 
29338 	irb = ire->ire_bucket;
29339 	ASSERT(irb != NULL);
29340 
29341 	ASSERT(DB_TYPE(first_mp) == M_CTL);
29342 
29343 	or = (opt_restart_t *)first_mp->b_rptr;
29344 	IRB_REFHOLD(irb);
29345 	for (; ire != NULL; ire = ire->ire_next) {
29346 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
29347 			continue;
29348 		if (ire->ire_addr != group)
29349 			continue;
29350 
29351 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
29352 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
29353 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
29354 		/* No resolver exists for the gateway; skip this ire. */
29355 		if (ire_gw == NULL)
29356 			continue;
29357 
29358 		/*
29359 		 * This function can return EINPROGRESS. If so the operation
29360 		 * will be restarted from ip_restart_optmgmt which will
29361 		 * call ip_opt_set and option processing will restart for
29362 		 * this option. So we may end up calling 'fn' more than once.
29363 		 * This requires that 'fn' is idempotent except for the
29364 		 * return value. The operation is considered a success if
29365 		 * it succeeds at least once on any one interface.
29366 		 */
29367 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
29368 		    NULL, fmode, src, first_mp);
29369 		if (error == 0)
29370 			or->or_private = CGTP_MCAST_SUCCESS;
29371 
29372 		if (ip_debug > 0) {
29373 			ulong_t	off;
29374 			char	*ksym;
29375 			ksym = kobj_getsymname((uintptr_t)fn, &off);
29376 			ip2dbg(("ip_multirt_apply_membership: "
29377 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
29378 			    "error %d [success %u]\n",
29379 			    ksym ? ksym : "?",
29380 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
29381 			    error, or->or_private));
29382 		}
29383 
29384 		ire_refrele(ire_gw);
29385 		if (error == EINPROGRESS) {
29386 			IRB_REFRELE(irb);
29387 			return (error);
29388 		}
29389 	}
29390 	IRB_REFRELE(irb);
29391 	/*
29392 	 * Consider the call as successful if we succeeded on at least
29393 	 * one interface. Otherwise, return the last encountered error.
29394 	 */
29395 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
29396 }
29397 
29398 /*
29399  * Issue a warning regarding a route crossing an interface with an
29400  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
29401  * amount of time is logged.
29402  */
29403 static void
29404 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
29405 {
29406 	hrtime_t	current = gethrtime();
29407 	char		buf[INET_ADDRSTRLEN];
29408 	ip_stack_t	*ipst = ire->ire_ipst;
29409 
29410 	/* Convert interval in ms to hrtime in ns */
29411 	if (ipst->ips_multirt_bad_mtu_last_time +
29412 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
29413 	    current) {
29414 		cmn_err(CE_WARN, "ip: ignoring multiroute "
29415 		    "to %s, incorrect MTU %u (expected %u)\n",
29416 		    ip_dot_addr(ire->ire_addr, buf),
29417 		    ire->ire_max_frag, max_frag);
29418 
29419 		ipst->ips_multirt_bad_mtu_last_time = current;
29420 	}
29421 }
29422 
29423 
29424 /*
29425  * Get the CGTP (multirouting) filtering status.
29426  * If 0, the CGTP hooks are transparent.
29427  */
29428 /* ARGSUSED */
29429 static int
29430 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
29431 {
29432 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
29433 
29434 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
29435 	return (0);
29436 }
29437 
29438 
29439 /*
29440  * Set the CGTP (multirouting) filtering status.
29441  * If the status is changed from active to transparent
29442  * or from transparent to active, forward the new status
29443  * to the filtering module (if loaded).
29444  */
29445 /* ARGSUSED */
29446 static int
29447 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
29448     cred_t *ioc_cr)
29449 {
29450 	long		new_value;
29451 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
29452 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29453 
29454 	if (secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
29455 		return (EPERM);
29456 
29457 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
29458 	    new_value < 0 || new_value > 1) {
29459 		return (EINVAL);
29460 	}
29461 
29462 	if ((!*ip_cgtp_filter_value) && new_value) {
29463 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
29464 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
29465 		    " (module not loaded)" : "");
29466 	}
29467 	if (*ip_cgtp_filter_value && (!new_value)) {
29468 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
29469 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
29470 		    " (module not loaded)" : "");
29471 	}
29472 
29473 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
29474 		int	res;
29475 		netstackid_t stackid;
29476 
29477 		stackid = ipst->ips_netstack->netstack_stackid;
29478 		res = ipst->ips_ip_cgtp_filter_ops->cfo_change_state(stackid,
29479 		    new_value);
29480 		if (res)
29481 			return (res);
29482 	}
29483 
29484 	*ip_cgtp_filter_value = (boolean_t)new_value;
29485 
29486 	return (0);
29487 }
29488 
29489 
29490 /*
29491  * Return the expected CGTP hooks version number.
29492  */
29493 int
29494 ip_cgtp_filter_supported(void)
29495 {
29496 	return (ip_cgtp_filter_rev);
29497 }
29498 
29499 
29500 /*
29501  * CGTP hooks can be registered by invoking this function.
29502  * Checks that the version number matches.
29503  */
29504 int
29505 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
29506 {
29507 	netstack_t *ns;
29508 	ip_stack_t *ipst;
29509 
29510 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
29511 		return (ENOTSUP);
29512 
29513 	ns = netstack_find_by_stackid(stackid);
29514 	if (ns == NULL)
29515 		return (EINVAL);
29516 	ipst = ns->netstack_ip;
29517 	ASSERT(ipst != NULL);
29518 
29519 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
29520 		netstack_rele(ns);
29521 		return (EALREADY);
29522 	}
29523 
29524 	ipst->ips_ip_cgtp_filter_ops = ops;
29525 	netstack_rele(ns);
29526 	return (0);
29527 }
29528 
29529 /*
29530  * CGTP hooks can be unregistered by invoking this function.
29531  * Returns ENXIO if there was no registration.
29532  * Returns EBUSY if the ndd variable has not been turned off.
29533  */
29534 int
29535 ip_cgtp_filter_unregister(netstackid_t stackid)
29536 {
29537 	netstack_t *ns;
29538 	ip_stack_t *ipst;
29539 
29540 	ns = netstack_find_by_stackid(stackid);
29541 	if (ns == NULL)
29542 		return (EINVAL);
29543 	ipst = ns->netstack_ip;
29544 	ASSERT(ipst != NULL);
29545 
29546 	if (ipst->ips_ip_cgtp_filter) {
29547 		netstack_rele(ns);
29548 		return (EBUSY);
29549 	}
29550 
29551 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
29552 		netstack_rele(ns);
29553 		return (ENXIO);
29554 	}
29555 	ipst->ips_ip_cgtp_filter_ops = NULL;
29556 	netstack_rele(ns);
29557 	return (0);
29558 }
29559 
29560 /*
29561  * Check whether there is a CGTP filter registration.
29562  * Returns non-zero if there is a registration, otherwise returns zero.
29563  * Note: returns zero if bad stackid.
29564  */
29565 int
29566 ip_cgtp_filter_is_registered(netstackid_t stackid)
29567 {
29568 	netstack_t *ns;
29569 	ip_stack_t *ipst;
29570 	int ret;
29571 
29572 	ns = netstack_find_by_stackid(stackid);
29573 	if (ns == NULL)
29574 		return (0);
29575 	ipst = ns->netstack_ip;
29576 	ASSERT(ipst != NULL);
29577 
29578 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
29579 		ret = 1;
29580 	else
29581 		ret = 0;
29582 
29583 	netstack_rele(ns);
29584 	return (ret);
29585 }
29586 
29587 static int
29588 ip_squeue_switch(int val)
29589 {
29590 	int rval = SQ_FILL;
29591 
29592 	switch (val) {
29593 	case IP_SQUEUE_ENTER_NODRAIN:
29594 		rval = SQ_NODRAIN;
29595 		break;
29596 	case IP_SQUEUE_ENTER:
29597 		rval = SQ_PROCESS;
29598 		break;
29599 	default:
29600 		break;
29601 	}
29602 	return (rval);
29603 }
29604 
29605 /* ARGSUSED */
29606 static int
29607 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
29608     caddr_t addr, cred_t *cr)
29609 {
29610 	int *v = (int *)addr;
29611 	long new_value;
29612 
29613 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29614 		return (EPERM);
29615 
29616 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29617 		return (EINVAL);
29618 
29619 	ip_squeue_flag = ip_squeue_switch(new_value);
29620 	*v = new_value;
29621 	return (0);
29622 }
29623 
29624 /*
29625  * Handle ndd set of variables which require PRIV_SYS_NET_CONFIG such as
29626  * ip_debug.
29627  */
29628 /* ARGSUSED */
29629 static int
29630 ip_int_set(queue_t *q, mblk_t *mp, char *value,
29631     caddr_t addr, cred_t *cr)
29632 {
29633 	int *v = (int *)addr;
29634 	long new_value;
29635 
29636 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29637 		return (EPERM);
29638 
29639 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29640 		return (EINVAL);
29641 
29642 	*v = new_value;
29643 	return (0);
29644 }
29645 
29646 /*
29647  * Handle changes to ipmp_hook_emulation ndd variable.
29648  * Need to update phyint_hook_ifindex.
29649  * Also generate a nic plumb event should a new ifidex be assigned to a group.
29650  */
29651 static void
29652 ipmp_hook_emulation_changed(ip_stack_t *ipst)
29653 {
29654 	phyint_t *phyi;
29655 	phyint_t *phyi_tmp;
29656 	char *groupname;
29657 	int namelen;
29658 	ill_t	*ill;
29659 	boolean_t new_group;
29660 
29661 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29662 	/*
29663 	 * Group indicies are stored in the phyint - a common structure
29664 	 * to both IPv4 and IPv6.
29665 	 */
29666 	phyi = avl_first(&ipst->ips_phyint_g_list->phyint_list_avl_by_index);
29667 	for (; phyi != NULL;
29668 	    phyi = avl_walk(&ipst->ips_phyint_g_list->phyint_list_avl_by_index,
29669 	    phyi, AVL_AFTER)) {
29670 		/* Ignore the ones that do not have a group */
29671 		if (phyi->phyint_groupname_len == 0)
29672 			continue;
29673 
29674 		/*
29675 		 * Look for other phyint in group.
29676 		 * Clear name/namelen so the lookup doesn't find ourselves.
29677 		 */
29678 		namelen = phyi->phyint_groupname_len;
29679 		groupname = phyi->phyint_groupname;
29680 		phyi->phyint_groupname_len = 0;
29681 		phyi->phyint_groupname = NULL;
29682 
29683 		phyi_tmp = phyint_lookup_group(groupname, B_FALSE, ipst);
29684 		/* Restore */
29685 		phyi->phyint_groupname_len = namelen;
29686 		phyi->phyint_groupname = groupname;
29687 
29688 		new_group = B_FALSE;
29689 		if (ipst->ips_ipmp_hook_emulation) {
29690 			/*
29691 			 * If the group already exists and has already
29692 			 * been assigned a group ifindex, we use the existing
29693 			 * group_ifindex, otherwise we pick a new group_ifindex
29694 			 * here.
29695 			 */
29696 			if (phyi_tmp != NULL &&
29697 			    phyi_tmp->phyint_group_ifindex != 0) {
29698 				phyi->phyint_group_ifindex =
29699 				    phyi_tmp->phyint_group_ifindex;
29700 			} else {
29701 				/* XXX We need a recovery strategy here. */
29702 				if (!ip_assign_ifindex(
29703 				    &phyi->phyint_group_ifindex, ipst))
29704 					cmn_err(CE_PANIC,
29705 					    "ip_assign_ifindex() failed");
29706 				new_group = B_TRUE;
29707 			}
29708 		} else {
29709 			phyi->phyint_group_ifindex = 0;
29710 		}
29711 		if (ipst->ips_ipmp_hook_emulation)
29712 			phyi->phyint_hook_ifindex = phyi->phyint_group_ifindex;
29713 		else
29714 			phyi->phyint_hook_ifindex = phyi->phyint_ifindex;
29715 
29716 		/*
29717 		 * For IP Filter to find out the relationship between
29718 		 * names and interface indicies, we need to generate
29719 		 * a NE_PLUMB event when a new group can appear.
29720 		 * We always generate events when a new interface appears
29721 		 * (even when ipmp_hook_emulation is set) so there
29722 		 * is no need to generate NE_PLUMB events when
29723 		 * ipmp_hook_emulation is turned off.
29724 		 * And since it isn't critical for IP Filter to get
29725 		 * the NE_UNPLUMB events we skip those here.
29726 		 */
29727 		if (new_group) {
29728 			/*
29729 			 * First phyint in group - generate group PLUMB event.
29730 			 * Since we are not running inside the ipsq we do
29731 			 * the dispatch immediately.
29732 			 */
29733 			if (phyi->phyint_illv4 != NULL)
29734 				ill = phyi->phyint_illv4;
29735 			else
29736 				ill = phyi->phyint_illv6;
29737 
29738 			if (ill != NULL)
29739 				ill_nic_event_plumb(ill, B_TRUE);
29740 		}
29741 	}
29742 	rw_exit(&ipst->ips_ill_g_lock);
29743 }
29744 
29745 /* ARGSUSED */
29746 static int
29747 ipmp_hook_emulation_set(queue_t *q, mblk_t *mp, char *value,
29748     caddr_t addr, cred_t *cr)
29749 {
29750 	int *v = (int *)addr;
29751 	long new_value;
29752 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29753 
29754 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29755 		return (EINVAL);
29756 
29757 	if (*v != new_value) {
29758 		*v = new_value;
29759 		ipmp_hook_emulation_changed(ipst);
29760 	}
29761 	return (0);
29762 }
29763 
29764 static void *
29765 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
29766 {
29767 	kstat_t *ksp;
29768 
29769 	ip_stat_t template = {
29770 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
29771 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
29772 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
29773 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
29774 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
29775 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
29776 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
29777 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
29778 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
29779 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
29780 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
29781 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
29782 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
29783 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
29784 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
29785 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
29786 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
29787 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
29788 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
29789 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
29790 		{ "ip_opt",			KSTAT_DATA_UINT64 },
29791 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
29792 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
29793 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29794 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29795 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29796 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29797 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29798 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29799 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29800 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29801 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29802 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29803 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29804 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29805 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29806 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29807 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29808 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29809 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29810 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29811 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29812 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29813 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29814 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29815 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29816 	};
29817 
29818 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29819 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29820 	    KSTAT_FLAG_VIRTUAL, stackid);
29821 
29822 	if (ksp == NULL)
29823 		return (NULL);
29824 
29825 	bcopy(&template, ip_statisticsp, sizeof (template));
29826 	ksp->ks_data = (void *)ip_statisticsp;
29827 	ksp->ks_private = (void *)(uintptr_t)stackid;
29828 
29829 	kstat_install(ksp);
29830 	return (ksp);
29831 }
29832 
29833 static void
29834 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29835 {
29836 	if (ksp != NULL) {
29837 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29838 		kstat_delete_netstack(ksp, stackid);
29839 	}
29840 }
29841 
29842 static void *
29843 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29844 {
29845 	kstat_t	*ksp;
29846 
29847 	ip_named_kstat_t template = {
29848 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29849 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29850 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29851 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29852 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29853 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29854 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29855 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29856 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29857 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29858 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29859 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29860 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29861 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29862 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29863 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29864 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29865 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29866 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29867 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29868 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29869 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29870 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29871 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29872 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29873 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29874 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29875 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29876 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29877 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29878 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29879 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29880 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29881 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29882 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29883 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29884 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29885 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29886 	};
29887 
29888 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29889 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
29890 	if (ksp == NULL || ksp->ks_data == NULL)
29891 		return (NULL);
29892 
29893 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29894 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29895 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29896 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29897 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29898 
29899 	template.netToMediaEntrySize.value.i32 =
29900 	    sizeof (mib2_ipNetToMediaEntry_t);
29901 
29902 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29903 
29904 	bcopy(&template, ksp->ks_data, sizeof (template));
29905 	ksp->ks_update = ip_kstat_update;
29906 	ksp->ks_private = (void *)(uintptr_t)stackid;
29907 
29908 	kstat_install(ksp);
29909 	return (ksp);
29910 }
29911 
29912 static void
29913 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29914 {
29915 	if (ksp != NULL) {
29916 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29917 		kstat_delete_netstack(ksp, stackid);
29918 	}
29919 }
29920 
29921 static int
29922 ip_kstat_update(kstat_t *kp, int rw)
29923 {
29924 	ip_named_kstat_t *ipkp;
29925 	mib2_ipIfStatsEntry_t ipmib;
29926 	ill_walk_context_t ctx;
29927 	ill_t *ill;
29928 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29929 	netstack_t	*ns;
29930 	ip_stack_t	*ipst;
29931 
29932 	if (kp == NULL || kp->ks_data == NULL)
29933 		return (EIO);
29934 
29935 	if (rw == KSTAT_WRITE)
29936 		return (EACCES);
29937 
29938 	ns = netstack_find_by_stackid(stackid);
29939 	if (ns == NULL)
29940 		return (-1);
29941 	ipst = ns->netstack_ip;
29942 	if (ipst == NULL) {
29943 		netstack_rele(ns);
29944 		return (-1);
29945 	}
29946 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29947 
29948 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29949 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29950 	ill = ILL_START_WALK_V4(&ctx, ipst);
29951 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29952 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29953 	rw_exit(&ipst->ips_ill_g_lock);
29954 
29955 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29956 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29957 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29958 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29959 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29960 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29961 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29962 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29963 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29964 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29965 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29966 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29967 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29968 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29969 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29970 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29971 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29972 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29973 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29974 
29975 	ipkp->routingDiscards.value.ui32 =	0;
29976 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29977 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29978 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29979 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29980 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29981 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29982 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29983 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29984 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29985 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29986 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29987 
29988 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29989 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29990 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29991 
29992 	netstack_rele(ns);
29993 
29994 	return (0);
29995 }
29996 
29997 static void *
29998 icmp_kstat_init(netstackid_t stackid)
29999 {
30000 	kstat_t	*ksp;
30001 
30002 	icmp_named_kstat_t template = {
30003 		{ "inMsgs",		KSTAT_DATA_UINT32 },
30004 		{ "inErrors",		KSTAT_DATA_UINT32 },
30005 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
30006 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
30007 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
30008 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
30009 		{ "inRedirects",	KSTAT_DATA_UINT32 },
30010 		{ "inEchos",		KSTAT_DATA_UINT32 },
30011 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
30012 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
30013 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
30014 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
30015 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
30016 		{ "outMsgs",		KSTAT_DATA_UINT32 },
30017 		{ "outErrors",		KSTAT_DATA_UINT32 },
30018 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
30019 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
30020 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
30021 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
30022 		{ "outRedirects",	KSTAT_DATA_UINT32 },
30023 		{ "outEchos",		KSTAT_DATA_UINT32 },
30024 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
30025 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
30026 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
30027 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
30028 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
30029 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
30030 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
30031 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
30032 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
30033 		{ "outDrops",		KSTAT_DATA_UINT32 },
30034 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
30035 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
30036 	};
30037 
30038 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
30039 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
30040 	if (ksp == NULL || ksp->ks_data == NULL)
30041 		return (NULL);
30042 
30043 	bcopy(&template, ksp->ks_data, sizeof (template));
30044 
30045 	ksp->ks_update = icmp_kstat_update;
30046 	ksp->ks_private = (void *)(uintptr_t)stackid;
30047 
30048 	kstat_install(ksp);
30049 	return (ksp);
30050 }
30051 
30052 static void
30053 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
30054 {
30055 	if (ksp != NULL) {
30056 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
30057 		kstat_delete_netstack(ksp, stackid);
30058 	}
30059 }
30060 
30061 static int
30062 icmp_kstat_update(kstat_t *kp, int rw)
30063 {
30064 	icmp_named_kstat_t *icmpkp;
30065 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
30066 	netstack_t	*ns;
30067 	ip_stack_t	*ipst;
30068 
30069 	if ((kp == NULL) || (kp->ks_data == NULL))
30070 		return (EIO);
30071 
30072 	if (rw == KSTAT_WRITE)
30073 		return (EACCES);
30074 
30075 	ns = netstack_find_by_stackid(stackid);
30076 	if (ns == NULL)
30077 		return (-1);
30078 	ipst = ns->netstack_ip;
30079 	if (ipst == NULL) {
30080 		netstack_rele(ns);
30081 		return (-1);
30082 	}
30083 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
30084 
30085 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
30086 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
30087 	icmpkp->inDestUnreachs.value.ui32 =
30088 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
30089 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
30090 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
30091 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
30092 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
30093 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
30094 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
30095 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
30096 	icmpkp->inTimestampReps.value.ui32 =
30097 	    ipst->ips_icmp_mib.icmpInTimestampReps;
30098 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
30099 	icmpkp->inAddrMaskReps.value.ui32 =
30100 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
30101 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
30102 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
30103 	icmpkp->outDestUnreachs.value.ui32 =
30104 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
30105 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
30106 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
30107 	icmpkp->outSrcQuenchs.value.ui32 =
30108 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
30109 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
30110 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
30111 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
30112 	icmpkp->outTimestamps.value.ui32 =
30113 	    ipst->ips_icmp_mib.icmpOutTimestamps;
30114 	icmpkp->outTimestampReps.value.ui32 =
30115 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
30116 	icmpkp->outAddrMasks.value.ui32 =
30117 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
30118 	icmpkp->outAddrMaskReps.value.ui32 =
30119 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
30120 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
30121 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
30122 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
30123 	icmpkp->outFragNeeded.value.ui32 =
30124 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
30125 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
30126 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
30127 	icmpkp->inBadRedirects.value.ui32 =
30128 	    ipst->ips_icmp_mib.icmpInBadRedirects;
30129 
30130 	netstack_rele(ns);
30131 	return (0);
30132 }
30133 
30134 /*
30135  * This is the fanout function for raw socket opened for SCTP.  Note
30136  * that it is called after SCTP checks that there is no socket which
30137  * wants a packet.  Then before SCTP handles this out of the blue packet,
30138  * this function is called to see if there is any raw socket for SCTP.
30139  * If there is and it is bound to the correct address, the packet will
30140  * be sent to that socket.  Note that only one raw socket can be bound to
30141  * a port.  This is assured in ipcl_sctp_hash_insert();
30142  */
30143 void
30144 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
30145     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
30146     zoneid_t zoneid)
30147 {
30148 	conn_t		*connp;
30149 	queue_t		*rq;
30150 	mblk_t		*first_mp;
30151 	boolean_t	secure;
30152 	ip6_t		*ip6h;
30153 	ip_stack_t	*ipst = recv_ill->ill_ipst;
30154 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
30155 	sctp_stack_t	*sctps = ipst->ips_netstack->netstack_sctp;
30156 	boolean_t	sctp_csum_err = B_FALSE;
30157 
30158 	if (flags & IP_FF_SCTP_CSUM_ERR) {
30159 		sctp_csum_err = B_TRUE;
30160 		flags &= ~IP_FF_SCTP_CSUM_ERR;
30161 	}
30162 
30163 	first_mp = mp;
30164 	if (mctl_present) {
30165 		mp = first_mp->b_cont;
30166 		secure = ipsec_in_is_secure(first_mp);
30167 		ASSERT(mp != NULL);
30168 	} else {
30169 		secure = B_FALSE;
30170 	}
30171 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
30172 
30173 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
30174 	if (connp == NULL) {
30175 		/*
30176 		 * Although raw sctp is not summed, OOB chunks must be.
30177 		 * Drop the packet here if the sctp checksum failed.
30178 		 */
30179 		if (sctp_csum_err) {
30180 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
30181 			freemsg(first_mp);
30182 			return;
30183 		}
30184 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
30185 		return;
30186 	}
30187 	rq = connp->conn_rq;
30188 	if (!canputnext(rq)) {
30189 		CONN_DEC_REF(connp);
30190 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
30191 		freemsg(first_mp);
30192 		return;
30193 	}
30194 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
30195 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
30196 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
30197 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
30198 		if (first_mp == NULL) {
30199 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
30200 			CONN_DEC_REF(connp);
30201 			return;
30202 		}
30203 	}
30204 	/*
30205 	 * We probably should not send M_CTL message up to
30206 	 * raw socket.
30207 	 */
30208 	if (mctl_present)
30209 		freeb(first_mp);
30210 
30211 	/* Initiate IPPF processing here if needed. */
30212 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
30213 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
30214 		ip_process(IPP_LOCAL_IN, &mp,
30215 		    recv_ill->ill_phyint->phyint_ifindex);
30216 		if (mp == NULL) {
30217 			CONN_DEC_REF(connp);
30218 			return;
30219 		}
30220 	}
30221 
30222 	if (connp->conn_recvif || connp->conn_recvslla ||
30223 	    ((connp->conn_ip_recvpktinfo ||
30224 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
30225 	    (flags & IP_FF_IPINFO))) {
30226 		int in_flags = 0;
30227 
30228 		/*
30229 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
30230 		 * IPF_RECVIF.
30231 		 */
30232 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
30233 			in_flags = IPF_RECVIF;
30234 		}
30235 		if (connp->conn_recvslla) {
30236 			in_flags |= IPF_RECVSLLA;
30237 		}
30238 		if (isv4) {
30239 			mp = ip_add_info(mp, recv_ill, in_flags,
30240 			    IPCL_ZONEID(connp), ipst);
30241 		} else {
30242 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
30243 			if (mp == NULL) {
30244 				BUMP_MIB(recv_ill->ill_ip_mib,
30245 				    ipIfStatsInDiscards);
30246 				CONN_DEC_REF(connp);
30247 				return;
30248 			}
30249 		}
30250 	}
30251 
30252 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
30253 	/*
30254 	 * We are sending the IPSEC_IN message also up. Refer
30255 	 * to comments above this function.
30256 	 * This is the SOCK_RAW, IPPROTO_SCTP case.
30257 	 */
30258 	(connp->conn_recv)(connp, mp, NULL);
30259 	CONN_DEC_REF(connp);
30260 }
30261 
30262 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
30263 {									\
30264 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
30265 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
30266 }
30267 /*
30268  * This function should be called only if all packet processing
30269  * including fragmentation is complete. Callers of this function
30270  * must set mp->b_prev to one of these values:
30271  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
30272  * prior to handing over the mp as first argument to this function.
30273  *
30274  * If the ire passed by caller is incomplete, this function
30275  * queues the packet and if necessary, sends ARP request and bails.
30276  * If the ire passed is fully resolved, we simply prepend
30277  * the link-layer header to the packet, do ipsec hw acceleration
30278  * work if necessary, and send the packet out on the wire.
30279  *
30280  * NOTE: IPsec will only call this function with fully resolved
30281  * ires if hw acceleration is involved.
30282  * TODO list :
30283  * 	a Handle M_MULTIDATA so that
30284  *	  tcp_multisend->tcp_multisend_data can
30285  *	  call ip_xmit_v4 directly
30286  *	b Handle post-ARP work for fragments so that
30287  *	  ip_wput_frag can call this function.
30288  */
30289 ipxmit_state_t
30290 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io,
30291     boolean_t flow_ctl_enabled, conn_t *connp)
30292 {
30293 	nce_t		*arpce;
30294 	ipha_t		*ipha;
30295 	queue_t		*q;
30296 	int		ill_index;
30297 	mblk_t		*nxt_mp, *first_mp;
30298 	boolean_t	xmit_drop = B_FALSE;
30299 	ip_proc_t	proc;
30300 	ill_t		*out_ill;
30301 	int		pkt_len;
30302 
30303 	arpce = ire->ire_nce;
30304 	ASSERT(arpce != NULL);
30305 
30306 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
30307 
30308 	mutex_enter(&arpce->nce_lock);
30309 	switch (arpce->nce_state) {
30310 	case ND_REACHABLE:
30311 		/* If there are other queued packets, queue this packet */
30312 		if (arpce->nce_qd_mp != NULL) {
30313 			if (mp != NULL)
30314 				nce_queue_mp_common(arpce, mp, B_FALSE);
30315 			mp = arpce->nce_qd_mp;
30316 		}
30317 		arpce->nce_qd_mp = NULL;
30318 		mutex_exit(&arpce->nce_lock);
30319 
30320 		/*
30321 		 * Flush the queue.  In the common case, where the
30322 		 * ARP is already resolved,  it will go through the
30323 		 * while loop only once.
30324 		 */
30325 		while (mp != NULL) {
30326 
30327 			nxt_mp = mp->b_next;
30328 			mp->b_next = NULL;
30329 			ASSERT(mp->b_datap->db_type != M_CTL);
30330 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
30331 			/*
30332 			 * This info is needed for IPQOS to do COS marking
30333 			 * in ip_wput_attach_llhdr->ip_process.
30334 			 */
30335 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
30336 			mp->b_prev = NULL;
30337 
30338 			/* set up ill index for outbound qos processing */
30339 			out_ill = ire_to_ill(ire);
30340 			ill_index = out_ill->ill_phyint->phyint_ifindex;
30341 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
30342 			    ill_index, &ipha);
30343 			if (first_mp == NULL) {
30344 				xmit_drop = B_TRUE;
30345 				BUMP_MIB(out_ill->ill_ip_mib,
30346 				    ipIfStatsOutDiscards);
30347 				goto next_mp;
30348 			}
30349 
30350 			/* non-ipsec hw accel case */
30351 			if (io == NULL || !io->ipsec_out_accelerated) {
30352 				/* send it */
30353 				q = ire->ire_stq;
30354 				if (proc == IPP_FWD_OUT) {
30355 					UPDATE_IB_PKT_COUNT(ire);
30356 				} else {
30357 					UPDATE_OB_PKT_COUNT(ire);
30358 				}
30359 				ire->ire_last_used_time = lbolt;
30360 
30361 				if (flow_ctl_enabled || canputnext(q)) {
30362 					if (proc == IPP_FWD_OUT) {
30363 
30364 					BUMP_MIB(out_ill->ill_ip_mib,
30365 					    ipIfStatsHCOutForwDatagrams);
30366 
30367 					}
30368 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
30369 					    pkt_len);
30370 
30371 					DTRACE_IP7(send, mblk_t *, first_mp,
30372 					    conn_t *, NULL, void_ip_t *, ipha,
30373 					    __dtrace_ipsr_ill_t *, out_ill,
30374 					    ipha_t *, ipha, ip6_t *, NULL, int,
30375 					    0);
30376 
30377 					ILL_SEND_TX(out_ill,
30378 					    ire, connp, first_mp, 0);
30379 				} else {
30380 					BUMP_MIB(out_ill->ill_ip_mib,
30381 					    ipIfStatsOutDiscards);
30382 					xmit_drop = B_TRUE;
30383 					freemsg(first_mp);
30384 				}
30385 			} else {
30386 				/*
30387 				 * Safety Pup says: make sure this
30388 				 *  is going to the right interface!
30389 				 */
30390 				ill_t *ill1 =
30391 				    (ill_t *)ire->ire_stq->q_ptr;
30392 				int ifindex =
30393 				    ill1->ill_phyint->phyint_ifindex;
30394 				if (ifindex !=
30395 				    io->ipsec_out_capab_ill_index) {
30396 					xmit_drop = B_TRUE;
30397 					freemsg(mp);
30398 				} else {
30399 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
30400 					    pkt_len);
30401 
30402 					DTRACE_IP7(send, mblk_t *, first_mp,
30403 					    conn_t *, NULL, void_ip_t *, ipha,
30404 					    __dtrace_ipsr_ill_t *, ill1,
30405 					    ipha_t *, ipha, ip6_t *, NULL,
30406 					    int, 0);
30407 
30408 					ipsec_hw_putnext(ire->ire_stq, mp);
30409 				}
30410 			}
30411 next_mp:
30412 			mp = nxt_mp;
30413 		} /* while (mp != NULL) */
30414 		if (xmit_drop)
30415 			return (SEND_FAILED);
30416 		else
30417 			return (SEND_PASSED);
30418 
30419 	case ND_INITIAL:
30420 	case ND_INCOMPLETE:
30421 
30422 		/*
30423 		 * While we do send off packets to dests that
30424 		 * use fully-resolved CGTP routes, we do not
30425 		 * handle unresolved CGTP routes.
30426 		 */
30427 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
30428 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
30429 
30430 		if (mp != NULL) {
30431 			/* queue the packet */
30432 			nce_queue_mp_common(arpce, mp, B_FALSE);
30433 		}
30434 
30435 		if (arpce->nce_state == ND_INCOMPLETE) {
30436 			mutex_exit(&arpce->nce_lock);
30437 			DTRACE_PROBE3(ip__xmit__incomplete,
30438 			    (ire_t *), ire, (mblk_t *), mp,
30439 			    (ipsec_out_t *), io);
30440 			return (LOOKUP_IN_PROGRESS);
30441 		}
30442 
30443 		arpce->nce_state = ND_INCOMPLETE;
30444 		mutex_exit(&arpce->nce_lock);
30445 		/*
30446 		 * Note that ire_add() (called from ire_forward())
30447 		 * holds a ref on the ire until ARP is completed.
30448 		 */
30449 
30450 		ire_arpresolve(ire, ire_to_ill(ire));
30451 		return (LOOKUP_IN_PROGRESS);
30452 	default:
30453 		ASSERT(0);
30454 		mutex_exit(&arpce->nce_lock);
30455 		return (LLHDR_RESLV_FAILED);
30456 	}
30457 }
30458 
30459 #undef	UPDATE_IP_MIB_OB_COUNTERS
30460 
30461 /*
30462  * Return B_TRUE if the buffers differ in length or content.
30463  * This is used for comparing extension header buffers.
30464  * Note that an extension header would be declared different
30465  * even if all that changed was the next header value in that header i.e.
30466  * what really changed is the next extension header.
30467  */
30468 boolean_t
30469 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
30470     uint_t blen)
30471 {
30472 	if (!b_valid)
30473 		blen = 0;
30474 
30475 	if (alen != blen)
30476 		return (B_TRUE);
30477 	if (alen == 0)
30478 		return (B_FALSE);	/* Both zero length */
30479 	return (bcmp(abuf, bbuf, alen));
30480 }
30481 
30482 /*
30483  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
30484  * Return B_FALSE if memory allocation fails - don't change any state!
30485  */
30486 boolean_t
30487 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
30488     const void *src, uint_t srclen)
30489 {
30490 	void *dst;
30491 
30492 	if (!src_valid)
30493 		srclen = 0;
30494 
30495 	ASSERT(*dstlenp == 0);
30496 	if (src != NULL && srclen != 0) {
30497 		dst = mi_alloc(srclen, BPRI_MED);
30498 		if (dst == NULL)
30499 			return (B_FALSE);
30500 	} else {
30501 		dst = NULL;
30502 	}
30503 	if (*dstp != NULL)
30504 		mi_free(*dstp);
30505 	*dstp = dst;
30506 	*dstlenp = dst == NULL ? 0 : srclen;
30507 	return (B_TRUE);
30508 }
30509 
30510 /*
30511  * Replace what is in *dst, *dstlen with the source.
30512  * Assumes ip_allocbuf has already been called.
30513  */
30514 void
30515 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
30516     const void *src, uint_t srclen)
30517 {
30518 	if (!src_valid)
30519 		srclen = 0;
30520 
30521 	ASSERT(*dstlenp == srclen);
30522 	if (src != NULL && srclen != 0)
30523 		bcopy(src, *dstp, srclen);
30524 }
30525 
30526 /*
30527  * Free the storage pointed to by the members of an ip6_pkt_t.
30528  */
30529 void
30530 ip6_pkt_free(ip6_pkt_t *ipp)
30531 {
30532 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
30533 
30534 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
30535 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
30536 		ipp->ipp_hopopts = NULL;
30537 		ipp->ipp_hopoptslen = 0;
30538 	}
30539 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
30540 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
30541 		ipp->ipp_rtdstopts = NULL;
30542 		ipp->ipp_rtdstoptslen = 0;
30543 	}
30544 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
30545 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
30546 		ipp->ipp_dstopts = NULL;
30547 		ipp->ipp_dstoptslen = 0;
30548 	}
30549 	if (ipp->ipp_fields & IPPF_RTHDR) {
30550 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
30551 		ipp->ipp_rthdr = NULL;
30552 		ipp->ipp_rthdrlen = 0;
30553 	}
30554 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
30555 	    IPPF_RTHDR);
30556 }
30557 
30558 zoneid_t
30559 ip_get_zoneid_v4(ipaddr_t addr, mblk_t *mp, ip_stack_t *ipst,
30560     zoneid_t lookup_zoneid)
30561 {
30562 	ire_t		*ire;
30563 	int		ire_flags = MATCH_IRE_TYPE;
30564 	zoneid_t	zoneid = ALL_ZONES;
30565 
30566 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE))
30567 		return (ALL_ZONES);
30568 
30569 	if (lookup_zoneid != ALL_ZONES)
30570 		ire_flags |= MATCH_IRE_ZONEONLY;
30571 	ire = ire_ctable_lookup(addr, NULL, IRE_LOCAL | IRE_LOOPBACK, NULL,
30572 	    lookup_zoneid, NULL, ire_flags, ipst);
30573 	if (ire != NULL) {
30574 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
30575 		ire_refrele(ire);
30576 	}
30577 	return (zoneid);
30578 }
30579 
30580 zoneid_t
30581 ip_get_zoneid_v6(in6_addr_t *addr, mblk_t *mp, const ill_t *ill,
30582     ip_stack_t *ipst, zoneid_t lookup_zoneid)
30583 {
30584 	ire_t		*ire;
30585 	int		ire_flags = MATCH_IRE_TYPE;
30586 	zoneid_t	zoneid = ALL_ZONES;
30587 	ipif_t		*ipif_arg = NULL;
30588 
30589 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE))
30590 		return (ALL_ZONES);
30591 
30592 	if (IN6_IS_ADDR_LINKLOCAL(addr)) {
30593 		ire_flags |= MATCH_IRE_ILL_GROUP;
30594 		ipif_arg = ill->ill_ipif;
30595 	}
30596 	if (lookup_zoneid != ALL_ZONES)
30597 		ire_flags |= MATCH_IRE_ZONEONLY;
30598 	ire = ire_ctable_lookup_v6(addr, NULL, IRE_LOCAL | IRE_LOOPBACK,
30599 	    ipif_arg, lookup_zoneid, NULL, ire_flags, ipst);
30600 	if (ire != NULL) {
30601 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
30602 		ire_refrele(ire);
30603 	}
30604 	return (zoneid);
30605 }
30606 
30607 /*
30608  * IP obserability hook support functions.
30609  */
30610 
30611 static void
30612 ipobs_init(ip_stack_t *ipst)
30613 {
30614 	ipst->ips_ipobs_enabled = B_FALSE;
30615 	list_create(&ipst->ips_ipobs_cb_list, sizeof (ipobs_cb_t),
30616 	    offsetof(ipobs_cb_t, ipobs_cbnext));
30617 	mutex_init(&ipst->ips_ipobs_cb_lock, NULL, MUTEX_DEFAULT, NULL);
30618 	ipst->ips_ipobs_cb_nwalkers = 0;
30619 	cv_init(&ipst->ips_ipobs_cb_cv, NULL, CV_DRIVER, NULL);
30620 }
30621 
30622 static void
30623 ipobs_fini(ip_stack_t *ipst)
30624 {
30625 	ipobs_cb_t *cb;
30626 
30627 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30628 	while (ipst->ips_ipobs_cb_nwalkers != 0)
30629 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
30630 
30631 	while ((cb = list_head(&ipst->ips_ipobs_cb_list)) != NULL) {
30632 		list_remove(&ipst->ips_ipobs_cb_list, cb);
30633 		kmem_free(cb, sizeof (*cb));
30634 	}
30635 	list_destroy(&ipst->ips_ipobs_cb_list);
30636 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30637 	mutex_destroy(&ipst->ips_ipobs_cb_lock);
30638 	cv_destroy(&ipst->ips_ipobs_cb_cv);
30639 }
30640 
30641 void
30642 ipobs_hook(mblk_t *mp, int htype, zoneid_t zsrc, zoneid_t zdst,
30643     const ill_t *ill, int ipver, uint32_t hlen, ip_stack_t *ipst)
30644 {
30645 	ipobs_cb_t *ipobs_cb;
30646 
30647 	ASSERT(DB_TYPE(mp) == M_DATA);
30648 
30649 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30650 	ipst->ips_ipobs_cb_nwalkers++;
30651 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30652 	for (ipobs_cb = list_head(&ipst->ips_ipobs_cb_list); ipobs_cb != NULL;
30653 	    ipobs_cb = list_next(&ipst->ips_ipobs_cb_list, ipobs_cb)) {
30654 		mblk_t  *mp2 = allocb(sizeof (ipobs_hook_data_t),
30655 		    BPRI_HI);
30656 		if (mp2 != NULL) {
30657 			ipobs_hook_data_t *ihd =
30658 			    (ipobs_hook_data_t *)mp2->b_rptr;
30659 			if (((ihd->ihd_mp = dupmsg(mp)) == NULL) &&
30660 			    ((ihd->ihd_mp = copymsg(mp)) == NULL)) {
30661 				freemsg(mp2);
30662 				continue;
30663 			}
30664 			ihd->ihd_mp->b_rptr += hlen;
30665 			ihd->ihd_htype = htype;
30666 			ihd->ihd_ipver = ipver;
30667 			ihd->ihd_zsrc = zsrc;
30668 			ihd->ihd_zdst = zdst;
30669 			ihd->ihd_ifindex = ill->ill_phyint->phyint_ifindex;
30670 			ihd->ihd_stack = ipst->ips_netstack;
30671 			mp2->b_wptr += sizeof (*ihd);
30672 			ipobs_cb->ipobs_cbfunc(mp2);
30673 		}
30674 	}
30675 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30676 	ipst->ips_ipobs_cb_nwalkers--;
30677 	if (ipst->ips_ipobs_cb_nwalkers == 0)
30678 		cv_broadcast(&ipst->ips_ipobs_cb_cv);
30679 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30680 }
30681 
30682 void
30683 ipobs_register_hook(netstack_t *ns, pfv_t func)
30684 {
30685 	ipobs_cb_t   *cb;
30686 	ip_stack_t *ipst = ns->netstack_ip;
30687 
30688 	cb = kmem_alloc(sizeof (*cb), KM_SLEEP);
30689 
30690 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30691 	while (ipst->ips_ipobs_cb_nwalkers != 0)
30692 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
30693 	ASSERT(ipst->ips_ipobs_cb_nwalkers == 0);
30694 
30695 	cb->ipobs_cbfunc = func;
30696 	list_insert_head(&ipst->ips_ipobs_cb_list, cb);
30697 	ipst->ips_ipobs_enabled = B_TRUE;
30698 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30699 }
30700 
30701 void
30702 ipobs_unregister_hook(netstack_t *ns, pfv_t func)
30703 {
30704 	ipobs_cb_t	*curcb;
30705 	ip_stack_t	*ipst = ns->netstack_ip;
30706 
30707 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30708 	while (ipst->ips_ipobs_cb_nwalkers != 0)
30709 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
30710 
30711 	for (curcb = list_head(&ipst->ips_ipobs_cb_list); curcb != NULL;
30712 	    curcb = list_next(&ipst->ips_ipobs_cb_list, curcb)) {
30713 		if (func == curcb->ipobs_cbfunc) {
30714 			list_remove(&ipst->ips_ipobs_cb_list, curcb);
30715 			kmem_free(curcb, sizeof (*curcb));
30716 			break;
30717 		}
30718 	}
30719 	if (list_is_empty(&ipst->ips_ipobs_cb_list))
30720 		ipst->ips_ipobs_enabled = B_FALSE;
30721 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30722 }
30723