xref: /illumos-gate/usr/src/uts/common/inet/ip/ip.c (revision e7437265dc2a4920c197ed4337665539d358b22c)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 /* Copyright (c) 1990 Mentat Inc. */
27 
28 #pragma ident	"%Z%%M%	%I%	%E% SMI"
29 
30 #include <sys/types.h>
31 #include <sys/stream.h>
32 #include <sys/dlpi.h>
33 #include <sys/stropts.h>
34 #include <sys/sysmacros.h>
35 #include <sys/strsubr.h>
36 #include <sys/strlog.h>
37 #include <sys/strsun.h>
38 #include <sys/zone.h>
39 #define	_SUN_TPI_VERSION 2
40 #include <sys/tihdr.h>
41 #include <sys/xti_inet.h>
42 #include <sys/ddi.h>
43 #include <sys/sunddi.h>
44 #include <sys/cmn_err.h>
45 #include <sys/debug.h>
46 #include <sys/kobj.h>
47 #include <sys/modctl.h>
48 #include <sys/atomic.h>
49 #include <sys/policy.h>
50 #include <sys/priv.h>
51 
52 #include <sys/systm.h>
53 #include <sys/param.h>
54 #include <sys/kmem.h>
55 #include <sys/sdt.h>
56 #include <sys/socket.h>
57 #include <sys/vtrace.h>
58 #include <sys/isa_defs.h>
59 #include <net/if.h>
60 #include <net/if_arp.h>
61 #include <net/route.h>
62 #include <sys/sockio.h>
63 #include <netinet/in.h>
64 #include <net/if_dl.h>
65 
66 #include <inet/common.h>
67 #include <inet/mi.h>
68 #include <inet/mib2.h>
69 #include <inet/nd.h>
70 #include <inet/arp.h>
71 #include <inet/snmpcom.h>
72 #include <inet/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/optcom.h>
91 #include <inet/ip_ndp.h>
92 #include <inet/ip_listutils.h>
93 #include <netinet/igmp.h>
94 #include <netinet/ip_mroute.h>
95 #include <inet/ipp_common.h>
96 
97 #include <net/pfkeyv2.h>
98 #include <inet/ipsec_info.h>
99 #include <inet/sadb.h>
100 #include <inet/ipsec_impl.h>
101 #include <sys/iphada.h>
102 #include <inet/tun.h>
103 #include <inet/ipdrop.h>
104 #include <inet/ip_netinfo.h>
105 
106 #include <sys/ethernet.h>
107 #include <net/if_types.h>
108 #include <sys/cpuvar.h>
109 
110 #include <ipp/ipp.h>
111 #include <ipp/ipp_impl.h>
112 #include <ipp/ipgpc/ipgpc.h>
113 
114 #include <sys/multidata.h>
115 #include <sys/pattr.h>
116 
117 #include <inet/ipclassifier.h>
118 #include <inet/sctp_ip.h>
119 #include <inet/sctp/sctp_impl.h>
120 #include <inet/udp_impl.h>
121 #include <sys/sunddi.h>
122 
123 #include <sys/tsol/label.h>
124 #include <sys/tsol/tnet.h>
125 
126 #include <rpc/pmap_prot.h>
127 
128 /*
129  * Values for squeue switch:
130  * IP_SQUEUE_ENTER_NODRAIN: squeue_enter_nodrain
131  * IP_SQUEUE_ENTER: squeue_enter
132  * IP_SQUEUE_FILL: squeue_fill
133  */
134 int ip_squeue_enter = 2;	/* Setable in /etc/system */
135 
136 squeue_func_t ip_input_proc;
137 #define	SET_BPREV_FLAG(x)	((mblk_t *)(uintptr_t)(x))
138 
139 #define	TCP6 "tcp6"
140 #define	TCP "tcp"
141 #define	SCTP "sctp"
142 #define	SCTP6 "sctp6"
143 
144 major_t TCP6_MAJ;
145 major_t TCP_MAJ;
146 major_t SCTP_MAJ;
147 major_t SCTP6_MAJ;
148 
149 /*
150  * Setable in /etc/system
151  */
152 int ip_poll_normal_ms = 100;
153 int ip_poll_normal_ticks = 0;
154 int ip_modclose_ackwait_ms = 3000;
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  * Synchronization notes:
201  *
202  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
203  * MT level protection given by STREAMS. IP uses a combination of its own
204  * internal serialization mechanism and standard Solaris locking techniques.
205  * The internal serialization is per phyint (no IPMP) or per IPMP group.
206  * This is used to serialize plumbing operations, IPMP operations, certain
207  * multicast operations, most set ioctls, igmp/mld timers etc.
208  *
209  * Plumbing is a long sequence of operations involving message
210  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
211  * involved in plumbing operations. A natural model is to serialize these
212  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
213  * parallel without any interference. But various set ioctls on hme0 are best
214  * serialized. However if the system uses IPMP, the operations are easier if
215  * they are serialized on a per IPMP group basis since IPMP operations
216  * happen across ill's of a group. Thus the lowest common denominator is to
217  * serialize most set ioctls, multicast join/leave operations, IPMP operations
218  * igmp/mld timer operations, and processing of DLPI control messages received
219  * from drivers on a per IPMP group basis. If the system does not employ
220  * IPMP the serialization is on a per phyint basis. This serialization is
221  * provided by the ipsq_t and primitives operating on this. Details can
222  * be found in ip_if.c above the core primitives operating on ipsq_t.
223  *
224  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
225  * Simiarly lookup of an ire by a thread also returns a refheld ire.
226  * In addition ipif's and ill's referenced by the ire are also indirectly
227  * refheld. Thus no ipif or ill can vanish nor can critical parameters like
228  * the ipif's address or netmask change as long as an ipif is refheld
229  * directly or indirectly. For example an SIOCLIFADDR ioctl that changes the
230  * address of an ipif has to go through the ipsq_t. This ensures that only
231  * 1 such exclusive operation proceeds at any time on the ipif. It then
232  * deletes all ires associated with this ipif, and waits for all refcnts
233  * associated with this ipif to come down to zero. The address is changed
234  * only after the ipif has been quiesced. Then the ipif is brought up again.
235  * More details are described above the comment in ip_sioctl_flags.
236  *
237  * Packet processing is based mostly on IREs and are fully multi-threaded
238  * using standard Solaris MT techniques.
239  *
240  * There are explicit locks in IP to handle:
241  * - The ip_g_head list maintained by mi_open_link() and friends.
242  *
243  * - The reassembly data structures (one lock per hash bucket)
244  *
245  * - conn_lock is meant to protect conn_t fields. The fields actually
246  *   protected by conn_lock are documented in the conn_t definition.
247  *
248  * - ire_lock to protect some of the fields of the ire, IRE tables
249  *   (one lock per hash bucket). Refer to ip_ire.c for details.
250  *
251  * - ndp_g_lock and nce_lock for protecting NCEs.
252  *
253  * - ill_lock protects fields of the ill and ipif. Details in ip.h
254  *
255  * - ill_g_lock: This is a global reader/writer lock. Protects the following
256  *	* The AVL tree based global multi list of all ills.
257  *	* The linked list of all ipifs of an ill
258  *	* The <ill-ipsq> mapping
259  *	* The ipsq->ipsq_phyint_list threaded by phyint_ipsq_next
260  *	* The illgroup list threaded by ill_group_next.
261  *	* <ill-phyint> association
262  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
263  *   into an ill, changing the <ill-ipsq> mapping of an ill, insertion/deletion
264  *   of an ill into the illgrp list, changing the <ill-phyint> assoc of an ill
265  *   will all have to hold the ill_g_lock as writer for the actual duration
266  *   of the insertion/deletion/change. More details about the <ill-ipsq> mapping
267  *   may be found in the IPMP section.
268  *
269  * - ill_lock:  This is a per ill mutex.
270  *   It protects some members of the ill and is documented below.
271  *   It also protects the <ill-ipsq> mapping
272  *   It also protects the illgroup list threaded by ill_group_next.
273  *   It also protects the <ill-phyint> assoc.
274  *   It also protects the list of ipifs hanging off the ill.
275  *
276  * - ipsq_lock: This is a per ipsq_t mutex lock.
277  *   This protects all the other members of the ipsq struct except
278  *   ipsq_refs and ipsq_phyint_list which are protected by ill_g_lock
279  *
280  * - illgrp_lock: This is a per ill_group mutex lock.
281  *   The only thing it protects is the illgrp_ill_schednext member of ill_group
282  *   which dictates which is the next ill in an ill_group that is to be chosen
283  *   for sending outgoing packets, through creation of an IRE_CACHE that
284  *   references this ill.
285  *
286  * - phyint_lock: This is a per phyint mutex lock. Protects just the
287  *   phyint_flags
288  *
289  * - ip_g_nd_lock: This is a global reader/writer lock.
290  *   Any call to nd_load to load a new parameter to the ND table must hold the
291  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
292  *   as reader.
293  *
294  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
295  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
296  *   uniqueness check also done atomically.
297  *
298  * - ipsec_capab_ills_lock: This readers/writer lock protects the global
299  *   lists of IPsec capable ills (ipsec_capab_ills_{ah,esp}). It is taken
300  *   as a writer when adding or deleting elements from these lists, and
301  *   as a reader when walking these lists to send a SADB update to the
302  *   IPsec capable ills.
303  *
304  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
305  *   group list linked by ill_usesrc_grp_next. It also protects the
306  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
307  *   group is being added or deleted.  This lock is taken as a reader when
308  *   walking the list/group(eg: to get the number of members in a usesrc group).
309  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
310  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
311  *   example, it is not necessary to take this lock in the initial portion
312  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_groupname and
313  *   ip_sioctl_flags since the these operations are executed exclusively and
314  *   that ensures that the "usesrc group state" cannot change. The "usesrc
315  *   group state" change can happen only in the latter part of
316  *   ip_sioctl_slifusesrc and in ill_delete.
317  *
318  * Changing <ill-phyint>, <ill-ipsq>, <ill-illgroup> assocications.
319  *
320  * To change the <ill-phyint> association, the ill_g_lock must be held
321  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
322  * must be held.
323  *
324  * To change the <ill-ipsq> association the ill_g_lock must be held as writer
325  * and the ill_lock of the ill in question must be held.
326  *
327  * To change the <ill-illgroup> association the ill_g_lock must be held as
328  * writer and the ill_lock of the ill in question must be held.
329  *
330  * To add or delete an ipif from the list of ipifs hanging off the ill,
331  * ill_g_lock (writer) and ill_lock must be held and the thread must be
332  * a writer on the associated ipsq,.
333  *
334  * To add or delete an ill to the system, the ill_g_lock must be held as
335  * writer and the thread must be a writer on the associated ipsq.
336  *
337  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
338  * must be a writer on the associated ipsq.
339  *
340  * Lock hierarchy
341  *
342  * Some lock hierarchy scenarios are listed below.
343  *
344  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock
345  * ill_g_lock -> illgrp_lock -> ill_lock
346  * ill_g_lock -> ill_lock(s) -> phyint_lock
347  * ill_g_lock -> ndp_g_lock -> ill_lock -> nce_lock
348  * ill_g_lock -> ip_addr_avail_lock
349  * conn_lock -> irb_lock -> ill_lock -> ire_lock
350  * ill_g_lock -> ip_g_nd_lock
351  *
352  * When more than 1 ill lock is needed to be held, all ill lock addresses
353  * are sorted on address and locked starting from highest addressed lock
354  * downward.
355  *
356  * Mobile-IP scenarios
357  *
358  * irb_lock -> ill_lock -> ire_mrtun_lock
359  * irb_lock -> ill_lock -> ire_srcif_table_lock
360  *
361  * IPsec scenarios
362  *
363  * ipsa_lock -> ill_g_lock -> ill_lock
364  * ipsec_capab_ills_lock -> ill_g_lock -> ill_lock
365  * ipsec_capab_ills_lock -> ipsa_lock
366  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
367  *
368  * Trusted Solaris scenarios
369  *
370  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
371  * igsa_lock -> gcdb_lock
372  * gcgrp_rwlock -> ire_lock
373  * gcgrp_rwlock -> gcdb_lock
374  *
375  *
376  * Routing/forwarding table locking notes:
377  *
378  * Lock acquisition order: Radix tree lock, irb_lock.
379  * Requirements:
380  * i.  Walker must not hold any locks during the walker callback.
381  * ii  Walker must not see a truncated tree during the walk because of any node
382  *     deletion.
383  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
384  *     in many places in the code to walk the irb list. Thus even if all the
385  *     ires in a bucket have been deleted, we still can't free the radix node
386  *     until the ires have actually been inactive'd (freed).
387  *
388  * Tree traversal - Need to hold the global tree lock in read mode.
389  * Before dropping the global tree lock, need to either increment the ire_refcnt
390  * to ensure that the radix node can't be deleted.
391  *
392  * Tree add - Need to hold the global tree lock in write mode to add a
393  * radix node. To prevent the node from being deleted, increment the
394  * irb_refcnt, after the node is added to the tree. The ire itself is
395  * added later while holding the irb_lock, but not the tree lock.
396  *
397  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
398  * All associated ires must be inactive (i.e. freed), and irb_refcnt
399  * must be zero.
400  *
401  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
402  * global tree lock (read mode) for traversal.
403  *
404  * IPSEC notes :
405  *
406  * IP interacts with the IPSEC code (AH/ESP) by tagging a M_CTL message
407  * in front of the actual packet. For outbound datagrams, the M_CTL
408  * contains a ipsec_out_t (defined in ipsec_info.h), which has the
409  * information used by the IPSEC code for applying the right level of
410  * protection. The information initialized by IP in the ipsec_out_t
411  * is determined by the per-socket policy or global policy in the system.
412  * For inbound datagrams, the M_CTL contains a ipsec_in_t (defined in
413  * ipsec_info.h) which starts out with nothing in it. It gets filled
414  * with the right information if it goes through the AH/ESP code, which
415  * happens if the incoming packet is secure. The information initialized
416  * by AH/ESP, is later used by IP(during fanouts to ULP) to see whether
417  * the policy requirements needed by per-socket policy or global policy
418  * is met or not.
419  *
420  * If there is both per-socket policy (set using setsockopt) and there
421  * is also global policy match for the 5 tuples of the socket,
422  * ipsec_override_policy() makes the decision of which one to use.
423  *
424  * For fully connected sockets i.e dst, src [addr, port] is known,
425  * conn_policy_cached is set indicating that policy has been cached.
426  * conn_in_enforce_policy may or may not be set depending on whether
427  * there is a global policy match or per-socket policy match.
428  * Policy inheriting happpens in ip_bind during the ipa_conn_t bind.
429  * Once the right policy is set on the conn_t, policy cannot change for
430  * this socket. This makes life simpler for TCP (UDP ?) where
431  * re-transmissions go out with the same policy. For symmetry, policy
432  * is cached for fully connected UDP sockets also. Thus if policy is cached,
433  * it also implies that policy is latched i.e policy cannot change
434  * on these sockets. As we have the right policy on the conn, we don't
435  * have to lookup global policy for every outbound and inbound datagram
436  * and thus serving as an optimization. Note that a global policy change
437  * does not affect fully connected sockets if they have policy. If fully
438  * connected sockets did not have any policy associated with it, global
439  * policy change may affect them.
440  *
441  * IP Flow control notes:
442  *
443  * Non-TCP streams are flow controlled by IP. On the send side, if the packet
444  * cannot be sent down to the driver by IP, because of a canput failure, IP
445  * does a putq on the conn_wq. This will cause ip_wsrv to run on the conn_wq.
446  * ip_wsrv in turn, inserts the conn in a list of conn's that need to be drained
447  * when the flowcontrol condition subsides. Ultimately STREAMS backenables the
448  * ip_wsrv on the IP module, which in turn does a qenable of the conn_wq of the
449  * first conn in the list of conn's to be drained. ip_wsrv on this conn drains
450  * the queued messages, and removes the conn from the drain list, if all
451  * messages were drained. It also qenables the next conn in the drain list to
452  * continue the drain process.
453  *
454  * In reality the drain list is not a single list, but a configurable number
455  * of lists. The ip_wsrv on the IP module, qenables the first conn in each
456  * list. If the ip_wsrv of the next qenabled conn does not run, because the
457  * stream closes, ip_close takes responsibility to qenable the next conn in
458  * the drain list. The directly called ip_wput path always does a putq, if
459  * it cannot putnext. Thus synchronization problems are handled between
460  * ip_wsrv and ip_close. conn_drain_insert and conn_drain_tail are the only
461  * functions that manipulate this drain list. Furthermore conn_drain_insert
462  * is called only from ip_wsrv, and there can be only 1 instance of ip_wsrv
463  * running on a queue at any time. conn_drain_tail can be simultaneously called
464  * from both ip_wsrv and ip_close.
465  *
466  * IPQOS notes:
467  *
468  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
469  * and IPQoS modules. IPPF includes hooks in IP at different control points
470  * (callout positions) which direct packets to IPQoS modules for policy
471  * processing. Policies, if present, are global.
472  *
473  * The callout positions are located in the following paths:
474  *		o local_in (packets destined for this host)
475  *		o local_out (packets orginating from this host )
476  *		o fwd_in  (packets forwarded by this m/c - inbound)
477  *		o fwd_out (packets forwarded by this m/c - outbound)
478  * Hooks at these callout points can be enabled/disabled using the ndd variable
479  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
480  * By default all the callout positions are enabled.
481  *
482  * Outbound (local_out)
483  * Hooks are placed in ip_wput_ire and ipsec_out_process.
484  *
485  * Inbound (local_in)
486  * Hooks are placed in ip_proto_input, icmp_inbound, ip_fanout_proto and
487  * TCP and UDP fanout routines.
488  *
489  * Forwarding (in and out)
490  * Hooks are placed in ip_rput_forward and ip_mrtun_forward.
491  *
492  * IP Policy Framework processing (IPPF processing)
493  * Policy processing for a packet is initiated by ip_process, which ascertains
494  * that the classifier (ipgpc) is loaded and configured, failing which the
495  * packet resumes normal processing in IP. If the clasifier is present, the
496  * packet is acted upon by one or more IPQoS modules (action instances), per
497  * filters configured in ipgpc and resumes normal IP processing thereafter.
498  * An action instance can drop a packet in course of its processing.
499  *
500  * A boolean variable, ip_policy, is used in all the fanout routines that can
501  * invoke ip_process for a packet. This variable indicates if the packet should
502  * to be sent for policy processing. The variable is set to B_TRUE by default,
503  * i.e. when the routines are invoked in the normal ip procesing path for a
504  * packet. The two exceptions being ip_wput_local and icmp_inbound_error_fanout;
505  * ip_policy is set to B_FALSE for all the routines called in these two
506  * functions because, in the former case,  we don't process loopback traffic
507  * currently while in the latter, the packets have already been processed in
508  * icmp_inbound.
509  *
510  * Zones notes:
511  *
512  * The partitioning rules for networking are as follows:
513  * 1) Packets coming from a zone must have a source address belonging to that
514  * zone.
515  * 2) Packets coming from a zone can only be sent on a physical interface on
516  * which the zone has an IP address.
517  * 3) Between two zones on the same machine, packet delivery is only allowed if
518  * there's a matching route for the destination and zone in the forwarding
519  * table.
520  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
521  * different zones can bind to the same port with the wildcard address
522  * (INADDR_ANY).
523  *
524  * The granularity of interface partitioning is at the logical interface level.
525  * Therefore, every zone has its own IP addresses, and incoming packets can be
526  * attributed to a zone unambiguously. A logical interface is placed into a zone
527  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
528  * structure. Rule (1) is implemented by modifying the source address selection
529  * algorithm so that the list of eligible addresses is filtered based on the
530  * sending process zone.
531  *
532  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
533  * across all zones, depending on their type. Here is the break-up:
534  *
535  * IRE type				Shared/exclusive
536  * --------				----------------
537  * IRE_BROADCAST			Exclusive
538  * IRE_DEFAULT (default routes)		Shared (*)
539  * IRE_LOCAL				Exclusive (x)
540  * IRE_LOOPBACK				Exclusive
541  * IRE_PREFIX (net routes)		Shared (*)
542  * IRE_CACHE				Exclusive
543  * IRE_IF_NORESOLVER (interface routes)	Exclusive
544  * IRE_IF_RESOLVER (interface routes)	Exclusive
545  * IRE_HOST (host routes)		Shared (*)
546  *
547  * (*) A zone can only use a default or off-subnet route if the gateway is
548  * directly reachable from the zone, that is, if the gateway's address matches
549  * one of the zone's logical interfaces.
550  *
551  * (x) IRE_LOCAL are handled a bit differently, since for all other entries
552  * in ire_ctable and IRE_INTERFACE, ire_src_addr is what can be used as source
553  * when sending packets using the IRE. For IRE_LOCAL ire_src_addr is the IP
554  * address of the zone itself (the destination). Since IRE_LOCAL is used
555  * for communication between zones, ip_wput_ire has special logic to set
556  * the right source address when sending using an IRE_LOCAL.
557  *
558  * Furthermore, when ip_restrict_interzone_loopback is set (the default),
559  * ire_cache_lookup restricts loopback using an IRE_LOCAL
560  * between zone to the case when L2 would have conceptually looped the packet
561  * back, i.e. the loopback which is required since neither Ethernet drivers
562  * nor Ethernet hardware loops them back. This is the case when the normal
563  * routes (ignoring IREs with different zoneids) would send out the packet on
564  * the same ill (or ill group) as the ill with which is IRE_LOCAL is
565  * associated.
566  *
567  * Multiple zones can share a common broadcast address; typically all zones
568  * share the 255.255.255.255 address. Incoming as well as locally originated
569  * broadcast packets must be dispatched to all the zones on the broadcast
570  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
571  * since some zones may not be on the 10.16.72/24 network. To handle this, each
572  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
573  * sent to every zone that has an IRE_BROADCAST entry for the destination
574  * address on the input ill, see conn_wantpacket().
575  *
576  * Applications in different zones can join the same multicast group address.
577  * For IPv4, group memberships are per-logical interface, so they're already
578  * inherently part of a zone. For IPv6, group memberships are per-physical
579  * interface, so we distinguish IPv6 group memberships based on group address,
580  * interface and zoneid. In both cases, received multicast packets are sent to
581  * every zone for which a group membership entry exists. On IPv6 we need to
582  * check that the target zone still has an address on the receiving physical
583  * interface; it could have been removed since the application issued the
584  * IPV6_JOIN_GROUP.
585  */
586 
587 /*
588  * Squeue Fanout flags:
589  *	0: No fanout.
590  *	1: Fanout across all squeues
591  */
592 boolean_t	ip_squeue_fanout = 0;
593 
594 /*
595  * Maximum dups allowed per packet.
596  */
597 uint_t ip_max_frag_dups = 10;
598 
599 #define	IS_SIMPLE_IPH(ipha)						\
600 	((ipha)->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION)
601 
602 /* RFC1122 Conformance */
603 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
604 
605 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
606 
607 static int	conn_set_held_ipif(conn_t *, ipif_t **, ipif_t *);
608 
609 static mblk_t	*ip_wput_attach_llhdr(mblk_t *, ire_t *, ip_proc_t, uint32_t);
610 static void	ip_ipsec_out_prepend(mblk_t *, mblk_t *, ill_t *);
611 
612 static void	icmp_frag_needed(queue_t *, mblk_t *, int, zoneid_t,
613 		    ip_stack_t *);
614 static void	icmp_inbound(queue_t *, mblk_t *, boolean_t, ill_t *, int,
615 		    uint32_t, boolean_t, boolean_t, ill_t *, zoneid_t);
616 static ipaddr_t	icmp_get_nexthop_addr(ipha_t *, ill_t *, zoneid_t, mblk_t *mp);
617 static boolean_t icmp_inbound_too_big(icmph_t *, ipha_t *, ill_t *, zoneid_t,
618 		    mblk_t *, int, ip_stack_t *);
619 static void	icmp_inbound_error_fanout(queue_t *, ill_t *, mblk_t *,
620 		    icmph_t *, ipha_t *, int, int, boolean_t, boolean_t,
621 		    ill_t *, zoneid_t);
622 static void	icmp_options_update(ipha_t *);
623 static void	icmp_param_problem(queue_t *, mblk_t *, uint8_t, zoneid_t,
624 		    ip_stack_t *);
625 static void	icmp_pkt(queue_t *, mblk_t *, void *, size_t, boolean_t,
626 		    zoneid_t zoneid, ip_stack_t *);
627 static mblk_t	*icmp_pkt_err_ok(mblk_t *, ip_stack_t *);
628 static void	icmp_redirect(ill_t *, mblk_t *);
629 static void	icmp_send_redirect(queue_t *, mblk_t *, ipaddr_t,
630 		    ip_stack_t *);
631 
632 static void	ip_arp_news(queue_t *, mblk_t *);
633 static boolean_t ip_bind_insert_ire(mblk_t *, ire_t *, iulp_t *,
634 		    ip_stack_t *);
635 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
636 char		*ip_dot_addr(ipaddr_t, char *);
637 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
638 int		ip_close(queue_t *, int);
639 static char	*ip_dot_saddr(uchar_t *, char *);
640 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
641 		    boolean_t, boolean_t, ill_t *, zoneid_t);
642 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
643 		    boolean_t, boolean_t, zoneid_t);
644 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
645 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
646 static void	ip_lrput(queue_t *, mblk_t *);
647 static void	ip_mrtun_forward(ire_t *, ill_t *, mblk_t *);
648 ipaddr_t	ip_net_mask(ipaddr_t);
649 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, ill_t *, conn_t *,
650 		    zoneid_t, ip_stack_t *);
651 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
652 		    conn_t *, uint32_t, zoneid_t, ip_opt_info_t *);
653 char		*ip_nv_lookup(nv_t *, int);
654 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
655 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
656 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
657 static boolean_t	ip_param_register(IDP *ndp, ipparam_t *, size_t,
658     ipndp_t *, size_t);
659 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
660 void	ip_rput(queue_t *, mblk_t *);
661 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
662 		    void *dummy_arg);
663 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
664 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *,
665     ip_stack_t *);
666 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
667 			    ire_t *, ip_stack_t *);
668 static boolean_t	ip_rput_multimblk_ipoptions(queue_t *, ill_t *,
669 			    mblk_t *, ipha_t **, ipaddr_t *, ip_stack_t *);
670 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *,
671     ip_stack_t *);
672 static boolean_t ip_rput_fragment(queue_t *, mblk_t **, ipha_t *, uint32_t *,
673 		    uint16_t *);
674 int		ip_snmp_get(queue_t *, mblk_t *);
675 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *,
676 		    mib2_ipIfStatsEntry_t *, ip_stack_t *);
677 static mblk_t	*ip_snmp_get_mib2_ip_traffic_stats(queue_t *, mblk_t *,
678 		    ip_stack_t *);
679 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *, ip_stack_t *);
680 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *, ip_stack_t *ipst);
681 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *, ip_stack_t *ipst);
682 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *, ip_stack_t *ipst);
683 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *, ip_stack_t *ipst);
684 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *,
685 		    ip_stack_t *ipst);
686 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *,
687 		    ip_stack_t *ipst);
688 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *,
689 		    ip_stack_t *ipst);
690 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *,
691 		    ip_stack_t *ipst);
692 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *,
693 		    ip_stack_t *ipst);
694 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *,
695 		    ip_stack_t *ipst);
696 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *,
697 		    ip_stack_t *ipst);
698 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *,
699 		    ip_stack_t *ipst);
700 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *,
701 		    ip_stack_t *ipst);
702 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *,
703 		    ip_stack_t *ipst);
704 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
705 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
706 static int	ip_snmp_get2_v6_media(nce_t *, iproutedata_t *);
707 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
708 static boolean_t	ip_source_routed(ipha_t *, ip_stack_t *);
709 static boolean_t	ip_source_route_included(ipha_t *);
710 static void	ip_trash_ire_reclaim_stack(ip_stack_t *);
711 
712 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t,
713 		    zoneid_t, ip_stack_t *);
714 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int, ip_stack_t *);
715 static void	ip_wput_local_options(ipha_t *, ip_stack_t *);
716 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
717 		    zoneid_t, ip_stack_t *);
718 
719 static void	conn_drain_init(ip_stack_t *);
720 static void	conn_drain_fini(ip_stack_t *);
721 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
722 
723 static void	conn_walk_drain(ip_stack_t *);
724 static void	conn_walk_fanout_table(connf_t *, uint_t, pfv_t, void *,
725     zoneid_t);
726 
727 static void	*ip_stack_init(netstackid_t stackid, netstack_t *ns);
728 static void	ip_stack_shutdown(netstackid_t stackid, void *arg);
729 static void	ip_stack_fini(netstackid_t stackid, void *arg);
730 
731 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
732     zoneid_t);
733 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
734     void *dummy_arg);
735 
736 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
737 
738 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
739     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
740     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
741 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
742 
743 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
744 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
745     caddr_t, cred_t *);
746 extern int	ip_squeue_bind_set(queue_t *q, mblk_t *mp, char *value,
747     caddr_t cp, cred_t *cr);
748 extern int	ip_squeue_profile_set(queue_t *, mblk_t *, char *, caddr_t,
749     cred_t *);
750 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
751     caddr_t cp, cred_t *cr);
752 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
753     cred_t *);
754 static int	ipmp_hook_emulation_set(queue_t *, mblk_t *, char *, caddr_t,
755     cred_t *);
756 static squeue_func_t ip_squeue_switch(int);
757 
758 static void	*ip_kstat_init(netstackid_t, ip_stack_t *);
759 static void	ip_kstat_fini(netstackid_t, kstat_t *);
760 static int	ip_kstat_update(kstat_t *kp, int rw);
761 static void	*icmp_kstat_init(netstackid_t);
762 static void	icmp_kstat_fini(netstackid_t, kstat_t *);
763 static int	icmp_kstat_update(kstat_t *kp, int rw);
764 static void	*ip_kstat2_init(netstackid_t, ip_stat_t *);
765 static void	ip_kstat2_fini(netstackid_t, kstat_t *);
766 
767 static int	ip_conn_report(queue_t *, mblk_t *, caddr_t, cred_t *);
768 
769 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
770     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
771 
772 static void	ip_rput_process_forward(queue_t *, mblk_t *, ire_t *,
773     ipha_t *, ill_t *, boolean_t);
774 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
775 
776 /* How long, in seconds, we allow frags to hang around. */
777 #define	IP_FRAG_TIMEOUT	60
778 
779 /*
780  * Threshold which determines whether MDT should be used when
781  * generating IP fragments; payload size must be greater than
782  * this threshold for MDT to take place.
783  */
784 #define	IP_WPUT_FRAG_MDT_MIN	32768
785 
786 /* Setable in /etc/system only */
787 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
788 
789 static long ip_rput_pullups;
790 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
791 
792 vmem_t *ip_minor_arena;
793 
794 int	ip_debug;
795 
796 #ifdef DEBUG
797 uint32_t ipsechw_debug = 0;
798 #endif
799 
800 /*
801  * Multirouting/CGTP stuff
802  */
803 cgtp_filter_ops_t	*ip_cgtp_filter_ops;	/* CGTP hooks */
804 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
805 boolean_t	ip_cgtp_filter;		/* Enable/disable CGTP hooks */
806 
807 /*
808  * XXX following really should only be in a header. Would need more
809  * header and .c clean up first.
810  */
811 extern optdb_obj_t	ip_opt_obj;
812 
813 ulong_t ip_squeue_enter_unbound = 0;
814 
815 /*
816  * Named Dispatch Parameter Table.
817  * All of these are alterable, within the min/max values given, at run time.
818  */
819 static ipparam_t	lcl_param_arr[] = {
820 	/* min	max	value	name */
821 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
822 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
823 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
824 	{  0,	1,	0,	"ip_respond_to_timestamp"},
825 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
826 	{  0,	1,	1,	"ip_send_redirects"},
827 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
828 	{  0,	10,	0,	"ip_debug"},
829 	{  0,	10,	0,	"ip_mrtdebug"},
830 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
831 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
832 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
833 	{  1,	255,	255,	"ip_def_ttl" },
834 	{  0,	1,	0,	"ip_forward_src_routed"},
835 	{  0,	256,	32,	"ip_wroff_extra" },
836 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
837 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
838 	{  0,	1,	1,	"ip_path_mtu_discovery" },
839 	{  0,	240,	30,	"ip_ignore_delete_time" },
840 	{  0,	1,	0,	"ip_ignore_redirect" },
841 	{  0,	1,	1,	"ip_output_queue" },
842 	{  1,	254,	1,	"ip_broadcast_ttl" },
843 	{  0,	99999,	100,	"ip_icmp_err_interval" },
844 	{  1,	99999,	10,	"ip_icmp_err_burst" },
845 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
846 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
847 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
848 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
849 	{  0,	1,	1,	"icmp_accept_clear_messages" },
850 	{  0,	1,	1,	"igmp_accept_clear_messages" },
851 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
852 				"ip_ndp_delay_first_probe_time"},
853 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
854 				"ip_ndp_max_unicast_solicit"},
855 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
856 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
857 	{  0,	1,	0,	"ip6_forward_src_routed"},
858 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
859 	{  0,	1,	1,	"ip6_send_redirects"},
860 	{  0,	1,	0,	"ip6_ignore_redirect" },
861 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
862 
863 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
864 
865 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
866 
867 	{  0,	1,	1,	"pim_accept_clear_messages" },
868 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
869 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
870 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
871 	{  0,	15,	0,	"ip_policy_mask" },
872 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
873 	{  0,	255,	1,	"ip_multirt_ttl" },
874 	{  0,	1,	1,	"ip_multidata_outbound" },
875 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
876 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
877 	{  0,	1000,	1,	"ip_max_temp_defend" },
878 	{  0,	1000,	3,	"ip_max_defend" },
879 	{  0,	999999,	30,	"ip_defend_interval" },
880 	{  0,	3600000, 300000, "ip_dup_recovery" },
881 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
882 	{  0,	1,	1,	"ip_lso_outbound" },
883 #ifdef DEBUG
884 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
885 #else
886 	{  0,	0,	0,	"" },
887 #endif
888 };
889 
890 /*
891  * Extended NDP table
892  * The addresses for the first two are filled in to be ips_ip_g_forward
893  * and ips_ipv6_forward at init time.
894  */
895 static ipndp_t	lcl_ndp_arr[] = {
896 	/* getf			setf		data			name */
897 #define	IPNDP_IP_FORWARDING_OFFSET	0
898 	{  ip_param_generic_get,	ip_forward_set,	NULL,
899 	    "ip_forwarding" },
900 #define	IPNDP_IP6_FORWARDING_OFFSET	1
901 	{  ip_param_generic_get,	ip_forward_set,	NULL,
902 	    "ip6_forwarding" },
903 	{  ip_ill_report,	NULL,		NULL,
904 	    "ip_ill_status" },
905 	{  ip_ipif_report,	NULL,		NULL,
906 	    "ip_ipif_status" },
907 	{  ip_ire_report,	NULL,		NULL,
908 	    "ipv4_ire_status" },
909 	{  ip_ire_report_mrtun,	NULL,		NULL,
910 	    "ipv4_mrtun_ire_status" },
911 	{  ip_ire_report_srcif,	NULL,		NULL,
912 	    "ipv4_srcif_ire_status" },
913 	{  ip_ire_report_v6,	NULL,		NULL,
914 	    "ipv6_ire_status" },
915 	{  ip_conn_report,	NULL,		NULL,
916 	    "ip_conn_status" },
917 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
918 	    "ip_rput_pullups" },
919 	{  ndp_report,		NULL,		NULL,
920 	    "ip_ndp_cache_report" },
921 	{  ip_srcid_report,	NULL,		NULL,
922 	    "ip_srcid_status" },
923 	{ ip_param_generic_get, ip_squeue_profile_set,
924 	    (caddr_t)&ip_squeue_profile, "ip_squeue_profile" },
925 	{ ip_param_generic_get, ip_squeue_bind_set,
926 	    (caddr_t)&ip_squeue_bind, "ip_squeue_bind" },
927 	{ ip_param_generic_get, ip_input_proc_set,
928 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
929 	{ ip_param_generic_get, ip_int_set,
930 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
931 #define	IPNDP_CGTP_FILTER_OFFSET	16
932 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, NULL,
933 	    "ip_cgtp_filter" },
934 	{ ip_param_generic_get, ip_int_set,
935 	    (caddr_t)&ip_soft_rings_cnt, "ip_soft_rings_cnt" },
936 #define	IPNDP_IPMP_HOOK_OFFSET	18
937 	{  ip_param_generic_get, ipmp_hook_emulation_set, NULL,
938 	    "ipmp_hook_emulation" },
939 };
940 
941 /*
942  * Table of IP ioctls encoding the various properties of the ioctl and
943  * indexed based on the last byte of the ioctl command. Occasionally there
944  * is a clash, and there is more than 1 ioctl with the same last byte.
945  * In such a case 1 ioctl is encoded in the ndx table and the remaining
946  * ioctls are encoded in the misc table. An entry in the ndx table is
947  * retrieved by indexing on the last byte of the ioctl command and comparing
948  * the ioctl command with the value in the ndx table. In the event of a
949  * mismatch the misc table is then searched sequentially for the desired
950  * ioctl command.
951  *
952  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
953  */
954 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
955 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
956 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
957 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
958 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
959 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
960 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
961 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
962 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
963 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
964 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
965 
966 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
967 			MISC_CMD, ip_siocaddrt, NULL },
968 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
969 			MISC_CMD, ip_siocdelrt, NULL },
970 
971 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
972 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
973 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
974 			IF_CMD, ip_sioctl_get_addr, NULL },
975 
976 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
977 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
978 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
979 			IPI_GET_CMD | IPI_REPL,
980 			IF_CMD, ip_sioctl_get_dstaddr, NULL },
981 
982 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
983 			IPI_PRIV | IPI_WR | IPI_REPL,
984 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
985 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
986 			IPI_MODOK | IPI_GET_CMD | IPI_REPL,
987 			IF_CMD, ip_sioctl_get_flags, NULL },
988 
989 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
990 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
991 
992 	/* copyin size cannot be coded for SIOCGIFCONF */
993 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
994 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
995 
996 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
997 			IF_CMD, ip_sioctl_mtu, NULL },
998 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
999 			IF_CMD, ip_sioctl_get_mtu, NULL },
1000 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
1001 			IPI_GET_CMD | IPI_REPL,
1002 			IF_CMD, ip_sioctl_get_brdaddr, NULL },
1003 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1004 			IF_CMD, ip_sioctl_brdaddr, NULL },
1005 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
1006 			IPI_GET_CMD | IPI_REPL,
1007 			IF_CMD, ip_sioctl_get_netmask, NULL },
1008 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1009 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1010 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1011 			IPI_GET_CMD | IPI_REPL,
1012 			IF_CMD, ip_sioctl_get_metric, NULL },
1013 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1014 			IF_CMD, ip_sioctl_metric, NULL },
1015 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1016 
1017 	/* See 166-168 below for extended SIOC*XARP ioctls */
1018 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV,
1019 			MISC_CMD, ip_sioctl_arp, NULL },
1020 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD | IPI_REPL,
1021 			MISC_CMD, ip_sioctl_arp, NULL },
1022 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV,
1023 			MISC_CMD, ip_sioctl_arp, NULL },
1024 
1025 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1026 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1027 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1028 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1029 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1030 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1031 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1032 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1033 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1034 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1035 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1036 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1037 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1038 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1039 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1040 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1041 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1042 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1043 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1044 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1045 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1046 
1047 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1048 			MISC_CMD, if_unitsel, if_unitsel_restart },
1049 
1050 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1051 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1052 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1053 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1054 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1055 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1056 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1057 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1058 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1059 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1060 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1061 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1062 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1063 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1064 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1065 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1066 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1067 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1068 
1069 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1070 			IPI_PRIV | IPI_WR | IPI_MODOK,
1071 			IF_CMD, ip_sioctl_sifname, NULL },
1072 
1073 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1074 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1075 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1076 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1077 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1078 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1079 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1080 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1081 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1082 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1083 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1084 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1085 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1086 
1087 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD | IPI_REPL,
1088 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1089 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1090 			IF_CMD, ip_sioctl_get_muxid, NULL },
1091 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1092 			IPI_PRIV | IPI_WR | IPI_REPL,
1093 			IF_CMD, ip_sioctl_muxid, NULL },
1094 
1095 	/* Both if and lif variants share same func */
1096 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1097 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1098 	/* Both if and lif variants share same func */
1099 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1100 			IPI_PRIV | IPI_WR | IPI_REPL,
1101 			IF_CMD, ip_sioctl_slifindex, NULL },
1102 
1103 	/* copyin size cannot be coded for SIOCGIFCONF */
1104 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
1105 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1106 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1107 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1108 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1109 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1110 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1111 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1112 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1113 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1114 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1115 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1116 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1117 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1118 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1119 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1120 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1121 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1122 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1123 
1124 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1125 			IPI_PRIV | IPI_WR | IPI_REPL,
1126 			LIF_CMD, ip_sioctl_removeif,
1127 			ip_sioctl_removeif_restart },
1128 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1129 			IPI_GET_CMD | IPI_PRIV | IPI_WR | IPI_REPL,
1130 			LIF_CMD, ip_sioctl_addif, NULL },
1131 #define	SIOCLIFADDR_NDX 112
1132 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1133 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1134 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1135 			IPI_GET_CMD | IPI_REPL,
1136 			LIF_CMD, ip_sioctl_get_addr, NULL },
1137 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1138 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1139 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1140 			IPI_GET_CMD | IPI_REPL,
1141 			LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1142 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1143 			IPI_PRIV | IPI_WR | IPI_REPL,
1144 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1145 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1146 			IPI_GET_CMD | IPI_MODOK | IPI_REPL,
1147 			LIF_CMD, ip_sioctl_get_flags, NULL },
1148 
1149 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1150 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1151 
1152 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1153 			ip_sioctl_get_lifconf, NULL },
1154 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1155 			LIF_CMD, ip_sioctl_mtu, NULL },
1156 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD | IPI_REPL,
1157 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1158 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1159 			IPI_GET_CMD | IPI_REPL,
1160 			LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1161 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1162 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1163 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1164 			IPI_GET_CMD | IPI_REPL,
1165 			LIF_CMD, ip_sioctl_get_netmask, NULL },
1166 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1167 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1168 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1169 			IPI_GET_CMD | IPI_REPL,
1170 			LIF_CMD, ip_sioctl_get_metric, NULL },
1171 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1172 			LIF_CMD, ip_sioctl_metric, NULL },
1173 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1174 			IPI_PRIV | IPI_WR | IPI_MODOK | IPI_REPL,
1175 			LIF_CMD, ip_sioctl_slifname,
1176 			ip_sioctl_slifname_restart },
1177 
1178 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD | IPI_REPL,
1179 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1180 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1181 			IPI_GET_CMD | IPI_REPL,
1182 			LIF_CMD, ip_sioctl_get_muxid, NULL },
1183 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1184 			IPI_PRIV | IPI_WR | IPI_REPL,
1185 			LIF_CMD, ip_sioctl_muxid, NULL },
1186 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1187 			IPI_GET_CMD | IPI_REPL,
1188 			LIF_CMD, ip_sioctl_get_lifindex, 0 },
1189 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1190 			IPI_PRIV | IPI_WR | IPI_REPL,
1191 			LIF_CMD, ip_sioctl_slifindex, 0 },
1192 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1193 			LIF_CMD, ip_sioctl_token, NULL },
1194 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1195 			IPI_GET_CMD | IPI_REPL,
1196 			LIF_CMD, ip_sioctl_get_token, NULL },
1197 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1198 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1199 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1200 			IPI_GET_CMD | IPI_REPL,
1201 			LIF_CMD, ip_sioctl_get_subnet, NULL },
1202 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1203 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1204 
1205 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1206 			IPI_GET_CMD | IPI_REPL,
1207 			LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1208 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1209 			LIF_CMD, ip_siocdelndp_v6, NULL },
1210 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1211 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1212 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1213 			LIF_CMD, ip_siocsetndp_v6, NULL },
1214 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1215 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1216 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1217 			MISC_CMD, ip_sioctl_tonlink, NULL },
1218 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1219 			MISC_CMD, ip_sioctl_tmysite, NULL },
1220 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), IPI_REPL,
1221 			TUN_CMD, ip_sioctl_tunparam, NULL },
1222 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1223 			IPI_PRIV | IPI_WR,
1224 			TUN_CMD, ip_sioctl_tunparam, NULL },
1225 
1226 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1227 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1228 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1229 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1230 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1231 
1232 	/* 153 */ { SIOCLIFFAILOVER, sizeof (struct lifreq),
1233 			IPI_PRIV | IPI_WR | IPI_REPL,
1234 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1235 	/* 154 */ { SIOCLIFFAILBACK, sizeof (struct lifreq),
1236 			IPI_PRIV | IPI_WR | IPI_REPL,
1237 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1238 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1239 			IPI_PRIV | IPI_WR,
1240 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1241 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1242 			IPI_GET_CMD | IPI_REPL,
1243 			LIF_CMD, ip_sioctl_get_groupname, NULL },
1244 	/* 157 */ { SIOCGLIFOINDEX, sizeof (struct lifreq),
1245 			IPI_GET_CMD | IPI_REPL,
1246 			LIF_CMD, ip_sioctl_get_oindex, NULL },
1247 
1248 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1249 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1250 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1251 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1252 
1253 	/* 161 */ { SIOCSLIFOINDEX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1254 		    LIF_CMD, ip_sioctl_slifoindex, NULL },
1255 
1256 	/* These are handled in ip_sioctl_copyin_setup itself */
1257 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1258 			MISC_CMD, NULL, NULL },
1259 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1260 			MISC_CMD, NULL, NULL },
1261 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1262 
1263 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1264 			ip_sioctl_get_lifconf, NULL },
1265 
1266 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV,
1267 			MISC_CMD, ip_sioctl_xarp, NULL },
1268 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD | IPI_REPL,
1269 			MISC_CMD, ip_sioctl_xarp, NULL },
1270 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV,
1271 			MISC_CMD, ip_sioctl_xarp, NULL },
1272 
1273 	/* SIOCPOPSOCKFS is not handled by IP */
1274 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1275 
1276 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1277 			IPI_GET_CMD | IPI_REPL,
1278 			LIF_CMD, ip_sioctl_get_lifzone, NULL },
1279 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1280 			IPI_PRIV | IPI_WR | IPI_REPL,
1281 			LIF_CMD, ip_sioctl_slifzone,
1282 			ip_sioctl_slifzone_restart },
1283 	/* 172-174 are SCTP ioctls and not handled by IP */
1284 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1285 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1286 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1287 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1288 			IPI_GET_CMD, LIF_CMD,
1289 			ip_sioctl_get_lifusesrc, 0 },
1290 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1291 			IPI_PRIV | IPI_WR,
1292 			LIF_CMD, ip_sioctl_slifusesrc,
1293 			NULL },
1294 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1295 			ip_sioctl_get_lifsrcof, NULL },
1296 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1297 			MISC_CMD, ip_sioctl_msfilter, NULL },
1298 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1299 			MISC_CMD, ip_sioctl_msfilter, NULL },
1300 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1301 			MISC_CMD, ip_sioctl_msfilter, NULL },
1302 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1303 			MISC_CMD, ip_sioctl_msfilter, NULL },
1304 	/* 182 */ { SIOCSIPMPFAILBACK, sizeof (int), IPI_PRIV, MISC_CMD,
1305 			ip_sioctl_set_ipmpfailback, NULL }
1306 };
1307 
1308 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1309 
1310 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1311 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1312 		IPI_GET_CMD | IPI_REPL, TUN_CMD, ip_sioctl_tunparam, NULL },
1313 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1314 		TUN_CMD, ip_sioctl_tunparam, NULL },
1315 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1316 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1317 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1318 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1319 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1320 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1321 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1322 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_REPL | IPI_GET_CMD,
1323 		MISC_CMD, mrt_ioctl},
1324 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_REPL | IPI_GET_CMD,
1325 		MISC_CMD, mrt_ioctl},
1326 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_REPL | IPI_GET_CMD,
1327 		MISC_CMD, mrt_ioctl}
1328 };
1329 
1330 int ip_misc_ioctl_count =
1331     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1332 
1333 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1334 					/* Settable in /etc/system */
1335 /* Defined in ip_ire.c */
1336 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1337 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1338 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1339 
1340 static nv_t	ire_nv_arr[] = {
1341 	{ IRE_BROADCAST, "BROADCAST" },
1342 	{ IRE_LOCAL, "LOCAL" },
1343 	{ IRE_LOOPBACK, "LOOPBACK" },
1344 	{ IRE_CACHE, "CACHE" },
1345 	{ IRE_DEFAULT, "DEFAULT" },
1346 	{ IRE_PREFIX, "PREFIX" },
1347 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1348 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1349 	{ IRE_HOST, "HOST" },
1350 	{ 0 }
1351 };
1352 
1353 nv_t	*ire_nv_tbl = ire_nv_arr;
1354 
1355 /* Defined in ip_netinfo.c */
1356 extern ddi_taskq_t	*eventq_queue_nic;
1357 
1358 /* Simple ICMP IP Header Template */
1359 static ipha_t icmp_ipha = {
1360 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1361 };
1362 
1363 struct module_info ip_mod_info = {
1364 	IP_MOD_ID, IP_MOD_NAME, 1, INFPSZ, 65536, 1024
1365 };
1366 
1367 /*
1368  * Duplicate static symbols within a module confuses mdb; so we avoid the
1369  * problem by making the symbols here distinct from those in udp.c.
1370  */
1371 
1372 static struct qinit iprinit = {
1373 	(pfi_t)ip_rput, NULL, ip_open, ip_close, NULL,
1374 	&ip_mod_info
1375 };
1376 
1377 static struct qinit ipwinit = {
1378 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, ip_open, ip_close, NULL,
1379 	&ip_mod_info
1380 };
1381 
1382 static struct qinit iplrinit = {
1383 	(pfi_t)ip_lrput, NULL, ip_open, ip_close, NULL,
1384 	&ip_mod_info
1385 };
1386 
1387 static struct qinit iplwinit = {
1388 	(pfi_t)ip_lwput, NULL, ip_open, ip_close, NULL,
1389 	&ip_mod_info
1390 };
1391 
1392 struct streamtab ipinfo = {
1393 	&iprinit, &ipwinit, &iplrinit, &iplwinit
1394 };
1395 
1396 #ifdef	DEBUG
1397 static boolean_t skip_sctp_cksum = B_FALSE;
1398 #endif
1399 
1400 /*
1401  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1402  * ip_rput_v6(), ip_output(), etc.  If the message
1403  * block already has a M_CTL at the front of it, then simply set the zoneid
1404  * appropriately.
1405  */
1406 mblk_t *
1407 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid, ip_stack_t *ipst)
1408 {
1409 	mblk_t		*first_mp;
1410 	ipsec_out_t	*io;
1411 
1412 	ASSERT(zoneid != ALL_ZONES);
1413 	if (mp->b_datap->db_type == M_CTL) {
1414 		io = (ipsec_out_t *)mp->b_rptr;
1415 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1416 		io->ipsec_out_zoneid = zoneid;
1417 		return (mp);
1418 	}
1419 
1420 	first_mp = ipsec_alloc_ipsec_out(ipst->ips_netstack);
1421 	if (first_mp == NULL)
1422 		return (NULL);
1423 	io = (ipsec_out_t *)first_mp->b_rptr;
1424 	/* This is not a secure packet */
1425 	io->ipsec_out_secure = B_FALSE;
1426 	io->ipsec_out_zoneid = zoneid;
1427 	first_mp->b_cont = mp;
1428 	return (first_mp);
1429 }
1430 
1431 /*
1432  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1433  */
1434 mblk_t *
1435 ip_copymsg(mblk_t *mp)
1436 {
1437 	mblk_t *nmp;
1438 	ipsec_info_t *in;
1439 
1440 	if (mp->b_datap->db_type != M_CTL)
1441 		return (copymsg(mp));
1442 
1443 	in = (ipsec_info_t *)mp->b_rptr;
1444 
1445 	/*
1446 	 * Note that M_CTL is also used for delivering ICMP error messages
1447 	 * upstream to transport layers.
1448 	 */
1449 	if (in->ipsec_info_type != IPSEC_OUT &&
1450 	    in->ipsec_info_type != IPSEC_IN)
1451 		return (copymsg(mp));
1452 
1453 	nmp = copymsg(mp->b_cont);
1454 
1455 	if (in->ipsec_info_type == IPSEC_OUT) {
1456 		return (ipsec_out_tag(mp, nmp,
1457 		    ((ipsec_out_t *)in)->ipsec_out_ns));
1458 	} else {
1459 		return (ipsec_in_tag(mp, nmp,
1460 		    ((ipsec_in_t *)in)->ipsec_in_ns));
1461 	}
1462 }
1463 
1464 /* Generate an ICMP fragmentation needed message. */
1465 static void
1466 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid,
1467     ip_stack_t *ipst)
1468 {
1469 	icmph_t	icmph;
1470 	mblk_t *first_mp;
1471 	boolean_t mctl_present;
1472 
1473 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1474 
1475 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
1476 		if (mctl_present)
1477 			freeb(first_mp);
1478 		return;
1479 	}
1480 
1481 	bzero(&icmph, sizeof (icmph_t));
1482 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1483 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1484 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1485 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1486 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1487 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
1488 	    ipst);
1489 }
1490 
1491 /*
1492  * icmp_inbound deals with ICMP messages in the following ways.
1493  *
1494  * 1) It needs to send a reply back and possibly delivering it
1495  *    to the "interested" upper clients.
1496  * 2) It needs to send it to the upper clients only.
1497  * 3) It needs to change some values in IP only.
1498  * 4) It needs to change some values in IP and upper layers e.g TCP.
1499  *
1500  * We need to accomodate icmp messages coming in clear until we get
1501  * everything secure from the wire. If icmp_accept_clear_messages
1502  * is zero we check with the global policy and act accordingly. If
1503  * it is non-zero, we accept the message without any checks. But
1504  * *this does not mean* that this will be delivered to the upper
1505  * clients. By accepting we might send replies back, change our MTU
1506  * value etc. but delivery to the ULP/clients depends on their policy
1507  * dispositions.
1508  *
1509  * We handle the above 4 cases in the context of IPSEC in the
1510  * following way :
1511  *
1512  * 1) Send the reply back in the same way as the request came in.
1513  *    If it came in encrypted, it goes out encrypted. If it came in
1514  *    clear, it goes out in clear. Thus, this will prevent chosen
1515  *    plain text attack.
1516  * 2) The client may or may not expect things to come in secure.
1517  *    If it comes in secure, the policy constraints are checked
1518  *    before delivering it to the upper layers. If it comes in
1519  *    clear, ipsec_inbound_accept_clear will decide whether to
1520  *    accept this in clear or not. In both the cases, if the returned
1521  *    message (IP header + 8 bytes) that caused the icmp message has
1522  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1523  *    sending up. If there are only 8 bytes of returned message, then
1524  *    upper client will not be notified.
1525  * 3) Check with global policy to see whether it matches the constaints.
1526  *    But this will be done only if icmp_accept_messages_in_clear is
1527  *    zero.
1528  * 4) If we need to change both in IP and ULP, then the decision taken
1529  *    while affecting the values in IP and while delivering up to TCP
1530  *    should be the same.
1531  *
1532  * 	There are two cases.
1533  *
1534  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1535  *	   failed), we will not deliver it to the ULP, even though they
1536  *	   are *willing* to accept in *clear*. This is fine as our global
1537  *	   disposition to icmp messages asks us reject the datagram.
1538  *
1539  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1540  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1541  *	   to deliver it to ULP (policy failed), it can lead to
1542  *	   consistency problems. The cases known at this time are
1543  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1544  *	   values :
1545  *
1546  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1547  *	     and Upper layer rejects. Then the communication will
1548  *	     come to a stop. This is solved by making similar decisions
1549  *	     at both levels. Currently, when we are unable to deliver
1550  *	     to the Upper Layer (due to policy failures) while IP has
1551  *	     adjusted ire_max_frag, the next outbound datagram would
1552  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1553  *	     will be with the right level of protection. Thus the right
1554  *	     value will be communicated even if we are not able to
1555  *	     communicate when we get from the wire initially. But this
1556  *	     assumes there would be at least one outbound datagram after
1557  *	     IP has adjusted its ire_max_frag value. To make things
1558  *	     simpler, we accept in clear after the validation of
1559  *	     AH/ESP headers.
1560  *
1561  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1562  *	     upper layer depending on the level of protection the upper
1563  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1564  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1565  *	     should be accepted in clear when the Upper layer expects secure.
1566  *	     Thus the communication may get aborted by some bad ICMP
1567  *	     packets.
1568  *
1569  * IPQoS Notes:
1570  * The only instance when a packet is sent for processing is when there
1571  * isn't an ICMP client and if we are interested in it.
1572  * If there is a client, IPPF processing will take place in the
1573  * ip_fanout_proto routine.
1574  *
1575  * Zones notes:
1576  * The packet is only processed in the context of the specified zone: typically
1577  * only this zone will reply to an echo request, and only interested clients in
1578  * this zone will receive a copy of the packet. This means that the caller must
1579  * call icmp_inbound() for each relevant zone.
1580  */
1581 static void
1582 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1583     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1584     ill_t *recv_ill, zoneid_t zoneid)
1585 {
1586 	icmph_t	*icmph;
1587 	ipha_t	*ipha;
1588 	int	iph_hdr_length;
1589 	int	hdr_length;
1590 	boolean_t	interested;
1591 	uint32_t	ts;
1592 	uchar_t	*wptr;
1593 	ipif_t	*ipif;
1594 	mblk_t *first_mp;
1595 	ipsec_in_t *ii;
1596 	ire_t *src_ire;
1597 	boolean_t onlink;
1598 	timestruc_t now;
1599 	uint32_t ill_index;
1600 	ip_stack_t *ipst;
1601 
1602 	ASSERT(ill != NULL);
1603 	ipst = ill->ill_ipst;
1604 
1605 	first_mp = mp;
1606 	if (mctl_present) {
1607 		mp = first_mp->b_cont;
1608 		ASSERT(mp != NULL);
1609 	}
1610 
1611 	ipha = (ipha_t *)mp->b_rptr;
1612 	if (ipst->ips_icmp_accept_clear_messages == 0) {
1613 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1614 		    ipha, NULL, mctl_present, ipst->ips_netstack);
1615 		if (first_mp == NULL)
1616 			return;
1617 	}
1618 
1619 	/*
1620 	 * On a labeled system, we have to check whether the zone itself is
1621 	 * permitted to receive raw traffic.
1622 	 */
1623 	if (is_system_labeled()) {
1624 		if (zoneid == ALL_ZONES)
1625 			zoneid = tsol_packet_to_zoneid(mp);
1626 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1627 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1628 			    zoneid));
1629 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1630 			freemsg(first_mp);
1631 			return;
1632 		}
1633 	}
1634 
1635 	/*
1636 	 * We have accepted the ICMP message. It means that we will
1637 	 * respond to the packet if needed. It may not be delivered
1638 	 * to the upper client depending on the policy constraints
1639 	 * and the disposition in ipsec_inbound_accept_clear.
1640 	 */
1641 
1642 	ASSERT(ill != NULL);
1643 
1644 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1645 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1646 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1647 		/* Last chance to get real. */
1648 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1649 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1650 			freemsg(first_mp);
1651 			return;
1652 		}
1653 		/* Refresh iph following the pullup. */
1654 		ipha = (ipha_t *)mp->b_rptr;
1655 	}
1656 	/* ICMP header checksum, including checksum field, should be zero. */
1657 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1658 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1659 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInCksumErrs);
1660 		freemsg(first_mp);
1661 		return;
1662 	}
1663 	/* The IP header will always be a multiple of four bytes */
1664 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1665 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1666 	    icmph->icmph_code));
1667 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1668 	/* We will set "interested" to "true" if we want a copy */
1669 	interested = B_FALSE;
1670 	switch (icmph->icmph_type) {
1671 	case ICMP_ECHO_REPLY:
1672 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1673 		break;
1674 	case ICMP_DEST_UNREACHABLE:
1675 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1676 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1677 		interested = B_TRUE;	/* Pass up to transport */
1678 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1679 		break;
1680 	case ICMP_SOURCE_QUENCH:
1681 		interested = B_TRUE;	/* Pass up to transport */
1682 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1683 		break;
1684 	case ICMP_REDIRECT:
1685 		if (!ipst->ips_ip_ignore_redirect)
1686 			interested = B_TRUE;
1687 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1688 		break;
1689 	case ICMP_ECHO_REQUEST:
1690 		/*
1691 		 * Whether to respond to echo requests that come in as IP
1692 		 * broadcasts or as IP multicast is subject to debate
1693 		 * (what isn't?).  We aim to please, you pick it.
1694 		 * Default is do it.
1695 		 */
1696 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1697 			/* unicast: always respond */
1698 			interested = B_TRUE;
1699 		} else if (CLASSD(ipha->ipha_dst)) {
1700 			/* multicast: respond based on tunable */
1701 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1702 		} else if (broadcast) {
1703 			/* broadcast: respond based on tunable */
1704 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1705 		}
1706 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1707 		break;
1708 	case ICMP_ROUTER_ADVERTISEMENT:
1709 	case ICMP_ROUTER_SOLICITATION:
1710 		break;
1711 	case ICMP_TIME_EXCEEDED:
1712 		interested = B_TRUE;	/* Pass up to transport */
1713 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1714 		break;
1715 	case ICMP_PARAM_PROBLEM:
1716 		interested = B_TRUE;	/* Pass up to transport */
1717 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1718 		break;
1719 	case ICMP_TIME_STAMP_REQUEST:
1720 		/* Response to Time Stamp Requests is local policy. */
1721 		if (ipst->ips_ip_g_resp_to_timestamp &&
1722 		    /* So is whether to respond if it was an IP broadcast. */
1723 		    (!broadcast || ipst->ips_ip_g_resp_to_timestamp_bcast)) {
1724 			int tstamp_len = 3 * sizeof (uint32_t);
1725 
1726 			if (wptr +  tstamp_len > mp->b_wptr) {
1727 				if (!pullupmsg(mp, wptr + tstamp_len -
1728 				    mp->b_rptr)) {
1729 					BUMP_MIB(ill->ill_ip_mib,
1730 					    ipIfStatsInDiscards);
1731 					freemsg(first_mp);
1732 					return;
1733 				}
1734 				/* Refresh ipha following the pullup. */
1735 				ipha = (ipha_t *)mp->b_rptr;
1736 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1737 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1738 			}
1739 			interested = B_TRUE;
1740 		}
1741 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1742 		break;
1743 	case ICMP_TIME_STAMP_REPLY:
1744 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1745 		break;
1746 	case ICMP_INFO_REQUEST:
1747 		/* Per RFC 1122 3.2.2.7, ignore this. */
1748 	case ICMP_INFO_REPLY:
1749 		break;
1750 	case ICMP_ADDRESS_MASK_REQUEST:
1751 		if ((ipst->ips_ip_respond_to_address_mask_broadcast ||
1752 		    !broadcast) &&
1753 		    /* TODO m_pullup of complete header? */
1754 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN) {
1755 			interested = B_TRUE;
1756 		}
1757 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1758 		break;
1759 	case ICMP_ADDRESS_MASK_REPLY:
1760 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1761 		break;
1762 	default:
1763 		interested = B_TRUE;	/* Pass up to transport */
1764 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1765 		break;
1766 	}
1767 	/* See if there is an ICMP client. */
1768 	if (ipst->ips_ipcl_proto_fanout[IPPROTO_ICMP].connf_head != NULL) {
1769 		/* If there is an ICMP client and we want one too, copy it. */
1770 		mblk_t *first_mp1;
1771 
1772 		if (!interested) {
1773 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1774 			    ip_policy, recv_ill, zoneid);
1775 			return;
1776 		}
1777 		first_mp1 = ip_copymsg(first_mp);
1778 		if (first_mp1 != NULL) {
1779 			ip_fanout_proto(q, first_mp1, ill, ipha,
1780 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1781 		}
1782 	} else if (!interested) {
1783 		freemsg(first_mp);
1784 		return;
1785 	} else {
1786 		/*
1787 		 * Initiate policy processing for this packet if ip_policy
1788 		 * is true.
1789 		 */
1790 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
1791 			ill_index = ill->ill_phyint->phyint_ifindex;
1792 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1793 			if (mp == NULL) {
1794 				if (mctl_present) {
1795 					freeb(first_mp);
1796 				}
1797 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1798 				return;
1799 			}
1800 		}
1801 	}
1802 	/* We want to do something with it. */
1803 	/* Check db_ref to make sure we can modify the packet. */
1804 	if (mp->b_datap->db_ref > 1) {
1805 		mblk_t	*first_mp1;
1806 
1807 		first_mp1 = ip_copymsg(first_mp);
1808 		freemsg(first_mp);
1809 		if (!first_mp1) {
1810 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1811 			return;
1812 		}
1813 		first_mp = first_mp1;
1814 		if (mctl_present) {
1815 			mp = first_mp->b_cont;
1816 			ASSERT(mp != NULL);
1817 		} else {
1818 			mp = first_mp;
1819 		}
1820 		ipha = (ipha_t *)mp->b_rptr;
1821 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1822 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1823 	}
1824 	switch (icmph->icmph_type) {
1825 	case ICMP_ADDRESS_MASK_REQUEST:
1826 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1827 		if (ipif == NULL) {
1828 			freemsg(first_mp);
1829 			return;
1830 		}
1831 		/*
1832 		 * outging interface must be IPv4
1833 		 */
1834 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1835 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1836 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1837 		ipif_refrele(ipif);
1838 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1839 		break;
1840 	case ICMP_ECHO_REQUEST:
1841 		icmph->icmph_type = ICMP_ECHO_REPLY;
1842 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1843 		break;
1844 	case ICMP_TIME_STAMP_REQUEST: {
1845 		uint32_t *tsp;
1846 
1847 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1848 		tsp = (uint32_t *)wptr;
1849 		tsp++;		/* Skip past 'originate time' */
1850 		/* Compute # of milliseconds since midnight */
1851 		gethrestime(&now);
1852 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1853 		    now.tv_nsec / (NANOSEC / MILLISEC);
1854 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1855 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1856 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1857 		break;
1858 	}
1859 	default:
1860 		ipha = (ipha_t *)&icmph[1];
1861 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1862 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1863 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1864 				freemsg(first_mp);
1865 				return;
1866 			}
1867 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1868 			ipha = (ipha_t *)&icmph[1];
1869 		}
1870 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1871 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1872 			freemsg(first_mp);
1873 			return;
1874 		}
1875 		hdr_length = IPH_HDR_LENGTH(ipha);
1876 		if (hdr_length < sizeof (ipha_t)) {
1877 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1878 			freemsg(first_mp);
1879 			return;
1880 		}
1881 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1882 			if (!pullupmsg(mp,
1883 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1884 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1885 				freemsg(first_mp);
1886 				return;
1887 			}
1888 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1889 			ipha = (ipha_t *)&icmph[1];
1890 		}
1891 		switch (icmph->icmph_type) {
1892 		case ICMP_REDIRECT:
1893 			/*
1894 			 * As there is no upper client to deliver, we don't
1895 			 * need the first_mp any more.
1896 			 */
1897 			if (mctl_present) {
1898 				freeb(first_mp);
1899 			}
1900 			icmp_redirect(ill, mp);
1901 			return;
1902 		case ICMP_DEST_UNREACHABLE:
1903 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1904 				if (!icmp_inbound_too_big(icmph, ipha, ill,
1905 				    zoneid, mp, iph_hdr_length, ipst)) {
1906 					freemsg(first_mp);
1907 					return;
1908 				}
1909 				/*
1910 				 * icmp_inbound_too_big() may alter mp.
1911 				 * Resynch ipha and icmph accordingly.
1912 				 */
1913 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1914 				ipha = (ipha_t *)&icmph[1];
1915 			}
1916 			/* FALLTHRU */
1917 		default :
1918 			/*
1919 			 * IPQoS notes: Since we have already done IPQoS
1920 			 * processing we don't want to do it again in
1921 			 * the fanout routines called by
1922 			 * icmp_inbound_error_fanout, hence the last
1923 			 * argument, ip_policy, is B_FALSE.
1924 			 */
1925 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
1926 			    ipha, iph_hdr_length, hdr_length, mctl_present,
1927 			    B_FALSE, recv_ill, zoneid);
1928 		}
1929 		return;
1930 	}
1931 	/* Send out an ICMP packet */
1932 	icmph->icmph_checksum = 0;
1933 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
1934 	if (broadcast || CLASSD(ipha->ipha_dst)) {
1935 		ipif_t	*ipif_chosen;
1936 		/*
1937 		 * Make it look like it was directed to us, so we don't look
1938 		 * like a fool with a broadcast or multicast source address.
1939 		 */
1940 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1941 		/*
1942 		 * Make sure that we haven't grabbed an interface that's DOWN.
1943 		 */
1944 		if (ipif != NULL) {
1945 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
1946 			    ipha->ipha_src, zoneid);
1947 			if (ipif_chosen != NULL) {
1948 				ipif_refrele(ipif);
1949 				ipif = ipif_chosen;
1950 			}
1951 		}
1952 		if (ipif == NULL) {
1953 			ip0dbg(("icmp_inbound: "
1954 			    "No source for broadcast/multicast:\n"
1955 			    "\tsrc 0x%x dst 0x%x ill %p "
1956 			    "ipif_lcl_addr 0x%x\n",
1957 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
1958 			    (void *)ill,
1959 			    ill->ill_ipif->ipif_lcl_addr));
1960 			freemsg(first_mp);
1961 			return;
1962 		}
1963 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1964 		ipha->ipha_dst = ipif->ipif_src_addr;
1965 		ipif_refrele(ipif);
1966 	}
1967 	/* Reset time to live. */
1968 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
1969 	{
1970 		/* Swap source and destination addresses */
1971 		ipaddr_t tmp;
1972 
1973 		tmp = ipha->ipha_src;
1974 		ipha->ipha_src = ipha->ipha_dst;
1975 		ipha->ipha_dst = tmp;
1976 	}
1977 	ipha->ipha_ident = 0;
1978 	if (!IS_SIMPLE_IPH(ipha))
1979 		icmp_options_update(ipha);
1980 
1981 	/*
1982 	 * ICMP echo replies should go out on the same interface
1983 	 * the request came on as probes used by in.mpathd for detecting
1984 	 * NIC failures are ECHO packets. We turn-off load spreading
1985 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
1986 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
1987 	 * function. This is in turn handled by ip_wput and ip_newroute
1988 	 * to make sure that the packet goes out on the interface it came
1989 	 * in on. If we don't turnoff load spreading, the packets might get
1990 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
1991 	 * to go out and in.mpathd would wrongly detect a failure or
1992 	 * mis-detect a NIC failure for link failure. As load spreading
1993 	 * can happen only if ill_group is not NULL, we do only for
1994 	 * that case and this does not affect the normal case.
1995 	 *
1996 	 * We turn off load spreading only on echo packets that came from
1997 	 * on-link hosts. If the interface route has been deleted, this will
1998 	 * not be enforced as we can't do much. For off-link hosts, as the
1999 	 * default routes in IPv4 does not typically have an ire_ipif
2000 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
2001 	 * Moreover, expecting a default route through this interface may
2002 	 * not be correct. We use ipha_dst because of the swap above.
2003 	 */
2004 	onlink = B_FALSE;
2005 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
2006 		/*
2007 		 * First, we need to make sure that it is not one of our
2008 		 * local addresses. If we set onlink when it is one of
2009 		 * our local addresses, we will end up creating IRE_CACHES
2010 		 * for one of our local addresses. Then, we will never
2011 		 * accept packets for them afterwards.
2012 		 */
2013 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2014 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2015 		if (src_ire == NULL) {
2016 			ipif = ipif_get_next_ipif(NULL, ill);
2017 			if (ipif == NULL) {
2018 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2019 				freemsg(mp);
2020 				return;
2021 			}
2022 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2023 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2024 			    NULL, MATCH_IRE_ILL | MATCH_IRE_TYPE, ipst);
2025 			ipif_refrele(ipif);
2026 			if (src_ire != NULL) {
2027 				onlink = B_TRUE;
2028 				ire_refrele(src_ire);
2029 			}
2030 		} else {
2031 			ire_refrele(src_ire);
2032 		}
2033 	}
2034 	if (!mctl_present) {
2035 		/*
2036 		 * This packet should go out the same way as it
2037 		 * came in i.e in clear. To make sure that global
2038 		 * policy will not be applied to this in ip_wput_ire,
2039 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2040 		 */
2041 		ASSERT(first_mp == mp);
2042 		first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2043 		if (first_mp == NULL) {
2044 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2045 			freemsg(mp);
2046 			return;
2047 		}
2048 		ii = (ipsec_in_t *)first_mp->b_rptr;
2049 
2050 		/* This is not a secure packet */
2051 		ii->ipsec_in_secure = B_FALSE;
2052 		if (onlink) {
2053 			ii->ipsec_in_attach_if = B_TRUE;
2054 			ii->ipsec_in_ill_index =
2055 			    ill->ill_phyint->phyint_ifindex;
2056 			ii->ipsec_in_rill_index =
2057 			    recv_ill->ill_phyint->phyint_ifindex;
2058 		}
2059 		first_mp->b_cont = mp;
2060 	} else if (onlink) {
2061 		ii = (ipsec_in_t *)first_mp->b_rptr;
2062 		ii->ipsec_in_attach_if = B_TRUE;
2063 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2064 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2065 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2066 	} else {
2067 		ii = (ipsec_in_t *)first_mp->b_rptr;
2068 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2069 	}
2070 	ii->ipsec_in_zoneid = zoneid;
2071 	ASSERT(zoneid != ALL_ZONES);
2072 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2073 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2074 		return;
2075 	}
2076 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2077 	put(WR(q), first_mp);
2078 }
2079 
2080 static ipaddr_t
2081 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2082 {
2083 	conn_t *connp;
2084 	connf_t *connfp;
2085 	ipaddr_t nexthop_addr = INADDR_ANY;
2086 	int hdr_length = IPH_HDR_LENGTH(ipha);
2087 	uint16_t *up;
2088 	uint32_t ports;
2089 	ip_stack_t *ipst = ill->ill_ipst;
2090 
2091 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2092 	switch (ipha->ipha_protocol) {
2093 		case IPPROTO_TCP:
2094 		{
2095 			tcph_t *tcph;
2096 
2097 			/* do a reverse lookup */
2098 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2099 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2100 			    TCPS_LISTEN, ipst);
2101 			break;
2102 		}
2103 		case IPPROTO_UDP:
2104 		{
2105 			uint32_t dstport, srcport;
2106 
2107 			((uint16_t *)&ports)[0] = up[1];
2108 			((uint16_t *)&ports)[1] = up[0];
2109 
2110 			/* Extract ports in net byte order */
2111 			dstport = htons(ntohl(ports) & 0xFFFF);
2112 			srcport = htons(ntohl(ports) >> 16);
2113 
2114 			connfp = &ipst->ips_ipcl_udp_fanout[
2115 			    IPCL_UDP_HASH(dstport, ipst)];
2116 			mutex_enter(&connfp->connf_lock);
2117 			connp = connfp->connf_head;
2118 
2119 			/* do a reverse lookup */
2120 			while ((connp != NULL) &&
2121 			    (!IPCL_UDP_MATCH(connp, dstport,
2122 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2123 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2124 				connp = connp->conn_next;
2125 			}
2126 			if (connp != NULL)
2127 				CONN_INC_REF(connp);
2128 			mutex_exit(&connfp->connf_lock);
2129 			break;
2130 		}
2131 		case IPPROTO_SCTP:
2132 		{
2133 			in6_addr_t map_src, map_dst;
2134 
2135 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2136 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2137 			((uint16_t *)&ports)[0] = up[1];
2138 			((uint16_t *)&ports)[1] = up[0];
2139 
2140 			connp = sctp_find_conn(&map_src, &map_dst, ports,
2141 			    zoneid, ipst->ips_netstack->netstack_sctp);
2142 			if (connp == NULL) {
2143 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2144 				    zoneid, ports, ipha, ipst);
2145 			} else {
2146 				CONN_INC_REF(connp);
2147 				SCTP_REFRELE(CONN2SCTP(connp));
2148 			}
2149 			break;
2150 		}
2151 		default:
2152 		{
2153 			ipha_t ripha;
2154 
2155 			ripha.ipha_src = ipha->ipha_dst;
2156 			ripha.ipha_dst = ipha->ipha_src;
2157 			ripha.ipha_protocol = ipha->ipha_protocol;
2158 
2159 			connfp = &ipst->ips_ipcl_proto_fanout[
2160 			    ipha->ipha_protocol];
2161 			mutex_enter(&connfp->connf_lock);
2162 			connp = connfp->connf_head;
2163 			for (connp = connfp->connf_head; connp != NULL;
2164 			    connp = connp->conn_next) {
2165 				if (IPCL_PROTO_MATCH(connp,
2166 				    ipha->ipha_protocol, &ripha, ill,
2167 				    0, zoneid)) {
2168 					CONN_INC_REF(connp);
2169 					break;
2170 				}
2171 			}
2172 			mutex_exit(&connfp->connf_lock);
2173 		}
2174 	}
2175 	if (connp != NULL) {
2176 		if (connp->conn_nexthop_set)
2177 			nexthop_addr = connp->conn_nexthop_v4;
2178 		CONN_DEC_REF(connp);
2179 	}
2180 	return (nexthop_addr);
2181 }
2182 
2183 /* Table from RFC 1191 */
2184 static int icmp_frag_size_table[] =
2185 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2186 
2187 /*
2188  * Process received ICMP Packet too big.
2189  * After updating any IRE it does the fanout to any matching transport streams.
2190  * Assumes the message has been pulled up till the IP header that caused
2191  * the error.
2192  *
2193  * Returns B_FALSE on failure and B_TRUE on success.
2194  */
2195 static boolean_t
2196 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2197     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length,
2198     ip_stack_t *ipst)
2199 {
2200 	ire_t	*ire, *first_ire;
2201 	int	mtu;
2202 	int	hdr_length;
2203 	ipaddr_t nexthop_addr;
2204 
2205 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2206 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2207 	ASSERT(ill != NULL);
2208 
2209 	hdr_length = IPH_HDR_LENGTH(ipha);
2210 
2211 	/* Drop if the original packet contained a source route */
2212 	if (ip_source_route_included(ipha)) {
2213 		return (B_FALSE);
2214 	}
2215 	/*
2216 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2217 	 * header.
2218 	 */
2219 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2220 	    mp->b_wptr) {
2221 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2222 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2223 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2224 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2225 			return (B_FALSE);
2226 		}
2227 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2228 		ipha = (ipha_t *)&icmph[1];
2229 	}
2230 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2231 	if (nexthop_addr != INADDR_ANY) {
2232 		/* nexthop set */
2233 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2234 		    nexthop_addr, 0, NULL, ALL_ZONES, MBLK_GETLABEL(mp),
2235 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW, ipst);
2236 	} else {
2237 		/* nexthop not set */
2238 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2239 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2240 	}
2241 
2242 	if (!first_ire) {
2243 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2244 		    ntohl(ipha->ipha_dst)));
2245 		return (B_FALSE);
2246 	}
2247 	/* Check for MTU discovery advice as described in RFC 1191 */
2248 	mtu = ntohs(icmph->icmph_du_mtu);
2249 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2250 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2251 	    ire = ire->ire_next) {
2252 		/*
2253 		 * Look for the connection to which this ICMP message is
2254 		 * directed. If it has the IP_NEXTHOP option set, then the
2255 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2256 		 * option. Else the search is limited to regular IREs.
2257 		 */
2258 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2259 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2260 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2261 		    (nexthop_addr != INADDR_ANY)))
2262 			continue;
2263 
2264 		mutex_enter(&ire->ire_lock);
2265 		if (icmph->icmph_du_zero == 0 && mtu > 68) {
2266 			/* Reduce the IRE max frag value as advised. */
2267 			ip1dbg(("Received mtu from router: %d (was %d)\n",
2268 			    mtu, ire->ire_max_frag));
2269 			ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2270 		} else {
2271 			uint32_t length;
2272 			int	i;
2273 
2274 			/*
2275 			 * Use the table from RFC 1191 to figure out
2276 			 * the next "plateau" based on the length in
2277 			 * the original IP packet.
2278 			 */
2279 			length = ntohs(ipha->ipha_length);
2280 			if (ire->ire_max_frag <= length &&
2281 			    ire->ire_max_frag >= length - hdr_length) {
2282 				/*
2283 				 * Handle broken BSD 4.2 systems that
2284 				 * return the wrong iph_length in ICMP
2285 				 * errors.
2286 				 */
2287 				ip1dbg(("Wrong mtu: sent %d, ire %d\n",
2288 				    length, ire->ire_max_frag));
2289 				length -= hdr_length;
2290 			}
2291 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2292 				if (length > icmp_frag_size_table[i])
2293 					break;
2294 			}
2295 			if (i == A_CNT(icmp_frag_size_table)) {
2296 				/* Smaller than 68! */
2297 				ip1dbg(("Too big for packet size %d\n",
2298 				    length));
2299 				ire->ire_max_frag = MIN(ire->ire_max_frag, 576);
2300 				ire->ire_frag_flag = 0;
2301 			} else {
2302 				mtu = icmp_frag_size_table[i];
2303 				ip1dbg(("Calculated mtu %d, packet size %d, "
2304 				    "before %d", mtu, length,
2305 				    ire->ire_max_frag));
2306 				ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2307 				ip1dbg((", after %d\n", ire->ire_max_frag));
2308 			}
2309 			/* Record the new max frag size for the ULP. */
2310 			icmph->icmph_du_zero = 0;
2311 			icmph->icmph_du_mtu =
2312 			    htons((uint16_t)ire->ire_max_frag);
2313 		}
2314 		mutex_exit(&ire->ire_lock);
2315 	}
2316 	rw_exit(&first_ire->ire_bucket->irb_lock);
2317 	ire_refrele(first_ire);
2318 	return (B_TRUE);
2319 }
2320 
2321 /*
2322  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2323  * calls this function.
2324  */
2325 static mblk_t *
2326 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2327 {
2328 	ipha_t *ipha;
2329 	icmph_t *icmph;
2330 	ipha_t *in_ipha;
2331 	int length;
2332 
2333 	ASSERT(mp->b_datap->db_type == M_DATA);
2334 
2335 	/*
2336 	 * For Self-encapsulated packets, we added an extra IP header
2337 	 * without the options. Inner IP header is the one from which
2338 	 * the outer IP header was formed. Thus, we need to remove the
2339 	 * outer IP header. To do this, we pullup the whole message
2340 	 * and overlay whatever follows the outer IP header over the
2341 	 * outer IP header.
2342 	 */
2343 
2344 	if (!pullupmsg(mp, -1))
2345 		return (NULL);
2346 
2347 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2348 	ipha = (ipha_t *)&icmph[1];
2349 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2350 
2351 	/*
2352 	 * The length that we want to overlay is following the inner
2353 	 * IP header. Subtracting the IP header + icmp header + outer
2354 	 * IP header's length should give us the length that we want to
2355 	 * overlay.
2356 	 */
2357 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2358 	    hdr_length;
2359 	/*
2360 	 * Overlay whatever follows the inner header over the
2361 	 * outer header.
2362 	 */
2363 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2364 
2365 	/* Set the wptr to account for the outer header */
2366 	mp->b_wptr -= hdr_length;
2367 	return (mp);
2368 }
2369 
2370 /*
2371  * Try to pass the ICMP message upstream in case the ULP cares.
2372  *
2373  * If the packet that caused the ICMP error is secure, we send
2374  * it to AH/ESP to make sure that the attached packet has a
2375  * valid association. ipha in the code below points to the
2376  * IP header of the packet that caused the error.
2377  *
2378  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2379  * in the context of IPSEC. Normally we tell the upper layer
2380  * whenever we send the ire (including ip_bind), the IPSEC header
2381  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2382  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2383  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2384  * same thing. As TCP has the IPSEC options size that needs to be
2385  * adjusted, we just pass the MTU unchanged.
2386  *
2387  * IFN could have been generated locally or by some router.
2388  *
2389  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2390  *	    This happens because IP adjusted its value of MTU on an
2391  *	    earlier IFN message and could not tell the upper layer,
2392  *	    the new adjusted value of MTU e.g. Packet was encrypted
2393  *	    or there was not enough information to fanout to upper
2394  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2395  *	    generates the IFN, where IPSEC processing has *not* been
2396  *	    done.
2397  *
2398  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2399  *	    could have generated this. This happens because ire_max_frag
2400  *	    value in IP was set to a new value, while the IPSEC processing
2401  *	    was being done and after we made the fragmentation check in
2402  *	    ip_wput_ire. Thus on return from IPSEC processing,
2403  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2404  *	    and generates the IFN. As IPSEC processing is over, we fanout
2405  *	    to AH/ESP to remove the header.
2406  *
2407  *	    In both these cases, ipsec_in_loopback will be set indicating
2408  *	    that IFN was generated locally.
2409  *
2410  * ROUTER : IFN could be secure or non-secure.
2411  *
2412  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2413  *	      packet in error has AH/ESP headers to validate the AH/ESP
2414  *	      headers. AH/ESP will verify whether there is a valid SA or
2415  *	      not and send it back. We will fanout again if we have more
2416  *	      data in the packet.
2417  *
2418  *	      If the packet in error does not have AH/ESP, we handle it
2419  *	      like any other case.
2420  *
2421  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2422  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2423  *	      for validation. AH/ESP will verify whether there is a
2424  *	      valid SA or not and send it back. We will fanout again if
2425  *	      we have more data in the packet.
2426  *
2427  *	      If the packet in error does not have AH/ESP, we handle it
2428  *	      like any other case.
2429  */
2430 static void
2431 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2432     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2433     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2434     zoneid_t zoneid)
2435 {
2436 	uint16_t *up;	/* Pointer to ports in ULP header */
2437 	uint32_t ports;	/* reversed ports for fanout */
2438 	ipha_t ripha;	/* With reversed addresses */
2439 	mblk_t *first_mp;
2440 	ipsec_in_t *ii;
2441 	tcph_t	*tcph;
2442 	conn_t	*connp;
2443 	ip_stack_t *ipst;
2444 
2445 	ASSERT(ill != NULL);
2446 
2447 	ASSERT(recv_ill != NULL);
2448 	ipst = recv_ill->ill_ipst;
2449 
2450 	first_mp = mp;
2451 	if (mctl_present) {
2452 		mp = first_mp->b_cont;
2453 		ASSERT(mp != NULL);
2454 
2455 		ii = (ipsec_in_t *)first_mp->b_rptr;
2456 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2457 	} else {
2458 		ii = NULL;
2459 	}
2460 
2461 	switch (ipha->ipha_protocol) {
2462 	case IPPROTO_UDP:
2463 		/*
2464 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2465 		 * transport header.
2466 		 */
2467 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2468 		    mp->b_wptr) {
2469 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2470 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2471 				goto discard_pkt;
2472 			}
2473 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2474 			ipha = (ipha_t *)&icmph[1];
2475 		}
2476 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2477 
2478 		/*
2479 		 * Attempt to find a client stream based on port.
2480 		 * Note that we do a reverse lookup since the header is
2481 		 * in the form we sent it out.
2482 		 * The ripha header is only used for the IP_UDP_MATCH and we
2483 		 * only set the src and dst addresses and protocol.
2484 		 */
2485 		ripha.ipha_src = ipha->ipha_dst;
2486 		ripha.ipha_dst = ipha->ipha_src;
2487 		ripha.ipha_protocol = ipha->ipha_protocol;
2488 		((uint16_t *)&ports)[0] = up[1];
2489 		((uint16_t *)&ports)[1] = up[0];
2490 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2491 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2492 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2493 		    icmph->icmph_type, icmph->icmph_code));
2494 
2495 		/* Have to change db_type after any pullupmsg */
2496 		DB_TYPE(mp) = M_CTL;
2497 
2498 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2499 		    mctl_present, ip_policy, recv_ill, zoneid);
2500 		return;
2501 
2502 	case IPPROTO_TCP:
2503 		/*
2504 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2505 		 * transport header.
2506 		 */
2507 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2508 		    mp->b_wptr) {
2509 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2510 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2511 				goto discard_pkt;
2512 			}
2513 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2514 			ipha = (ipha_t *)&icmph[1];
2515 		}
2516 		/*
2517 		 * Find a TCP client stream for this packet.
2518 		 * Note that we do a reverse lookup since the header is
2519 		 * in the form we sent it out.
2520 		 */
2521 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2522 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN,
2523 		    ipst);
2524 		if (connp == NULL)
2525 			goto discard_pkt;
2526 
2527 		/* Have to change db_type after any pullupmsg */
2528 		DB_TYPE(mp) = M_CTL;
2529 		squeue_fill(connp->conn_sqp, first_mp, tcp_input,
2530 		    connp, SQTAG_TCP_INPUT_ICMP_ERR);
2531 		return;
2532 
2533 	case IPPROTO_SCTP:
2534 		/*
2535 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2536 		 * transport header.
2537 		 */
2538 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2539 		    mp->b_wptr) {
2540 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2541 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2542 				goto discard_pkt;
2543 			}
2544 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2545 			ipha = (ipha_t *)&icmph[1];
2546 		}
2547 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2548 		/*
2549 		 * Find a SCTP client stream for this packet.
2550 		 * Note that we do a reverse lookup since the header is
2551 		 * in the form we sent it out.
2552 		 * The ripha header is only used for the matching and we
2553 		 * only set the src and dst addresses, protocol, and version.
2554 		 */
2555 		ripha.ipha_src = ipha->ipha_dst;
2556 		ripha.ipha_dst = ipha->ipha_src;
2557 		ripha.ipha_protocol = ipha->ipha_protocol;
2558 		ripha.ipha_version_and_hdr_length =
2559 		    ipha->ipha_version_and_hdr_length;
2560 		((uint16_t *)&ports)[0] = up[1];
2561 		((uint16_t *)&ports)[1] = up[0];
2562 
2563 		/* Have to change db_type after any pullupmsg */
2564 		DB_TYPE(mp) = M_CTL;
2565 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2566 		    mctl_present, ip_policy, zoneid);
2567 		return;
2568 
2569 	case IPPROTO_ESP:
2570 	case IPPROTO_AH: {
2571 		int ipsec_rc;
2572 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
2573 
2574 		/*
2575 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2576 		 * We will re-use the IPSEC_IN if it is already present as
2577 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2578 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2579 		 * one and attach it in the front.
2580 		 */
2581 		if (ii != NULL) {
2582 			/*
2583 			 * ip_fanout_proto_again converts the ICMP errors
2584 			 * that come back from AH/ESP to M_DATA so that
2585 			 * if it is non-AH/ESP and we do a pullupmsg in
2586 			 * this function, it would work. Convert it back
2587 			 * to M_CTL before we send up as this is a ICMP
2588 			 * error. This could have been generated locally or
2589 			 * by some router. Validate the inner IPSEC
2590 			 * headers.
2591 			 *
2592 			 * NOTE : ill_index is used by ip_fanout_proto_again
2593 			 * to locate the ill.
2594 			 */
2595 			ASSERT(ill != NULL);
2596 			ii->ipsec_in_ill_index =
2597 			    ill->ill_phyint->phyint_ifindex;
2598 			ii->ipsec_in_rill_index =
2599 			    recv_ill->ill_phyint->phyint_ifindex;
2600 			DB_TYPE(first_mp->b_cont) = M_CTL;
2601 		} else {
2602 			/*
2603 			 * IPSEC_IN is not present. We attach a ipsec_in
2604 			 * message and send up to IPSEC for validating
2605 			 * and removing the IPSEC headers. Clear
2606 			 * ipsec_in_secure so that when we return
2607 			 * from IPSEC, we don't mistakenly think that this
2608 			 * is a secure packet came from the network.
2609 			 *
2610 			 * NOTE : ill_index is used by ip_fanout_proto_again
2611 			 * to locate the ill.
2612 			 */
2613 			ASSERT(first_mp == mp);
2614 			first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2615 			if (first_mp == NULL) {
2616 				freemsg(mp);
2617 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2618 				return;
2619 			}
2620 			ii = (ipsec_in_t *)first_mp->b_rptr;
2621 
2622 			/* This is not a secure packet */
2623 			ii->ipsec_in_secure = B_FALSE;
2624 			first_mp->b_cont = mp;
2625 			DB_TYPE(mp) = M_CTL;
2626 			ASSERT(ill != NULL);
2627 			ii->ipsec_in_ill_index =
2628 			    ill->ill_phyint->phyint_ifindex;
2629 			ii->ipsec_in_rill_index =
2630 			    recv_ill->ill_phyint->phyint_ifindex;
2631 		}
2632 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2633 
2634 		if (!ipsec_loaded(ipss)) {
2635 			ip_proto_not_sup(q, first_mp, 0, zoneid, ipst);
2636 			return;
2637 		}
2638 
2639 		if (ipha->ipha_protocol == IPPROTO_ESP)
2640 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2641 		else
2642 			ipsec_rc = ipsecah_icmp_error(first_mp);
2643 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2644 			return;
2645 
2646 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2647 		return;
2648 	}
2649 	default:
2650 		/*
2651 		 * The ripha header is only used for the lookup and we
2652 		 * only set the src and dst addresses and protocol.
2653 		 */
2654 		ripha.ipha_src = ipha->ipha_dst;
2655 		ripha.ipha_dst = ipha->ipha_src;
2656 		ripha.ipha_protocol = ipha->ipha_protocol;
2657 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2658 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2659 		    ntohl(ipha->ipha_dst),
2660 		    icmph->icmph_type, icmph->icmph_code));
2661 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2662 			ipha_t *in_ipha;
2663 
2664 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2665 			    mp->b_wptr) {
2666 				if (!pullupmsg(mp, (uchar_t *)ipha +
2667 				    hdr_length + sizeof (ipha_t) -
2668 				    mp->b_rptr)) {
2669 					goto discard_pkt;
2670 				}
2671 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2672 				ipha = (ipha_t *)&icmph[1];
2673 			}
2674 			/*
2675 			 * Caller has verified that length has to be
2676 			 * at least the size of IP header.
2677 			 */
2678 			ASSERT(hdr_length >= sizeof (ipha_t));
2679 			/*
2680 			 * Check the sanity of the inner IP header like
2681 			 * we did for the outer header.
2682 			 */
2683 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2684 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2685 				goto discard_pkt;
2686 			}
2687 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2688 				goto discard_pkt;
2689 			}
2690 			/* Check for Self-encapsulated tunnels */
2691 			if (in_ipha->ipha_src == ipha->ipha_src &&
2692 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2693 
2694 				mp = icmp_inbound_self_encap_error(mp,
2695 				    iph_hdr_length, hdr_length);
2696 				if (mp == NULL)
2697 					goto discard_pkt;
2698 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2699 				ipha = (ipha_t *)&icmph[1];
2700 				hdr_length = IPH_HDR_LENGTH(ipha);
2701 				/*
2702 				 * The packet in error is self-encapsualted.
2703 				 * And we are finding it further encapsulated
2704 				 * which we could not have possibly generated.
2705 				 */
2706 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2707 					goto discard_pkt;
2708 				}
2709 				icmp_inbound_error_fanout(q, ill, first_mp,
2710 				    icmph, ipha, iph_hdr_length, hdr_length,
2711 				    mctl_present, ip_policy, recv_ill, zoneid);
2712 				return;
2713 			}
2714 		}
2715 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2716 		    ipha->ipha_protocol == IPPROTO_IPV6) &&
2717 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2718 		    ii != NULL &&
2719 		    ii->ipsec_in_loopback &&
2720 		    ii->ipsec_in_secure) {
2721 			/*
2722 			 * For IP tunnels that get a looped-back
2723 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2724 			 * reported new MTU to take into account the IPsec
2725 			 * headers protecting this configured tunnel.
2726 			 *
2727 			 * This allows the tunnel module (tun.c) to blindly
2728 			 * accept the MTU reported in an ICMP "too big"
2729 			 * message.
2730 			 *
2731 			 * Non-looped back ICMP messages will just be
2732 			 * handled by the security protocols (if needed),
2733 			 * and the first subsequent packet will hit this
2734 			 * path.
2735 			 */
2736 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2737 			    ipsec_in_extra_length(first_mp));
2738 		}
2739 		/* Have to change db_type after any pullupmsg */
2740 		DB_TYPE(mp) = M_CTL;
2741 
2742 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2743 		    ip_policy, recv_ill, zoneid);
2744 		return;
2745 	}
2746 	/* NOTREACHED */
2747 discard_pkt:
2748 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2749 drop_pkt:;
2750 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2751 	freemsg(first_mp);
2752 }
2753 
2754 /*
2755  * Common IP options parser.
2756  *
2757  * Setup routine: fill in *optp with options-parsing state, then
2758  * tail-call ipoptp_next to return the first option.
2759  */
2760 uint8_t
2761 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2762 {
2763 	uint32_t totallen; /* total length of all options */
2764 
2765 	totallen = ipha->ipha_version_and_hdr_length -
2766 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2767 	totallen <<= 2;
2768 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2769 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2770 	optp->ipoptp_flags = 0;
2771 	return (ipoptp_next(optp));
2772 }
2773 
2774 /*
2775  * Common IP options parser: extract next option.
2776  */
2777 uint8_t
2778 ipoptp_next(ipoptp_t *optp)
2779 {
2780 	uint8_t *end = optp->ipoptp_end;
2781 	uint8_t *cur = optp->ipoptp_next;
2782 	uint8_t opt, len, pointer;
2783 
2784 	/*
2785 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2786 	 * has been corrupted.
2787 	 */
2788 	ASSERT(cur <= end);
2789 
2790 	if (cur == end)
2791 		return (IPOPT_EOL);
2792 
2793 	opt = cur[IPOPT_OPTVAL];
2794 
2795 	/*
2796 	 * Skip any NOP options.
2797 	 */
2798 	while (opt == IPOPT_NOP) {
2799 		cur++;
2800 		if (cur == end)
2801 			return (IPOPT_EOL);
2802 		opt = cur[IPOPT_OPTVAL];
2803 	}
2804 
2805 	if (opt == IPOPT_EOL)
2806 		return (IPOPT_EOL);
2807 
2808 	/*
2809 	 * Option requiring a length.
2810 	 */
2811 	if ((cur + 1) >= end) {
2812 		optp->ipoptp_flags |= IPOPTP_ERROR;
2813 		return (IPOPT_EOL);
2814 	}
2815 	len = cur[IPOPT_OLEN];
2816 	if (len < 2) {
2817 		optp->ipoptp_flags |= IPOPTP_ERROR;
2818 		return (IPOPT_EOL);
2819 	}
2820 	optp->ipoptp_cur = cur;
2821 	optp->ipoptp_len = len;
2822 	optp->ipoptp_next = cur + len;
2823 	if (cur + len > end) {
2824 		optp->ipoptp_flags |= IPOPTP_ERROR;
2825 		return (IPOPT_EOL);
2826 	}
2827 
2828 	/*
2829 	 * For the options which require a pointer field, make sure
2830 	 * its there, and make sure it points to either something
2831 	 * inside this option, or the end of the option.
2832 	 */
2833 	switch (opt) {
2834 	case IPOPT_RR:
2835 	case IPOPT_TS:
2836 	case IPOPT_LSRR:
2837 	case IPOPT_SSRR:
2838 		if (len <= IPOPT_OFFSET) {
2839 			optp->ipoptp_flags |= IPOPTP_ERROR;
2840 			return (opt);
2841 		}
2842 		pointer = cur[IPOPT_OFFSET];
2843 		if (pointer - 1 > len) {
2844 			optp->ipoptp_flags |= IPOPTP_ERROR;
2845 			return (opt);
2846 		}
2847 		break;
2848 	}
2849 
2850 	/*
2851 	 * Sanity check the pointer field based on the type of the
2852 	 * option.
2853 	 */
2854 	switch (opt) {
2855 	case IPOPT_RR:
2856 	case IPOPT_SSRR:
2857 	case IPOPT_LSRR:
2858 		if (pointer < IPOPT_MINOFF_SR)
2859 			optp->ipoptp_flags |= IPOPTP_ERROR;
2860 		break;
2861 	case IPOPT_TS:
2862 		if (pointer < IPOPT_MINOFF_IT)
2863 			optp->ipoptp_flags |= IPOPTP_ERROR;
2864 		/*
2865 		 * Note that the Internet Timestamp option also
2866 		 * contains two four bit fields (the Overflow field,
2867 		 * and the Flag field), which follow the pointer
2868 		 * field.  We don't need to check that these fields
2869 		 * fall within the length of the option because this
2870 		 * was implicitely done above.  We've checked that the
2871 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2872 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2873 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2874 		 */
2875 		ASSERT(len > IPOPT_POS_OV_FLG);
2876 		break;
2877 	}
2878 
2879 	return (opt);
2880 }
2881 
2882 /*
2883  * Use the outgoing IP header to create an IP_OPTIONS option the way
2884  * it was passed down from the application.
2885  */
2886 int
2887 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2888 {
2889 	ipoptp_t	opts;
2890 	const uchar_t	*opt;
2891 	uint8_t		optval;
2892 	uint8_t		optlen;
2893 	uint32_t	len = 0;
2894 	uchar_t	*buf1 = buf;
2895 
2896 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2897 	len += IP_ADDR_LEN;
2898 	bzero(buf1, IP_ADDR_LEN);
2899 
2900 	/*
2901 	 * OK to cast away const here, as we don't store through the returned
2902 	 * opts.ipoptp_cur pointer.
2903 	 */
2904 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
2905 	    optval != IPOPT_EOL;
2906 	    optval = ipoptp_next(&opts)) {
2907 		int	off;
2908 
2909 		opt = opts.ipoptp_cur;
2910 		optlen = opts.ipoptp_len;
2911 		switch (optval) {
2912 		case IPOPT_SSRR:
2913 		case IPOPT_LSRR:
2914 
2915 			/*
2916 			 * Insert ipha_dst as the first entry in the source
2917 			 * route and move down the entries on step.
2918 			 * The last entry gets placed at buf1.
2919 			 */
2920 			buf[IPOPT_OPTVAL] = optval;
2921 			buf[IPOPT_OLEN] = optlen;
2922 			buf[IPOPT_OFFSET] = optlen;
2923 
2924 			off = optlen - IP_ADDR_LEN;
2925 			if (off < 0) {
2926 				/* No entries in source route */
2927 				break;
2928 			}
2929 			/* Last entry in source route */
2930 			bcopy(opt + off, buf1, IP_ADDR_LEN);
2931 			off -= IP_ADDR_LEN;
2932 
2933 			while (off > 0) {
2934 				bcopy(opt + off,
2935 				    buf + off + IP_ADDR_LEN,
2936 				    IP_ADDR_LEN);
2937 				off -= IP_ADDR_LEN;
2938 			}
2939 			/* ipha_dst into first slot */
2940 			bcopy(&ipha->ipha_dst,
2941 			    buf + off + IP_ADDR_LEN,
2942 			    IP_ADDR_LEN);
2943 			buf += optlen;
2944 			len += optlen;
2945 			break;
2946 
2947 		case IPOPT_COMSEC:
2948 		case IPOPT_SECURITY:
2949 			/* if passing up a label is not ok, then remove */
2950 			if (is_system_labeled())
2951 				break;
2952 			/* FALLTHROUGH */
2953 		default:
2954 			bcopy(opt, buf, optlen);
2955 			buf += optlen;
2956 			len += optlen;
2957 			break;
2958 		}
2959 	}
2960 done:
2961 	/* Pad the resulting options */
2962 	while (len & 0x3) {
2963 		*buf++ = IPOPT_EOL;
2964 		len++;
2965 	}
2966 	return (len);
2967 }
2968 
2969 /*
2970  * Update any record route or timestamp options to include this host.
2971  * Reverse any source route option.
2972  * This routine assumes that the options are well formed i.e. that they
2973  * have already been checked.
2974  */
2975 static void
2976 icmp_options_update(ipha_t *ipha)
2977 {
2978 	ipoptp_t	opts;
2979 	uchar_t		*opt;
2980 	uint8_t		optval;
2981 	ipaddr_t	src;		/* Our local address */
2982 	ipaddr_t	dst;
2983 
2984 	ip2dbg(("icmp_options_update\n"));
2985 	src = ipha->ipha_src;
2986 	dst = ipha->ipha_dst;
2987 
2988 	for (optval = ipoptp_first(&opts, ipha);
2989 	    optval != IPOPT_EOL;
2990 	    optval = ipoptp_next(&opts)) {
2991 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
2992 		opt = opts.ipoptp_cur;
2993 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
2994 		    optval, opts.ipoptp_len));
2995 		switch (optval) {
2996 			int off1, off2;
2997 		case IPOPT_SSRR:
2998 		case IPOPT_LSRR:
2999 			/*
3000 			 * Reverse the source route.  The first entry
3001 			 * should be the next to last one in the current
3002 			 * source route (the last entry is our address).
3003 			 * The last entry should be the final destination.
3004 			 */
3005 			off1 = IPOPT_MINOFF_SR - 1;
3006 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
3007 			if (off2 < 0) {
3008 				/* No entries in source route */
3009 				ip1dbg((
3010 				    "icmp_options_update: bad src route\n"));
3011 				break;
3012 			}
3013 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3014 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3015 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3016 			off2 -= IP_ADDR_LEN;
3017 
3018 			while (off1 < off2) {
3019 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3020 				bcopy((char *)opt + off2, (char *)opt + off1,
3021 				    IP_ADDR_LEN);
3022 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3023 				off1 += IP_ADDR_LEN;
3024 				off2 -= IP_ADDR_LEN;
3025 			}
3026 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3027 			break;
3028 		}
3029 	}
3030 }
3031 
3032 /*
3033  * Process received ICMP Redirect messages.
3034  */
3035 static void
3036 icmp_redirect(ill_t *ill, mblk_t *mp)
3037 {
3038 	ipha_t	*ipha;
3039 	int	iph_hdr_length;
3040 	icmph_t	*icmph;
3041 	ipha_t	*ipha_err;
3042 	ire_t	*ire;
3043 	ire_t	*prev_ire;
3044 	ire_t	*save_ire;
3045 	ipaddr_t  src, dst, gateway;
3046 	iulp_t	ulp_info = { 0 };
3047 	int	error;
3048 	ip_stack_t *ipst;
3049 
3050 	ASSERT(ill != NULL);
3051 	ipst = ill->ill_ipst;
3052 
3053 	ipha = (ipha_t *)mp->b_rptr;
3054 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3055 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3056 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3057 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3058 		freemsg(mp);
3059 		return;
3060 	}
3061 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3062 	ipha_err = (ipha_t *)&icmph[1];
3063 	src = ipha->ipha_src;
3064 	dst = ipha_err->ipha_dst;
3065 	gateway = icmph->icmph_rd_gateway;
3066 	/* Make sure the new gateway is reachable somehow. */
3067 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3068 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3069 	/*
3070 	 * Make sure we had a route for the dest in question and that
3071 	 * that route was pointing to the old gateway (the source of the
3072 	 * redirect packet.)
3073 	 */
3074 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3075 	    NULL, MATCH_IRE_GW, ipst);
3076 	/*
3077 	 * Check that
3078 	 *	the redirect was not from ourselves
3079 	 *	the new gateway and the old gateway are directly reachable
3080 	 */
3081 	if (!prev_ire ||
3082 	    !ire ||
3083 	    ire->ire_type == IRE_LOCAL) {
3084 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3085 		freemsg(mp);
3086 		if (ire != NULL)
3087 			ire_refrele(ire);
3088 		if (prev_ire != NULL)
3089 			ire_refrele(prev_ire);
3090 		return;
3091 	}
3092 
3093 	/*
3094 	 * Should we use the old ULP info to create the new gateway?  From
3095 	 * a user's perspective, we should inherit the info so that it
3096 	 * is a "smooth" transition.  If we do not do that, then new
3097 	 * connections going thru the new gateway will have no route metrics,
3098 	 * which is counter-intuitive to user.  From a network point of
3099 	 * view, this may or may not make sense even though the new gateway
3100 	 * is still directly connected to us so the route metrics should not
3101 	 * change much.
3102 	 *
3103 	 * But if the old ire_uinfo is not initialized, we do another
3104 	 * recursive lookup on the dest using the new gateway.  There may
3105 	 * be a route to that.  If so, use it to initialize the redirect
3106 	 * route.
3107 	 */
3108 	if (prev_ire->ire_uinfo.iulp_set) {
3109 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3110 	} else {
3111 		ire_t *tmp_ire;
3112 		ire_t *sire;
3113 
3114 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3115 		    ALL_ZONES, 0, NULL,
3116 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT),
3117 		    ipst);
3118 		if (sire != NULL) {
3119 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3120 			/*
3121 			 * If sire != NULL, ire_ftable_lookup() should not
3122 			 * return a NULL value.
3123 			 */
3124 			ASSERT(tmp_ire != NULL);
3125 			ire_refrele(tmp_ire);
3126 			ire_refrele(sire);
3127 		} else if (tmp_ire != NULL) {
3128 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3129 			    sizeof (iulp_t));
3130 			ire_refrele(tmp_ire);
3131 		}
3132 	}
3133 	if (prev_ire->ire_type == IRE_CACHE)
3134 		ire_delete(prev_ire);
3135 	ire_refrele(prev_ire);
3136 	/*
3137 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3138 	 * require TOS routing
3139 	 */
3140 	switch (icmph->icmph_code) {
3141 	case 0:
3142 	case 1:
3143 		/* TODO: TOS specificity for cases 2 and 3 */
3144 	case 2:
3145 	case 3:
3146 		break;
3147 	default:
3148 		freemsg(mp);
3149 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3150 		ire_refrele(ire);
3151 		return;
3152 	}
3153 	/*
3154 	 * Create a Route Association.  This will allow us to remember that
3155 	 * someone we believe told us to use the particular gateway.
3156 	 */
3157 	save_ire = ire;
3158 	ire = ire_create(
3159 	    (uchar_t *)&dst,			/* dest addr */
3160 	    (uchar_t *)&ip_g_all_ones,		/* mask */
3161 	    (uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3162 	    (uchar_t *)&gateway,		/* gateway addr */
3163 	    NULL,				/* no in_srcaddr */
3164 	    &save_ire->ire_max_frag,		/* max frag */
3165 	    NULL,				/* Fast Path header */
3166 	    NULL,				/* no rfq */
3167 	    NULL,				/* no stq */
3168 	    IRE_HOST,
3169 	    NULL,
3170 	    NULL,
3171 	    NULL,
3172 	    0,
3173 	    0,
3174 	    0,
3175 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3176 	    &ulp_info,
3177 	    NULL,
3178 	    NULL,
3179 	    ipst);
3180 
3181 	if (ire == NULL) {
3182 		freemsg(mp);
3183 		ire_refrele(save_ire);
3184 		return;
3185 	}
3186 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3187 	ire_refrele(save_ire);
3188 	atomic_inc_32(&ipst->ips_ip_redirect_cnt);
3189 
3190 	if (error == 0) {
3191 		ire_refrele(ire);		/* Held in ire_add_v4 */
3192 		/* tell routing sockets that we received a redirect */
3193 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3194 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3195 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
3196 	}
3197 
3198 	/*
3199 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3200 	 * This together with the added IRE has the effect of
3201 	 * modifying an existing redirect.
3202 	 */
3203 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3204 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), ipst);
3205 	if (prev_ire != NULL) {
3206 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3207 			ire_delete(prev_ire);
3208 		ire_refrele(prev_ire);
3209 	}
3210 
3211 	freemsg(mp);
3212 }
3213 
3214 /*
3215  * Generate an ICMP parameter problem message.
3216  */
3217 static void
3218 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid,
3219 	ip_stack_t *ipst)
3220 {
3221 	icmph_t	icmph;
3222 	boolean_t mctl_present;
3223 	mblk_t *first_mp;
3224 
3225 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3226 
3227 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3228 		if (mctl_present)
3229 			freeb(first_mp);
3230 		return;
3231 	}
3232 
3233 	bzero(&icmph, sizeof (icmph_t));
3234 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3235 	icmph.icmph_pp_ptr = ptr;
3236 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
3237 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3238 	    ipst);
3239 }
3240 
3241 /*
3242  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3243  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3244  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3245  * an icmp error packet can be sent.
3246  * Assigns an appropriate source address to the packet. If ipha_dst is
3247  * one of our addresses use it for source. Otherwise pick a source based
3248  * on a route lookup back to ipha_src.
3249  * Note that ipha_src must be set here since the
3250  * packet is likely to arrive on an ill queue in ip_wput() which will
3251  * not set a source address.
3252  */
3253 static void
3254 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3255     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
3256 {
3257 	ipaddr_t dst;
3258 	icmph_t	*icmph;
3259 	ipha_t	*ipha;
3260 	uint_t	len_needed;
3261 	size_t	msg_len;
3262 	mblk_t	*mp1;
3263 	ipaddr_t src;
3264 	ire_t	*ire;
3265 	mblk_t *ipsec_mp;
3266 	ipsec_out_t	*io = NULL;
3267 	boolean_t xmit_if_on = B_FALSE;
3268 
3269 	if (mctl_present) {
3270 		/*
3271 		 * If it is :
3272 		 *
3273 		 * 1) a IPSEC_OUT, then this is caused by outbound
3274 		 *    datagram originating on this host. IPSEC processing
3275 		 *    may or may not have been done. Refer to comments above
3276 		 *    icmp_inbound_error_fanout for details.
3277 		 *
3278 		 * 2) a IPSEC_IN if we are generating a icmp_message
3279 		 *    for an incoming datagram destined for us i.e called
3280 		 *    from ip_fanout_send_icmp.
3281 		 */
3282 		ipsec_info_t *in;
3283 		ipsec_mp = mp;
3284 		mp = ipsec_mp->b_cont;
3285 
3286 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3287 		ipha = (ipha_t *)mp->b_rptr;
3288 
3289 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3290 		    in->ipsec_info_type == IPSEC_IN);
3291 
3292 		if (in->ipsec_info_type == IPSEC_IN) {
3293 			/*
3294 			 * Convert the IPSEC_IN to IPSEC_OUT.
3295 			 */
3296 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3297 				BUMP_MIB(&ipst->ips_ip_mib,
3298 				    ipIfStatsOutDiscards);
3299 				return;
3300 			}
3301 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3302 		} else {
3303 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3304 			io = (ipsec_out_t *)in;
3305 			if (io->ipsec_out_xmit_if)
3306 				xmit_if_on = B_TRUE;
3307 			/*
3308 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3309 			 * ire lookup.
3310 			 */
3311 			io->ipsec_out_proc_begin = B_FALSE;
3312 		}
3313 		ASSERT(zoneid == io->ipsec_out_zoneid);
3314 		ASSERT(zoneid != ALL_ZONES);
3315 	} else {
3316 		/*
3317 		 * This is in clear. The icmp message we are building
3318 		 * here should go out in clear.
3319 		 *
3320 		 * Pardon the convolution of it all, but it's easier to
3321 		 * allocate a "use cleartext" IPSEC_IN message and convert
3322 		 * it than it is to allocate a new one.
3323 		 */
3324 		ipsec_in_t *ii;
3325 		ASSERT(DB_TYPE(mp) == M_DATA);
3326 		ipsec_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
3327 		if (ipsec_mp == NULL) {
3328 			freemsg(mp);
3329 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3330 			return;
3331 		}
3332 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3333 
3334 		/* This is not a secure packet */
3335 		ii->ipsec_in_secure = B_FALSE;
3336 		/*
3337 		 * For trusted extensions using a shared IP address we can
3338 		 * send using any zoneid.
3339 		 */
3340 		if (zoneid == ALL_ZONES)
3341 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3342 		else
3343 			ii->ipsec_in_zoneid = zoneid;
3344 		ipsec_mp->b_cont = mp;
3345 		ipha = (ipha_t *)mp->b_rptr;
3346 		/*
3347 		 * Convert the IPSEC_IN to IPSEC_OUT.
3348 		 */
3349 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3350 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3351 			return;
3352 		}
3353 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3354 	}
3355 
3356 	/* Remember our eventual destination */
3357 	dst = ipha->ipha_src;
3358 
3359 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3360 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE, ipst);
3361 	if (ire != NULL &&
3362 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3363 		src = ipha->ipha_dst;
3364 	} else if (!xmit_if_on) {
3365 		if (ire != NULL)
3366 			ire_refrele(ire);
3367 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3368 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY),
3369 		    ipst);
3370 		if (ire == NULL) {
3371 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3372 			freemsg(ipsec_mp);
3373 			return;
3374 		}
3375 		src = ire->ire_src_addr;
3376 	} else {
3377 		ipif_t	*ipif = NULL;
3378 		ill_t	*ill;
3379 		/*
3380 		 * This must be an ICMP error coming from
3381 		 * ip_mrtun_forward(). The src addr should
3382 		 * be equal to the IP-addr of the outgoing
3383 		 * interface.
3384 		 */
3385 		if (io == NULL) {
3386 			/* This is not a IPSEC_OUT type control msg */
3387 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3388 			freemsg(ipsec_mp);
3389 			return;
3390 		}
3391 		ill = ill_lookup_on_ifindex(io->ipsec_out_ill_index, B_FALSE,
3392 		    NULL, NULL, NULL, NULL, ipst);
3393 		if (ill != NULL) {
3394 			ipif = ipif_get_next_ipif(NULL, ill);
3395 			ill_refrele(ill);
3396 		}
3397 		if (ipif == NULL) {
3398 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3399 			freemsg(ipsec_mp);
3400 			return;
3401 		}
3402 		src = ipif->ipif_src_addr;
3403 		ipif_refrele(ipif);
3404 	}
3405 
3406 	if (ire != NULL)
3407 		ire_refrele(ire);
3408 
3409 	/*
3410 	 * Check if we can send back more then 8 bytes in addition to
3411 	 * the IP header.  We try to send 64 bytes of data and the internal
3412 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
3413 	 */
3414 	len_needed = IPH_HDR_LENGTH(ipha);
3415 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
3416 	    ipha->ipha_protocol == IPPROTO_IPV6) {
3417 
3418 		if (!pullupmsg(mp, -1)) {
3419 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3420 			freemsg(ipsec_mp);
3421 			return;
3422 		}
3423 		ipha = (ipha_t *)mp->b_rptr;
3424 
3425 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
3426 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
3427 			    len_needed));
3428 		} else {
3429 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
3430 
3431 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
3432 			len_needed += ip_hdr_length_v6(mp, ip6h);
3433 		}
3434 	}
3435 	len_needed += ipst->ips_ip_icmp_return;
3436 	msg_len = msgdsize(mp);
3437 	if (msg_len > len_needed) {
3438 		(void) adjmsg(mp, len_needed - msg_len);
3439 		msg_len = len_needed;
3440 	}
3441 	mp1 = allocb_tmpl(sizeof (icmp_ipha) + len, mp);
3442 	if (mp1 == NULL) {
3443 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
3444 		freemsg(ipsec_mp);
3445 		return;
3446 	}
3447 	mp1->b_cont = mp;
3448 	mp = mp1;
3449 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3450 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3451 	    io->ipsec_out_type == IPSEC_OUT);
3452 	ipsec_mp->b_cont = mp;
3453 
3454 	/*
3455 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3456 	 * node generates be accepted in peace by all on-host destinations.
3457 	 * If we do NOT assume that all on-host destinations trust
3458 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3459 	 * (Look for ipsec_out_icmp_loopback).
3460 	 */
3461 	io->ipsec_out_icmp_loopback = B_TRUE;
3462 
3463 	ipha = (ipha_t *)mp->b_rptr;
3464 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3465 	*ipha = icmp_ipha;
3466 	ipha->ipha_src = src;
3467 	ipha->ipha_dst = dst;
3468 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
3469 	msg_len += sizeof (icmp_ipha) + len;
3470 	if (msg_len > IP_MAXPACKET) {
3471 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3472 		msg_len = IP_MAXPACKET;
3473 	}
3474 	ipha->ipha_length = htons((uint16_t)msg_len);
3475 	icmph = (icmph_t *)&ipha[1];
3476 	bcopy(stuff, icmph, len);
3477 	icmph->icmph_checksum = 0;
3478 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3479 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
3480 	put(q, ipsec_mp);
3481 }
3482 
3483 /*
3484  * Determine if an ICMP error packet can be sent given the rate limit.
3485  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3486  * in milliseconds) and a burst size. Burst size number of packets can
3487  * be sent arbitrarely closely spaced.
3488  * The state is tracked using two variables to implement an approximate
3489  * token bucket filter:
3490  *	icmp_pkt_err_last - lbolt value when the last burst started
3491  *	icmp_pkt_err_sent - number of packets sent in current burst
3492  */
3493 boolean_t
3494 icmp_err_rate_limit(ip_stack_t *ipst)
3495 {
3496 	clock_t now = TICK_TO_MSEC(lbolt);
3497 	uint_t refilled; /* Number of packets refilled in tbf since last */
3498 	/* Guard against changes by loading into local variable */
3499 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
3500 
3501 	if (err_interval == 0)
3502 		return (B_FALSE);
3503 
3504 	if (ipst->ips_icmp_pkt_err_last > now) {
3505 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3506 		ipst->ips_icmp_pkt_err_last = 0;
3507 		ipst->ips_icmp_pkt_err_sent = 0;
3508 	}
3509 	/*
3510 	 * If we are in a burst update the token bucket filter.
3511 	 * Update the "last" time to be close to "now" but make sure
3512 	 * we don't loose precision.
3513 	 */
3514 	if (ipst->ips_icmp_pkt_err_sent != 0) {
3515 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
3516 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
3517 			ipst->ips_icmp_pkt_err_sent = 0;
3518 		} else {
3519 			ipst->ips_icmp_pkt_err_sent -= refilled;
3520 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
3521 		}
3522 	}
3523 	if (ipst->ips_icmp_pkt_err_sent == 0) {
3524 		/* Start of new burst */
3525 		ipst->ips_icmp_pkt_err_last = now;
3526 	}
3527 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
3528 		ipst->ips_icmp_pkt_err_sent++;
3529 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3530 		    ipst->ips_icmp_pkt_err_sent));
3531 		return (B_FALSE);
3532 	}
3533 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3534 	return (B_TRUE);
3535 }
3536 
3537 /*
3538  * Check if it is ok to send an IPv4 ICMP error packet in
3539  * response to the IPv4 packet in mp.
3540  * Free the message and return null if no
3541  * ICMP error packet should be sent.
3542  */
3543 static mblk_t *
3544 icmp_pkt_err_ok(mblk_t *mp, ip_stack_t *ipst)
3545 {
3546 	icmph_t	*icmph;
3547 	ipha_t	*ipha;
3548 	uint_t	len_needed;
3549 	ire_t	*src_ire;
3550 	ire_t	*dst_ire;
3551 
3552 	if (!mp)
3553 		return (NULL);
3554 	ipha = (ipha_t *)mp->b_rptr;
3555 	if (ip_csum_hdr(ipha)) {
3556 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
3557 		freemsg(mp);
3558 		return (NULL);
3559 	}
3560 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3561 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3562 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3563 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3564 	if (src_ire != NULL || dst_ire != NULL ||
3565 	    CLASSD(ipha->ipha_dst) ||
3566 	    CLASSD(ipha->ipha_src) ||
3567 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3568 		/* Note: only errors to the fragment with offset 0 */
3569 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3570 		freemsg(mp);
3571 		if (src_ire != NULL)
3572 			ire_refrele(src_ire);
3573 		if (dst_ire != NULL)
3574 			ire_refrele(dst_ire);
3575 		return (NULL);
3576 	}
3577 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3578 		/*
3579 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3580 		 * errors in response to any ICMP errors.
3581 		 */
3582 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3583 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3584 			if (!pullupmsg(mp, len_needed)) {
3585 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3586 				freemsg(mp);
3587 				return (NULL);
3588 			}
3589 			ipha = (ipha_t *)mp->b_rptr;
3590 		}
3591 		icmph = (icmph_t *)
3592 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3593 		switch (icmph->icmph_type) {
3594 		case ICMP_DEST_UNREACHABLE:
3595 		case ICMP_SOURCE_QUENCH:
3596 		case ICMP_TIME_EXCEEDED:
3597 		case ICMP_PARAM_PROBLEM:
3598 		case ICMP_REDIRECT:
3599 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3600 			freemsg(mp);
3601 			return (NULL);
3602 		default:
3603 			break;
3604 		}
3605 	}
3606 	/*
3607 	 * If this is a labeled system, then check to see if we're allowed to
3608 	 * send a response to this particular sender.  If not, then just drop.
3609 	 */
3610 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3611 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3612 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3613 		freemsg(mp);
3614 		return (NULL);
3615 	}
3616 	if (icmp_err_rate_limit(ipst)) {
3617 		/*
3618 		 * Only send ICMP error packets every so often.
3619 		 * This should be done on a per port/source basis,
3620 		 * but for now this will suffice.
3621 		 */
3622 		freemsg(mp);
3623 		return (NULL);
3624 	}
3625 	return (mp);
3626 }
3627 
3628 /*
3629  * Generate an ICMP redirect message.
3630  */
3631 static void
3632 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway, ip_stack_t *ipst)
3633 {
3634 	icmph_t	icmph;
3635 
3636 	/*
3637 	 * We are called from ip_rput where we could
3638 	 * not have attached an IPSEC_IN.
3639 	 */
3640 	ASSERT(mp->b_datap->db_type == M_DATA);
3641 
3642 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3643 		return;
3644 	}
3645 
3646 	bzero(&icmph, sizeof (icmph_t));
3647 	icmph.icmph_type = ICMP_REDIRECT;
3648 	icmph.icmph_code = 1;
3649 	icmph.icmph_rd_gateway = gateway;
3650 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3651 	/* Redirects sent by router, and router is global zone */
3652 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID, ipst);
3653 }
3654 
3655 /*
3656  * Generate an ICMP time exceeded message.
3657  */
3658 void
3659 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3660     ip_stack_t *ipst)
3661 {
3662 	icmph_t	icmph;
3663 	boolean_t mctl_present;
3664 	mblk_t *first_mp;
3665 
3666 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3667 
3668 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3669 		if (mctl_present)
3670 			freeb(first_mp);
3671 		return;
3672 	}
3673 
3674 	bzero(&icmph, sizeof (icmph_t));
3675 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3676 	icmph.icmph_code = code;
3677 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3678 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3679 	    ipst);
3680 }
3681 
3682 /*
3683  * Generate an ICMP unreachable message.
3684  */
3685 void
3686 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3687     ip_stack_t *ipst)
3688 {
3689 	icmph_t	icmph;
3690 	mblk_t *first_mp;
3691 	boolean_t mctl_present;
3692 
3693 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3694 
3695 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3696 		if (mctl_present)
3697 			freeb(first_mp);
3698 		return;
3699 	}
3700 
3701 	bzero(&icmph, sizeof (icmph_t));
3702 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3703 	icmph.icmph_code = code;
3704 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3705 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3706 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3707 	    zoneid, ipst);
3708 }
3709 
3710 /*
3711  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3712  * duplicate.  As long as someone else holds the address, the interface will
3713  * stay down.  When that conflict goes away, the interface is brought back up.
3714  * This is done so that accidental shutdowns of addresses aren't made
3715  * permanent.  Your server will recover from a failure.
3716  *
3717  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3718  * user space process (dhcpagent).
3719  *
3720  * Recovery completes if ARP reports that the address is now ours (via
3721  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3722  *
3723  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3724  */
3725 static void
3726 ipif_dup_recovery(void *arg)
3727 {
3728 	ipif_t *ipif = arg;
3729 	ill_t *ill = ipif->ipif_ill;
3730 	mblk_t *arp_add_mp;
3731 	mblk_t *arp_del_mp;
3732 	area_t *area;
3733 	ip_stack_t *ipst = ill->ill_ipst;
3734 
3735 	ipif->ipif_recovery_id = 0;
3736 
3737 	/*
3738 	 * No lock needed for moving or condemned check, as this is just an
3739 	 * optimization.
3740 	 */
3741 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3742 	    (ipif->ipif_flags & IPIF_POINTOPOINT) ||
3743 	    (ipif->ipif_state_flags & (IPIF_MOVING | IPIF_CONDEMNED))) {
3744 		/* No reason to try to bring this address back. */
3745 		return;
3746 	}
3747 
3748 	if ((arp_add_mp = ipif_area_alloc(ipif)) == NULL)
3749 		goto alloc_fail;
3750 
3751 	if (ipif->ipif_arp_del_mp == NULL) {
3752 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3753 			goto alloc_fail;
3754 		ipif->ipif_arp_del_mp = arp_del_mp;
3755 	}
3756 
3757 	/* Setting the 'unverified' flag restarts DAD */
3758 	area = (area_t *)arp_add_mp->b_rptr;
3759 	area->area_flags = ACE_F_PERMANENT | ACE_F_PUBLISH | ACE_F_MYADDR |
3760 	    ACE_F_UNVERIFIED;
3761 	putnext(ill->ill_rq, arp_add_mp);
3762 	return;
3763 
3764 alloc_fail:
3765 	/*
3766 	 * On allocation failure, just restart the timer.  Note that the ipif
3767 	 * is down here, so no other thread could be trying to start a recovery
3768 	 * timer.  The ill_lock protects the condemned flag and the recovery
3769 	 * timer ID.
3770 	 */
3771 	freemsg(arp_add_mp);
3772 	mutex_enter(&ill->ill_lock);
3773 	if (ipst->ips_ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0 &&
3774 	    !(ipif->ipif_state_flags & IPIF_CONDEMNED)) {
3775 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3776 		    MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3777 	}
3778 	mutex_exit(&ill->ill_lock);
3779 }
3780 
3781 /*
3782  * This is for exclusive changes due to ARP.  Either tear down an interface due
3783  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3784  */
3785 /* ARGSUSED */
3786 static void
3787 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3788 {
3789 	ill_t	*ill = rq->q_ptr;
3790 	arh_t *arh;
3791 	ipaddr_t src;
3792 	ipif_t	*ipif;
3793 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3794 	char hbuf[MAC_STR_LEN];
3795 	char sbuf[INET_ADDRSTRLEN];
3796 	const char *failtype;
3797 	boolean_t bring_up;
3798 	ip_stack_t *ipst = ill->ill_ipst;
3799 
3800 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3801 	case AR_CN_READY:
3802 		failtype = NULL;
3803 		bring_up = B_TRUE;
3804 		break;
3805 	case AR_CN_FAILED:
3806 		failtype = "in use";
3807 		bring_up = B_FALSE;
3808 		break;
3809 	default:
3810 		failtype = "claimed";
3811 		bring_up = B_FALSE;
3812 		break;
3813 	}
3814 
3815 	arh = (arh_t *)mp->b_cont->b_rptr;
3816 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3817 
3818 	/* Handle failures due to probes */
3819 	if (src == 0) {
3820 		bcopy((char *)&arh[1] + 2 * arh->arh_hlen + IP_ADDR_LEN, &src,
3821 		    IP_ADDR_LEN);
3822 	}
3823 
3824 	(void) strlcpy(ibuf, ill->ill_name, sizeof (ibuf));
3825 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3826 	    sizeof (hbuf));
3827 	(void) ip_dot_addr(src, sbuf);
3828 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3829 
3830 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3831 		    ipif->ipif_lcl_addr != src) {
3832 			continue;
3833 		}
3834 
3835 		/*
3836 		 * If we failed on a recovery probe, then restart the timer to
3837 		 * try again later.
3838 		 */
3839 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3840 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3841 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3842 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3843 		    ipst->ips_ip_dup_recovery > 0 &&
3844 		    ipif->ipif_recovery_id == 0) {
3845 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3846 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3847 			continue;
3848 		}
3849 
3850 		/*
3851 		 * If what we're trying to do has already been done, then do
3852 		 * nothing.
3853 		 */
3854 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3855 			continue;
3856 
3857 		if (ipif->ipif_id != 0) {
3858 			(void) snprintf(ibuf + ill->ill_name_length - 1,
3859 			    sizeof (ibuf) - ill->ill_name_length + 1, ":%d",
3860 			    ipif->ipif_id);
3861 		}
3862 		if (failtype == NULL) {
3863 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3864 			    ibuf);
3865 		} else {
3866 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3867 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3868 		}
3869 
3870 		if (bring_up) {
3871 			ASSERT(ill->ill_dl_up);
3872 			/*
3873 			 * Free up the ARP delete message so we can allocate
3874 			 * a fresh one through the normal path.
3875 			 */
3876 			freemsg(ipif->ipif_arp_del_mp);
3877 			ipif->ipif_arp_del_mp = NULL;
3878 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3879 			    EINPROGRESS) {
3880 				ipif->ipif_addr_ready = 1;
3881 				(void) ipif_up_done(ipif);
3882 			}
3883 			continue;
3884 		}
3885 
3886 		mutex_enter(&ill->ill_lock);
3887 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3888 		ipif->ipif_flags |= IPIF_DUPLICATE;
3889 		ill->ill_ipif_dup_count++;
3890 		mutex_exit(&ill->ill_lock);
3891 		/*
3892 		 * Already exclusive on the ill; no need to handle deferred
3893 		 * processing here.
3894 		 */
3895 		(void) ipif_down(ipif, NULL, NULL);
3896 		ipif_down_tail(ipif);
3897 		mutex_enter(&ill->ill_lock);
3898 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3899 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3900 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3901 		    ipst->ips_ip_dup_recovery > 0) {
3902 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3903 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3904 		}
3905 		mutex_exit(&ill->ill_lock);
3906 	}
3907 	freemsg(mp);
3908 }
3909 
3910 /* ARGSUSED */
3911 static void
3912 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3913 {
3914 	ill_t	*ill = rq->q_ptr;
3915 	arh_t *arh;
3916 	ipaddr_t src;
3917 	ipif_t	*ipif;
3918 
3919 	arh = (arh_t *)mp->b_cont->b_rptr;
3920 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3921 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3922 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3923 			(void) ipif_resolver_up(ipif, Res_act_defend);
3924 	}
3925 	freemsg(mp);
3926 }
3927 
3928 /*
3929  * News from ARP.  ARP sends notification of interesting events down
3930  * to its clients using M_CTL messages with the interesting ARP packet
3931  * attached via b_cont.
3932  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3933  * queue as opposed to ARP sending the message to all the clients, i.e. all
3934  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3935  * table if a cache IRE is found to delete all the entries for the address in
3936  * the packet.
3937  */
3938 static void
3939 ip_arp_news(queue_t *q, mblk_t *mp)
3940 {
3941 	arcn_t		*arcn;
3942 	arh_t		*arh;
3943 	ire_t		*ire = NULL;
3944 	char		hbuf[MAC_STR_LEN];
3945 	char		sbuf[INET_ADDRSTRLEN];
3946 	ipaddr_t	src;
3947 	in6_addr_t	v6src;
3948 	boolean_t	isv6 = B_FALSE;
3949 	ipif_t		*ipif;
3950 	ill_t		*ill;
3951 	ip_stack_t	*ipst;
3952 
3953 	if (CONN_Q(q)) {
3954 		conn_t *connp = Q_TO_CONN(q);
3955 
3956 		ipst = connp->conn_netstack->netstack_ip;
3957 	} else {
3958 		ill_t *ill = (ill_t *)q->q_ptr;
3959 
3960 		ipst = ill->ill_ipst;
3961 	}
3962 
3963 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3964 		if (q->q_next) {
3965 			putnext(q, mp);
3966 		} else
3967 			freemsg(mp);
3968 		return;
3969 	}
3970 	arh = (arh_t *)mp->b_cont->b_rptr;
3971 	/* Is it one we are interested in? */
3972 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3973 		isv6 = B_TRUE;
3974 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3975 		    IPV6_ADDR_LEN);
3976 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3977 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3978 		    IP_ADDR_LEN);
3979 	} else {
3980 		freemsg(mp);
3981 		return;
3982 	}
3983 
3984 	ill = q->q_ptr;
3985 
3986 	arcn = (arcn_t *)mp->b_rptr;
3987 	switch (arcn->arcn_code) {
3988 	case AR_CN_BOGON:
3989 		/*
3990 		 * Someone is sending ARP packets with a source protocol
3991 		 * address that we have published and for which we believe our
3992 		 * entry is authoritative and (when ill_arp_extend is set)
3993 		 * verified to be unique on the network.
3994 		 *
3995 		 * The ARP module internally handles the cases where the sender
3996 		 * is just probing (for DAD) and where the hardware address of
3997 		 * a non-authoritative entry has changed.  Thus, these are the
3998 		 * real conflicts, and we have to do resolution.
3999 		 *
4000 		 * We back away quickly from the address if it's from DHCP or
4001 		 * otherwise temporary and hasn't been used recently (or at
4002 		 * all).  We'd like to include "deprecated" addresses here as
4003 		 * well (as there's no real reason to defend something we're
4004 		 * discarding), but IPMP "reuses" this flag to mean something
4005 		 * other than the standard meaning.
4006 		 *
4007 		 * If the ARP module above is not extended (meaning that it
4008 		 * doesn't know how to defend the address), then we just log
4009 		 * the problem as we always did and continue on.  It's not
4010 		 * right, but there's little else we can do, and those old ATM
4011 		 * users are going away anyway.
4012 		 */
4013 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
4014 		    hbuf, sizeof (hbuf));
4015 		(void) ip_dot_addr(src, sbuf);
4016 		if (isv6) {
4017 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL,
4018 			    ipst);
4019 		} else {
4020 			ire = ire_cache_lookup(src, ALL_ZONES, NULL, ipst);
4021 		}
4022 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
4023 			uint32_t now;
4024 			uint32_t maxage;
4025 			clock_t lused;
4026 			uint_t maxdefense;
4027 			uint_t defs;
4028 
4029 			/*
4030 			 * First, figure out if this address hasn't been used
4031 			 * in a while.  If it hasn't, then it's a better
4032 			 * candidate for abandoning.
4033 			 */
4034 			ipif = ire->ire_ipif;
4035 			ASSERT(ipif != NULL);
4036 			now = gethrestime_sec();
4037 			maxage = now - ire->ire_create_time;
4038 			if (maxage > ipst->ips_ip_max_temp_idle)
4039 				maxage = ipst->ips_ip_max_temp_idle;
4040 			lused = drv_hztousec(ddi_get_lbolt() -
4041 			    ire->ire_last_used_time) / MICROSEC + 1;
4042 			if (lused >= maxage && (ipif->ipif_flags &
4043 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
4044 				maxdefense = ipst->ips_ip_max_temp_defend;
4045 			else
4046 				maxdefense = ipst->ips_ip_max_defend;
4047 
4048 			/*
4049 			 * Now figure out how many times we've defended
4050 			 * ourselves.  Ignore defenses that happened long in
4051 			 * the past.
4052 			 */
4053 			mutex_enter(&ire->ire_lock);
4054 			if ((defs = ire->ire_defense_count) > 0 &&
4055 			    now - ire->ire_defense_time >
4056 			    ipst->ips_ip_defend_interval) {
4057 				ire->ire_defense_count = defs = 0;
4058 			}
4059 			ire->ire_defense_count++;
4060 			ire->ire_defense_time = now;
4061 			mutex_exit(&ire->ire_lock);
4062 			ill_refhold(ill);
4063 			ire_refrele(ire);
4064 
4065 			/*
4066 			 * If we've defended ourselves too many times already,
4067 			 * then give up and tear down the interface(s) using
4068 			 * this address.  Otherwise, defend by sending out a
4069 			 * gratuitous ARP.
4070 			 */
4071 			if (defs >= maxdefense && ill->ill_arp_extend) {
4072 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4073 				    B_FALSE);
4074 			} else {
4075 				cmn_err(CE_WARN,
4076 				    "node %s is using our IP address %s on %s",
4077 				    hbuf, sbuf, ill->ill_name);
4078 				/*
4079 				 * If this is an old (ATM) ARP module, then
4080 				 * don't try to defend the address.  Remain
4081 				 * compatible with the old behavior.  Defend
4082 				 * only with new ARP.
4083 				 */
4084 				if (ill->ill_arp_extend) {
4085 					qwriter_ip(ill, q, mp, ip_arp_defend,
4086 					    NEW_OP, B_FALSE);
4087 				} else {
4088 					ill_refrele(ill);
4089 				}
4090 			}
4091 			return;
4092 		}
4093 		cmn_err(CE_WARN,
4094 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4095 		    hbuf, sbuf, ill->ill_name);
4096 		if (ire != NULL)
4097 			ire_refrele(ire);
4098 		break;
4099 	case AR_CN_ANNOUNCE:
4100 		if (isv6) {
4101 			/*
4102 			 * For XRESOLV interfaces.
4103 			 * Delete the IRE cache entry and NCE for this
4104 			 * v6 address
4105 			 */
4106 			ip_ire_clookup_and_delete_v6(&v6src, ipst);
4107 			/*
4108 			 * If v6src is a non-zero, it's a router address
4109 			 * as below. Do the same sort of thing to clean
4110 			 * out off-net IRE_CACHE entries that go through
4111 			 * the router.
4112 			 */
4113 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4114 				ire_walk_v6(ire_delete_cache_gw_v6,
4115 				    (char *)&v6src, ALL_ZONES, ipst);
4116 			}
4117 		} else {
4118 			nce_hw_map_t hwm;
4119 
4120 			/*
4121 			 * ARP gives us a copy of any packet where it thinks
4122 			 * the address has changed, so that we can update our
4123 			 * caches.  We're responsible for caching known answers
4124 			 * in the current design.  We check whether the
4125 			 * hardware address really has changed in all of our
4126 			 * entries that have cached this mapping, and if so, we
4127 			 * blow them away.  This way we will immediately pick
4128 			 * up the rare case of a host changing hardware
4129 			 * address.
4130 			 */
4131 			if (src == 0)
4132 				break;
4133 			hwm.hwm_addr = src;
4134 			hwm.hwm_hwlen = arh->arh_hlen;
4135 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4136 			ndp_walk_common(ipst->ips_ndp4, NULL,
4137 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4138 		}
4139 		break;
4140 	case AR_CN_READY:
4141 		/* No external v6 resolver has a contract to use this */
4142 		if (isv6)
4143 			break;
4144 		/* If the link is down, we'll retry this later */
4145 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4146 			break;
4147 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4148 		    NULL, NULL, ipst);
4149 		if (ipif != NULL) {
4150 			/*
4151 			 * If this is a duplicate recovery, then we now need to
4152 			 * go exclusive to bring this thing back up.
4153 			 */
4154 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4155 			    IPIF_DUPLICATE) {
4156 				ipif_refrele(ipif);
4157 				ill_refhold(ill);
4158 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4159 				    B_FALSE);
4160 				return;
4161 			}
4162 			/*
4163 			 * If this is the first notice that this address is
4164 			 * ready, then let the user know now.
4165 			 */
4166 			if ((ipif->ipif_flags & IPIF_UP) &&
4167 			    !ipif->ipif_addr_ready) {
4168 				ipif_mask_reply(ipif);
4169 				ip_rts_ifmsg(ipif);
4170 				ip_rts_newaddrmsg(RTM_ADD, 0, ipif);
4171 				sctp_update_ipif(ipif, SCTP_IPIF_UP);
4172 			}
4173 			ipif->ipif_addr_ready = 1;
4174 			ipif_refrele(ipif);
4175 		}
4176 		ire = ire_cache_lookup(src, ALL_ZONES, MBLK_GETLABEL(mp), ipst);
4177 		if (ire != NULL) {
4178 			ire->ire_defense_count = 0;
4179 			ire_refrele(ire);
4180 		}
4181 		break;
4182 	case AR_CN_FAILED:
4183 		/* No external v6 resolver has a contract to use this */
4184 		if (isv6)
4185 			break;
4186 		ill_refhold(ill);
4187 		qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP, B_FALSE);
4188 		return;
4189 	}
4190 	freemsg(mp);
4191 }
4192 
4193 /*
4194  * Create a mblk suitable for carrying the interface index and/or source link
4195  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4196  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4197  * application.
4198  */
4199 mblk_t *
4200 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags, zoneid_t zoneid,
4201     ip_stack_t *ipst)
4202 {
4203 	mblk_t		*mp;
4204 	ip_pktinfo_t	*pinfo;
4205 	ipha_t *ipha;
4206 	struct ether_header *pether;
4207 
4208 	mp = allocb(sizeof (ip_pktinfo_t), BPRI_MED);
4209 	if (mp == NULL) {
4210 		ip1dbg(("ip_add_info: allocation failure.\n"));
4211 		return (data_mp);
4212 	}
4213 
4214 	ipha	= (ipha_t *)data_mp->b_rptr;
4215 	pinfo = (ip_pktinfo_t *)mp->b_rptr;
4216 	bzero(pinfo, sizeof (ip_pktinfo_t));
4217 	pinfo->ip_pkt_flags = (uchar_t)flags;
4218 	pinfo->ip_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4219 
4220 	if (flags & (IPF_RECVIF | IPF_RECVADDR))
4221 		pinfo->ip_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4222 	if (flags & IPF_RECVADDR) {
4223 		ipif_t	*ipif;
4224 		ire_t	*ire;
4225 
4226 		/*
4227 		 * Only valid for V4
4228 		 */
4229 		ASSERT((ipha->ipha_version_and_hdr_length & 0xf0) ==
4230 		    (IPV4_VERSION << 4));
4231 
4232 		ipif = ipif_get_next_ipif(NULL, ill);
4233 		if (ipif != NULL) {
4234 			/*
4235 			 * Since a decision has already been made to deliver the
4236 			 * packet, there is no need to test for SECATTR and
4237 			 * ZONEONLY.
4238 			 * When a multicast packet is transmitted
4239 			 * a cache entry is created for the multicast address.
4240 			 * When delivering a copy of the packet or when new
4241 			 * packets are received we do not want to match on the
4242 			 * cached entry so explicitly match on
4243 			 * IRE_LOCAL and IRE_LOOPBACK
4244 			 */
4245 			ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4246 			    IRE_LOCAL | IRE_LOOPBACK,
4247 			    ipif, zoneid, NULL,
4248 			    MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP, ipst);
4249 			if (ire == NULL) {
4250 				/*
4251 				 * packet must have come on a different
4252 				 * interface.
4253 				 * Since a decision has already been made to
4254 				 * deliver the packet, there is no need to test
4255 				 * for SECATTR and ZONEONLY.
4256 				 * Only match on local and broadcast ire's.
4257 				 * See detailed comment above.
4258 				 */
4259 				ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4260 				    IRE_LOCAL | IRE_LOOPBACK, ipif, zoneid,
4261 				    NULL, MATCH_IRE_TYPE, ipst);
4262 			}
4263 
4264 			if (ire == NULL) {
4265 				/*
4266 				 * This is either a multicast packet or
4267 				 * the address has been removed since
4268 				 * the packet was received.
4269 				 * Return INADDR_ANY so that normal source
4270 				 * selection occurs for the response.
4271 				 */
4272 
4273 				pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4274 			} else {
4275 				pinfo->ip_pkt_match_addr.s_addr =
4276 				    ire->ire_src_addr;
4277 				ire_refrele(ire);
4278 			}
4279 			ipif_refrele(ipif);
4280 		} else {
4281 			pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4282 		}
4283 	}
4284 
4285 	pether = (struct ether_header *)((char *)ipha
4286 	    - sizeof (struct ether_header));
4287 	/*
4288 	 * Make sure the interface is an ethernet type, since this option
4289 	 * is currently supported only on this type of interface. Also make
4290 	 * sure we are pointing correctly above db_base.
4291 	 */
4292 
4293 	if ((flags & IPF_RECVSLLA) &&
4294 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4295 	    (ill->ill_type == IFT_ETHER) &&
4296 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4297 
4298 		pinfo->ip_pkt_slla.sdl_type = IFT_ETHER;
4299 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
4300 		    (uchar_t *)pinfo->ip_pkt_slla.sdl_data, ETHERADDRL);
4301 	} else {
4302 		/*
4303 		 * Clear the bit. Indicate to upper layer that IP is not
4304 		 * sending this ancillary info.
4305 		 */
4306 		pinfo->ip_pkt_flags = pinfo->ip_pkt_flags & ~IPF_RECVSLLA;
4307 	}
4308 
4309 	mp->b_datap->db_type = M_CTL;
4310 	mp->b_wptr += sizeof (ip_pktinfo_t);
4311 	mp->b_cont = data_mp;
4312 
4313 	return (mp);
4314 }
4315 
4316 /*
4317  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4318  * part of the bind request.
4319  */
4320 
4321 boolean_t
4322 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4323 {
4324 	ipsec_in_t *ii;
4325 
4326 	ASSERT(policy_mp != NULL);
4327 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4328 
4329 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4330 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4331 
4332 	connp->conn_policy = ii->ipsec_in_policy;
4333 	ii->ipsec_in_policy = NULL;
4334 
4335 	if (ii->ipsec_in_action != NULL) {
4336 		if (connp->conn_latch == NULL) {
4337 			connp->conn_latch = iplatch_create();
4338 			if (connp->conn_latch == NULL)
4339 				return (B_FALSE);
4340 		}
4341 		ipsec_latch_inbound(connp->conn_latch, ii);
4342 	}
4343 	return (B_TRUE);
4344 }
4345 
4346 /*
4347  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4348  * and to arrange for power-fanout assist.  The ULP is identified by
4349  * adding a single byte at the end of the original bind message.
4350  * A ULP other than UDP or TCP that wishes to be recognized passes
4351  * down a bind with a zero length address.
4352  *
4353  * The binding works as follows:
4354  * - A zero byte address means just bind to the protocol.
4355  * - A four byte address is treated as a request to validate
4356  *   that the address is a valid local address, appropriate for
4357  *   an application to bind to. This does not affect any fanout
4358  *   information in IP.
4359  * - A sizeof sin_t byte address is used to bind to only the local address
4360  *   and port.
4361  * - A sizeof ipa_conn_t byte address contains complete fanout information
4362  *   consisting of local and remote addresses and ports.  In
4363  *   this case, the addresses are both validated as appropriate
4364  *   for this operation, and, if so, the information is retained
4365  *   for use in the inbound fanout.
4366  *
4367  * The ULP (except in the zero-length bind) can append an
4368  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4369  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4370  * a copy of the source or destination IRE (source for local bind;
4371  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4372  * policy information contained should be copied on to the conn.
4373  *
4374  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4375  */
4376 mblk_t *
4377 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4378 {
4379 	ssize_t		len;
4380 	struct T_bind_req	*tbr;
4381 	sin_t		*sin;
4382 	ipa_conn_t	*ac;
4383 	uchar_t		*ucp;
4384 	mblk_t		*mp1;
4385 	boolean_t	ire_requested;
4386 	boolean_t	ipsec_policy_set = B_FALSE;
4387 	int		error = 0;
4388 	int		protocol;
4389 	ipa_conn_x_t	*acx;
4390 
4391 	ASSERT(!connp->conn_af_isv6);
4392 	connp->conn_pkt_isv6 = B_FALSE;
4393 
4394 	len = MBLKL(mp);
4395 	if (len < (sizeof (*tbr) + 1)) {
4396 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4397 		    "ip_bind: bogus msg, len %ld", len);
4398 		/* XXX: Need to return something better */
4399 		goto bad_addr;
4400 	}
4401 	/* Back up and extract the protocol identifier. */
4402 	mp->b_wptr--;
4403 	protocol = *mp->b_wptr & 0xFF;
4404 	tbr = (struct T_bind_req *)mp->b_rptr;
4405 	/* Reset the message type in preparation for shipping it back. */
4406 	DB_TYPE(mp) = M_PCPROTO;
4407 
4408 	connp->conn_ulp = (uint8_t)protocol;
4409 
4410 	/*
4411 	 * Check for a zero length address.  This is from a protocol that
4412 	 * wants to register to receive all packets of its type.
4413 	 */
4414 	if (tbr->ADDR_length == 0) {
4415 		/*
4416 		 * These protocols are now intercepted in ip_bind_v6().
4417 		 * Reject protocol-level binds here for now.
4418 		 *
4419 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4420 		 * so that the protocol type cannot be SCTP.
4421 		 */
4422 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4423 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4424 			goto bad_addr;
4425 		}
4426 
4427 		/*
4428 		 *
4429 		 * The udp module never sends down a zero-length address,
4430 		 * and allowing this on a labeled system will break MLP
4431 		 * functionality.
4432 		 */
4433 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4434 			goto bad_addr;
4435 
4436 		if (connp->conn_mac_exempt)
4437 			goto bad_addr;
4438 
4439 		/* No hash here really.  The table is big enough. */
4440 		connp->conn_srcv6 = ipv6_all_zeros;
4441 
4442 		ipcl_proto_insert(connp, protocol);
4443 
4444 		tbr->PRIM_type = T_BIND_ACK;
4445 		return (mp);
4446 	}
4447 
4448 	/* Extract the address pointer from the message. */
4449 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4450 	    tbr->ADDR_length);
4451 	if (ucp == NULL) {
4452 		ip1dbg(("ip_bind: no address\n"));
4453 		goto bad_addr;
4454 	}
4455 	if (!OK_32PTR(ucp)) {
4456 		ip1dbg(("ip_bind: unaligned address\n"));
4457 		goto bad_addr;
4458 	}
4459 	/*
4460 	 * Check for trailing mps.
4461 	 */
4462 
4463 	mp1 = mp->b_cont;
4464 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4465 	ipsec_policy_set = (mp1 != NULL && DB_TYPE(mp1) == IPSEC_POLICY_SET);
4466 
4467 	switch (tbr->ADDR_length) {
4468 	default:
4469 		ip1dbg(("ip_bind: bad address length %d\n",
4470 		    (int)tbr->ADDR_length));
4471 		goto bad_addr;
4472 
4473 	case IP_ADDR_LEN:
4474 		/* Verification of local address only */
4475 		error = ip_bind_laddr(connp, mp, *(ipaddr_t *)ucp, 0,
4476 		    ire_requested, ipsec_policy_set, B_FALSE);
4477 		break;
4478 
4479 	case sizeof (sin_t):
4480 		sin = (sin_t *)ucp;
4481 		error = ip_bind_laddr(connp, mp, sin->sin_addr.s_addr,
4482 		    sin->sin_port, ire_requested, ipsec_policy_set, B_TRUE);
4483 		break;
4484 
4485 	case sizeof (ipa_conn_t):
4486 		ac = (ipa_conn_t *)ucp;
4487 		/* For raw socket, the local port is not set. */
4488 		if (ac->ac_lport == 0)
4489 			ac->ac_lport = connp->conn_lport;
4490 		/* Always verify destination reachability. */
4491 		error = ip_bind_connected(connp, mp, &ac->ac_laddr,
4492 		    ac->ac_lport, ac->ac_faddr, ac->ac_fport, ire_requested,
4493 		    ipsec_policy_set, B_TRUE, B_TRUE);
4494 		break;
4495 
4496 	case sizeof (ipa_conn_x_t):
4497 		acx = (ipa_conn_x_t *)ucp;
4498 		/*
4499 		 * Whether or not to verify destination reachability depends
4500 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4501 		 */
4502 		error = ip_bind_connected(connp, mp, &acx->acx_conn.ac_laddr,
4503 		    acx->acx_conn.ac_lport, acx->acx_conn.ac_faddr,
4504 		    acx->acx_conn.ac_fport, ire_requested, ipsec_policy_set,
4505 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
4506 		break;
4507 	}
4508 	if (error == EINPROGRESS)
4509 		return (NULL);
4510 	else if (error != 0)
4511 		goto bad_addr;
4512 	/*
4513 	 * Pass the IPSEC headers size in ire_ipsec_overhead.
4514 	 * We can't do this in ip_bind_insert_ire because the policy
4515 	 * may not have been inherited at that point in time and hence
4516 	 * conn_out_enforce_policy may not be set.
4517 	 */
4518 	mp1 = mp->b_cont;
4519 	if (ire_requested && connp->conn_out_enforce_policy &&
4520 	    mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE) {
4521 		ire_t *ire = (ire_t *)mp1->b_rptr;
4522 		ASSERT(MBLKL(mp1) >= sizeof (ire_t));
4523 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4524 	}
4525 
4526 	/* Send it home. */
4527 	mp->b_datap->db_type = M_PCPROTO;
4528 	tbr->PRIM_type = T_BIND_ACK;
4529 	return (mp);
4530 
4531 bad_addr:
4532 	/*
4533 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4534 	 * a unix errno.
4535 	 */
4536 	if (error > 0)
4537 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4538 	else
4539 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4540 	return (mp);
4541 }
4542 
4543 /*
4544  * Here address is verified to be a valid local address.
4545  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4546  * address is also considered a valid local address.
4547  * In the case of a broadcast/multicast address, however, the
4548  * upper protocol is expected to reset the src address
4549  * to 0 if it sees a IRE_BROADCAST type returned so that
4550  * no packets are emitted with broadcast/multicast address as
4551  * source address (that violates hosts requirements RFC1122)
4552  * The addresses valid for bind are:
4553  *	(1) - INADDR_ANY (0)
4554  *	(2) - IP address of an UP interface
4555  *	(3) - IP address of a DOWN interface
4556  *	(4) - valid local IP broadcast addresses. In this case
4557  *	the conn will only receive packets destined to
4558  *	the specified broadcast address.
4559  *	(5) - a multicast address. In this case
4560  *	the conn will only receive packets destined to
4561  *	the specified multicast address. Note: the
4562  *	application still has to issue an
4563  *	IP_ADD_MEMBERSHIP socket option.
4564  *
4565  * On error, return -1 for TBADADDR otherwise pass the
4566  * errno with TSYSERR reply.
4567  *
4568  * In all the above cases, the bound address must be valid in the current zone.
4569  * When the address is loopback, multicast or broadcast, there might be many
4570  * matching IREs so bind has to look up based on the zone.
4571  *
4572  * Note: lport is in network byte order.
4573  */
4574 int
4575 ip_bind_laddr(conn_t *connp, mblk_t *mp, ipaddr_t src_addr, uint16_t lport,
4576     boolean_t ire_requested, boolean_t ipsec_policy_set,
4577     boolean_t fanout_insert)
4578 {
4579 	int		error = 0;
4580 	ire_t		*src_ire;
4581 	mblk_t		*policy_mp;
4582 	ipif_t		*ipif;
4583 	zoneid_t	zoneid;
4584 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4585 
4586 	if (ipsec_policy_set) {
4587 		policy_mp = mp->b_cont;
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 	ipif = NULL;
4598 
4599 	zoneid = IPCL_ZONEID(connp);
4600 
4601 	if (src_addr) {
4602 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4603 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
4604 		/*
4605 		 * If an address other than 0.0.0.0 is requested,
4606 		 * we verify that it is a valid address for bind
4607 		 * Note: Following code is in if-else-if form for
4608 		 * readability compared to a condition check.
4609 		 */
4610 		/* LINTED - statement has no consequent */
4611 		if (IRE_IS_LOCAL(src_ire)) {
4612 			/*
4613 			 * (2) Bind to address of local UP interface
4614 			 */
4615 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4616 			/*
4617 			 * (4) Bind to broadcast address
4618 			 * Note: permitted only from transports that
4619 			 * request IRE
4620 			 */
4621 			if (!ire_requested)
4622 				error = EADDRNOTAVAIL;
4623 		} else {
4624 			/*
4625 			 * (3) Bind to address of local DOWN interface
4626 			 * (ipif_lookup_addr() looks up all interfaces
4627 			 * but we do not get here for UP interfaces
4628 			 * - case (2) above)
4629 			 * We put the protocol byte back into the mblk
4630 			 * since we may come back via ip_wput_nondata()
4631 			 * later with this mblk if ipif_lookup_addr chooses
4632 			 * to defer processing.
4633 			 */
4634 			*mp->b_wptr++ = (char)connp->conn_ulp;
4635 			if ((ipif = ipif_lookup_addr(src_addr, NULL, zoneid,
4636 			    CONNP_TO_WQ(connp), mp, ip_wput_nondata,
4637 			    &error, ipst)) != NULL) {
4638 				ipif_refrele(ipif);
4639 			} else if (error == EINPROGRESS) {
4640 				if (src_ire != NULL)
4641 					ire_refrele(src_ire);
4642 				return (EINPROGRESS);
4643 			} else if (CLASSD(src_addr)) {
4644 				error = 0;
4645 				if (src_ire != NULL)
4646 					ire_refrele(src_ire);
4647 				/*
4648 				 * (5) bind to multicast address.
4649 				 * Fake out the IRE returned to upper
4650 				 * layer to be a broadcast IRE.
4651 				 */
4652 				src_ire = ire_ctable_lookup(
4653 				    INADDR_BROADCAST, INADDR_ANY,
4654 				    IRE_BROADCAST, NULL, zoneid, NULL,
4655 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY),
4656 				    ipst);
4657 				if (src_ire == NULL || !ire_requested)
4658 					error = EADDRNOTAVAIL;
4659 			} else {
4660 				/*
4661 				 * Not a valid address for bind
4662 				 */
4663 				error = EADDRNOTAVAIL;
4664 			}
4665 			/*
4666 			 * Just to keep it consistent with the processing in
4667 			 * ip_bind_v4()
4668 			 */
4669 			mp->b_wptr--;
4670 		}
4671 		if (error) {
4672 			/* Red Alert!  Attempting to be a bogon! */
4673 			ip1dbg(("ip_bind: bad src address 0x%x\n",
4674 			    ntohl(src_addr)));
4675 			goto bad_addr;
4676 		}
4677 	}
4678 
4679 	/*
4680 	 * Allow setting new policies. For example, disconnects come
4681 	 * down as ipa_t bind. As we would have set conn_policy_cached
4682 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4683 	 * can change after the disconnect.
4684 	 */
4685 	connp->conn_policy_cached = B_FALSE;
4686 
4687 	/*
4688 	 * If not fanout_insert this was just an address verification
4689 	 */
4690 	if (fanout_insert) {
4691 		/*
4692 		 * The addresses have been verified. Time to insert in
4693 		 * the correct fanout list.
4694 		 */
4695 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4696 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4697 		connp->conn_lport = lport;
4698 		connp->conn_fport = 0;
4699 		/*
4700 		 * Do we need to add a check to reject Multicast packets
4701 		 *
4702 		 * We need to make sure that the conn_recv is set to a non-null
4703 		 * value before we insert the conn into the classifier table.
4704 		 * This is to avoid a race with an incoming packet which does an
4705 		 * ipcl_classify().
4706 		 */
4707 		if (*mp->b_wptr == IPPROTO_TCP)
4708 			connp->conn_recv = tcp_conn_request;
4709 		error = ipcl_bind_insert(connp, *mp->b_wptr, src_addr, lport);
4710 	}
4711 
4712 	if (error == 0) {
4713 		if (ire_requested) {
4714 			if (!ip_bind_insert_ire(mp, src_ire, NULL, ipst)) {
4715 				error = -1;
4716 				/* Falls through to bad_addr */
4717 			}
4718 		} else if (ipsec_policy_set) {
4719 			if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4720 				error = -1;
4721 				/* Falls through to bad_addr */
4722 			}
4723 		}
4724 	} else if (connp->conn_ulp == IPPROTO_TCP) {
4725 		connp->conn_recv = tcp_input;
4726 	}
4727 bad_addr:
4728 	if (error != 0) {
4729 		if (connp->conn_anon_port) {
4730 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4731 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4732 			    B_FALSE);
4733 		}
4734 		connp->conn_mlp_type = mlptSingle;
4735 	}
4736 	if (src_ire != NULL)
4737 		IRE_REFRELE(src_ire);
4738 	if (ipsec_policy_set) {
4739 		ASSERT(policy_mp == mp->b_cont);
4740 		ASSERT(policy_mp != NULL);
4741 		freeb(policy_mp);
4742 		/*
4743 		 * As of now assume that nothing else accompanies
4744 		 * IPSEC_POLICY_SET.
4745 		 */
4746 		mp->b_cont = NULL;
4747 	}
4748 	return (error);
4749 }
4750 
4751 /*
4752  * Verify that both the source and destination addresses
4753  * are valid.  If verify_dst is false, then the destination address may be
4754  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4755  * destination reachability, while tunnels do not.
4756  * Note that we allow connect to broadcast and multicast
4757  * addresses when ire_requested is set. Thus the ULP
4758  * has to check for IRE_BROADCAST and multicast.
4759  *
4760  * Returns zero if ok.
4761  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4762  * (for use with TSYSERR reply).
4763  *
4764  * Note: lport and fport are in network byte order.
4765  */
4766 int
4767 ip_bind_connected(conn_t *connp, mblk_t *mp, ipaddr_t *src_addrp,
4768     uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4769     boolean_t ire_requested, boolean_t ipsec_policy_set,
4770     boolean_t fanout_insert, boolean_t verify_dst)
4771 {
4772 	ire_t		*src_ire;
4773 	ire_t		*dst_ire;
4774 	int		error = 0;
4775 	int 		protocol;
4776 	mblk_t		*policy_mp;
4777 	ire_t		*sire = NULL;
4778 	ire_t		*md_dst_ire = NULL;
4779 	ire_t		*lso_dst_ire = NULL;
4780 	ill_t		*ill = NULL;
4781 	zoneid_t	zoneid;
4782 	ipaddr_t	src_addr = *src_addrp;
4783 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4784 
4785 	src_ire = dst_ire = NULL;
4786 	protocol = *mp->b_wptr & 0xFF;
4787 
4788 	/*
4789 	 * If we never got a disconnect before, clear it now.
4790 	 */
4791 	connp->conn_fully_bound = B_FALSE;
4792 
4793 	if (ipsec_policy_set) {
4794 		policy_mp = mp->b_cont;
4795 	}
4796 
4797 	zoneid = IPCL_ZONEID(connp);
4798 
4799 	if (CLASSD(dst_addr)) {
4800 		/* Pick up an IRE_BROADCAST */
4801 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4802 		    NULL, zoneid, MBLK_GETLABEL(mp),
4803 		    (MATCH_IRE_RECURSIVE |
4804 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4805 		    MATCH_IRE_SECATTR), ipst);
4806 	} else {
4807 		/*
4808 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4809 		 * and onlink ipif is not found set ENETUNREACH error.
4810 		 */
4811 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4812 			ipif_t *ipif;
4813 
4814 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4815 			    dst_addr : connp->conn_nexthop_v4, zoneid, ipst);
4816 			if (ipif == NULL) {
4817 				error = ENETUNREACH;
4818 				goto bad_addr;
4819 			}
4820 			ipif_refrele(ipif);
4821 		}
4822 
4823 		if (connp->conn_nexthop_set) {
4824 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4825 			    0, 0, NULL, NULL, zoneid, MBLK_GETLABEL(mp),
4826 			    MATCH_IRE_SECATTR, ipst);
4827 		} else {
4828 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4829 			    &sire, zoneid, MBLK_GETLABEL(mp),
4830 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4831 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4832 			    MATCH_IRE_SECATTR), ipst);
4833 		}
4834 	}
4835 	/*
4836 	 * dst_ire can't be a broadcast when not ire_requested.
4837 	 * We also prevent ire's with src address INADDR_ANY to
4838 	 * be used, which are created temporarily for
4839 	 * sending out packets from endpoints that have
4840 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4841 	 * reachable.  If verify_dst is false, the destination needn't be
4842 	 * reachable.
4843 	 *
4844 	 * If we match on a reject or black hole, then we've got a
4845 	 * local failure.  May as well fail out the connect() attempt,
4846 	 * since it's never going to succeed.
4847 	 */
4848 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4849 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4850 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4851 		/*
4852 		 * If we're verifying destination reachability, we always want
4853 		 * to complain here.
4854 		 *
4855 		 * If we're not verifying destination reachability but the
4856 		 * destination has a route, we still want to fail on the
4857 		 * temporary address and broadcast address tests.
4858 		 */
4859 		if (verify_dst || (dst_ire != NULL)) {
4860 			if (ip_debug > 2) {
4861 				pr_addr_dbg("ip_bind_connected: bad connected "
4862 				    "dst %s\n", 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: no label for dst %s\n",
4894 			    AF_INET, &dst_addr);
4895 		}
4896 		goto bad_addr;
4897 	}
4898 
4899 	/*
4900 	 * If the app does a connect(), it means that it will most likely
4901 	 * send more than 1 packet to the destination.  It makes sense
4902 	 * to clear the temporary flag.
4903 	 */
4904 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4905 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4906 		irb_t *irb = dst_ire->ire_bucket;
4907 
4908 		rw_enter(&irb->irb_lock, RW_WRITER);
4909 		dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4910 		irb->irb_tmp_ire_cnt--;
4911 		rw_exit(&irb->irb_lock);
4912 	}
4913 
4914 	/*
4915 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4916 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4917 	 * eligibility tests for passive connects are handled separately
4918 	 * through tcp_adapt_ire().  We do this before the source address
4919 	 * selection, because dst_ire may change after a call to
4920 	 * ipif_select_source().  This is a best-effort check, as the
4921 	 * packet for this connection may not actually go through
4922 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4923 	 * calling ip_newroute().  This is why we further check on the
4924 	 * IRE during LSO/Multidata packet transmission in
4925 	 * tcp_lsosend()/tcp_multisend().
4926 	 */
4927 	if (!ipsec_policy_set && dst_ire != NULL &&
4928 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4929 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4930 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4931 			lso_dst_ire = dst_ire;
4932 			IRE_REFHOLD(lso_dst_ire);
4933 		} else if (ipst->ips_ip_multidata_outbound &&
4934 		    ILL_MDT_CAPABLE(ill)) {
4935 			md_dst_ire = dst_ire;
4936 			IRE_REFHOLD(md_dst_ire);
4937 		}
4938 	}
4939 
4940 	if (dst_ire != NULL &&
4941 	    dst_ire->ire_type == IRE_LOCAL &&
4942 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4943 		/*
4944 		 * If the IRE belongs to a different zone, look for a matching
4945 		 * route in the forwarding table and use the source address from
4946 		 * that route.
4947 		 */
4948 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4949 		    zoneid, 0, NULL,
4950 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4951 		    MATCH_IRE_RJ_BHOLE, ipst);
4952 		if (src_ire == NULL) {
4953 			error = EHOSTUNREACH;
4954 			goto bad_addr;
4955 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4956 			if (!(src_ire->ire_type & IRE_HOST))
4957 				error = ENETUNREACH;
4958 			else
4959 				error = EHOSTUNREACH;
4960 			goto bad_addr;
4961 		}
4962 		if (src_addr == INADDR_ANY)
4963 			src_addr = src_ire->ire_src_addr;
4964 		ire_refrele(src_ire);
4965 		src_ire = NULL;
4966 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4967 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4968 			src_addr = sire->ire_src_addr;
4969 			ire_refrele(dst_ire);
4970 			dst_ire = sire;
4971 			sire = NULL;
4972 		} else {
4973 			/*
4974 			 * Pick a source address so that a proper inbound
4975 			 * load spreading would happen.
4976 			 */
4977 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4978 			ipif_t *src_ipif = NULL;
4979 			ire_t *ipif_ire;
4980 
4981 			/*
4982 			 * Supply a local source address such that inbound
4983 			 * load spreading happens.
4984 			 *
4985 			 * Determine the best source address on this ill for
4986 			 * the destination.
4987 			 *
4988 			 * 1) For broadcast, we should return a broadcast ire
4989 			 *    found above so that upper layers know that the
4990 			 *    destination address is a broadcast address.
4991 			 *
4992 			 * 2) If this is part of a group, select a better
4993 			 *    source address so that better inbound load
4994 			 *    balancing happens. Do the same if the ipif
4995 			 *    is DEPRECATED.
4996 			 *
4997 			 * 3) If the outgoing interface is part of a usesrc
4998 			 *    group, then try selecting a source address from
4999 			 *    the usesrc ILL.
5000 			 */
5001 			if ((dst_ire->ire_zoneid != zoneid &&
5002 			    dst_ire->ire_zoneid != ALL_ZONES) ||
5003 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
5004 			    ((dst_ill->ill_group != NULL) ||
5005 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
5006 			    (dst_ill->ill_usesrc_ifindex != 0)))) {
5007 				/*
5008 				 * If the destination is reachable via a
5009 				 * given gateway, the selected source address
5010 				 * should be in the same subnet as the gateway.
5011 				 * Otherwise, the destination is not reachable.
5012 				 *
5013 				 * If there are no interfaces on the same subnet
5014 				 * as the destination, ipif_select_source gives
5015 				 * first non-deprecated interface which might be
5016 				 * on a different subnet than the gateway.
5017 				 * This is not desirable. Hence pass the dst_ire
5018 				 * source address to ipif_select_source.
5019 				 * It is sure that the destination is reachable
5020 				 * with the dst_ire source address subnet.
5021 				 * So passing dst_ire source address to
5022 				 * ipif_select_source will make sure that the
5023 				 * selected source will be on the same subnet
5024 				 * as dst_ire source address.
5025 				 */
5026 				ipaddr_t saddr =
5027 				    dst_ire->ire_ipif->ipif_src_addr;
5028 				src_ipif = ipif_select_source(dst_ill,
5029 				    saddr, zoneid);
5030 				if (src_ipif != NULL) {
5031 					if (IS_VNI(src_ipif->ipif_ill)) {
5032 						/*
5033 						 * For VNI there is no
5034 						 * interface route
5035 						 */
5036 						src_addr =
5037 						    src_ipif->ipif_src_addr;
5038 					} else {
5039 						ipif_ire =
5040 						    ipif_to_ire(src_ipif);
5041 						if (ipif_ire != NULL) {
5042 							IRE_REFRELE(dst_ire);
5043 							dst_ire = ipif_ire;
5044 						}
5045 						src_addr =
5046 						    dst_ire->ire_src_addr;
5047 					}
5048 					ipif_refrele(src_ipif);
5049 				} else {
5050 					src_addr = dst_ire->ire_src_addr;
5051 				}
5052 			} else {
5053 				src_addr = dst_ire->ire_src_addr;
5054 			}
5055 		}
5056 	}
5057 
5058 	/*
5059 	 * We do ire_route_lookup() here (and not
5060 	 * interface lookup as we assert that
5061 	 * src_addr should only come from an
5062 	 * UP interface for hard binding.
5063 	 */
5064 	ASSERT(src_ire == NULL);
5065 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5066 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
5067 	/* src_ire must be a local|loopback */
5068 	if (!IRE_IS_LOCAL(src_ire)) {
5069 		if (ip_debug > 2) {
5070 			pr_addr_dbg("ip_bind_connected: bad connected "
5071 			    "src %s\n", AF_INET, &src_addr);
5072 		}
5073 		error = EADDRNOTAVAIL;
5074 		goto bad_addr;
5075 	}
5076 
5077 	/*
5078 	 * If the source address is a loopback address, the
5079 	 * destination had best be local or multicast.
5080 	 * The transports that can't handle multicast will reject
5081 	 * those addresses.
5082 	 */
5083 	if (src_ire->ire_type == IRE_LOOPBACK &&
5084 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5085 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
5086 		error = -1;
5087 		goto bad_addr;
5088 	}
5089 
5090 	/*
5091 	 * Allow setting new policies. For example, disconnects come
5092 	 * down as ipa_t bind. As we would have set conn_policy_cached
5093 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5094 	 * can change after the disconnect.
5095 	 */
5096 	connp->conn_policy_cached = B_FALSE;
5097 
5098 	/*
5099 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5100 	 * can handle their passed-in conn's.
5101 	 */
5102 
5103 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5104 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5105 	connp->conn_lport = lport;
5106 	connp->conn_fport = fport;
5107 	*src_addrp = src_addr;
5108 
5109 	ASSERT(!(ipsec_policy_set && ire_requested));
5110 	if (ire_requested) {
5111 		iulp_t *ulp_info = NULL;
5112 
5113 		/*
5114 		 * Note that sire will not be NULL if this is an off-link
5115 		 * connection and there is not cache for that dest yet.
5116 		 *
5117 		 * XXX Because of an existing bug, if there are multiple
5118 		 * default routes, the IRE returned now may not be the actual
5119 		 * default route used (default routes are chosen in a
5120 		 * round robin fashion).  So if the metrics for different
5121 		 * default routes are different, we may return the wrong
5122 		 * metrics.  This will not be a problem if the existing
5123 		 * bug is fixed.
5124 		 */
5125 		if (sire != NULL) {
5126 			ulp_info = &(sire->ire_uinfo);
5127 		}
5128 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info, ipst)) {
5129 			error = -1;
5130 			goto bad_addr;
5131 		}
5132 	} else if (ipsec_policy_set) {
5133 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
5134 			error = -1;
5135 			goto bad_addr;
5136 		}
5137 	}
5138 
5139 	/*
5140 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5141 	 * we'll cache that.  If we don't, we'll inherit global policy.
5142 	 *
5143 	 * We can't insert until the conn reflects the policy. Note that
5144 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5145 	 * connections where we don't have a policy. This is to prevent
5146 	 * global policy lookups in the inbound path.
5147 	 *
5148 	 * If we insert before we set conn_policy_cached,
5149 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5150 	 * because global policy cound be non-empty. We normally call
5151 	 * ipsec_check_policy() for conn_policy_cached connections only if
5152 	 * ipc_in_enforce_policy is set. But in this case,
5153 	 * conn_policy_cached can get set anytime since we made the
5154 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5155 	 * called, which will make the above assumption false.  Thus, we
5156 	 * need to insert after we set conn_policy_cached.
5157 	 */
5158 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5159 		goto bad_addr;
5160 
5161 	if (fanout_insert) {
5162 		/*
5163 		 * The addresses have been verified. Time to insert in
5164 		 * the correct fanout list.
5165 		 * We need to make sure that the conn_recv is set to a non-null
5166 		 * value before we insert into the classifier table to avoid a
5167 		 * race with an incoming packet which does an ipcl_classify().
5168 		 */
5169 		if (protocol == IPPROTO_TCP)
5170 			connp->conn_recv = tcp_input;
5171 		error = ipcl_conn_insert(connp, protocol, src_addr,
5172 		    dst_addr, connp->conn_ports);
5173 	}
5174 
5175 	if (error == 0) {
5176 		connp->conn_fully_bound = B_TRUE;
5177 		/*
5178 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5179 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5180 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5181 		 * ip_xxinfo_return(), which performs further checks
5182 		 * against them and upon success, returns the LSO/MDT info
5183 		 * mblk which we will attach to the bind acknowledgment.
5184 		 */
5185 		if (lso_dst_ire != NULL) {
5186 			mblk_t *lsoinfo_mp;
5187 
5188 			ASSERT(ill->ill_lso_capab != NULL);
5189 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5190 			    ill->ill_name, ill->ill_lso_capab)) != NULL)
5191 				linkb(mp, lsoinfo_mp);
5192 		} else if (md_dst_ire != NULL) {
5193 			mblk_t *mdinfo_mp;
5194 
5195 			ASSERT(ill->ill_mdt_capab != NULL);
5196 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5197 			    ill->ill_name, ill->ill_mdt_capab)) != NULL)
5198 				linkb(mp, mdinfo_mp);
5199 		}
5200 	}
5201 bad_addr:
5202 	if (ipsec_policy_set) {
5203 		ASSERT(policy_mp == mp->b_cont);
5204 		ASSERT(policy_mp != NULL);
5205 		freeb(policy_mp);
5206 		/*
5207 		 * As of now assume that nothing else accompanies
5208 		 * IPSEC_POLICY_SET.
5209 		 */
5210 		mp->b_cont = NULL;
5211 	}
5212 	if (src_ire != NULL)
5213 		IRE_REFRELE(src_ire);
5214 	if (dst_ire != NULL)
5215 		IRE_REFRELE(dst_ire);
5216 	if (sire != NULL)
5217 		IRE_REFRELE(sire);
5218 	if (md_dst_ire != NULL)
5219 		IRE_REFRELE(md_dst_ire);
5220 	if (lso_dst_ire != NULL)
5221 		IRE_REFRELE(lso_dst_ire);
5222 	return (error);
5223 }
5224 
5225 /*
5226  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
5227  * Prefers dst_ire over src_ire.
5228  */
5229 static boolean_t
5230 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info, ip_stack_t *ipst)
5231 {
5232 	mblk_t	*mp1;
5233 	ire_t *ret_ire = NULL;
5234 
5235 	mp1 = mp->b_cont;
5236 	ASSERT(mp1 != NULL);
5237 
5238 	if (ire != NULL) {
5239 		/*
5240 		 * mp1 initialized above to IRE_DB_REQ_TYPE
5241 		 * appended mblk. Its <upper protocol>'s
5242 		 * job to make sure there is room.
5243 		 */
5244 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
5245 			return (0);
5246 
5247 		mp1->b_datap->db_type = IRE_DB_TYPE;
5248 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
5249 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
5250 		ret_ire = (ire_t *)mp1->b_rptr;
5251 		/*
5252 		 * Pass the latest setting of the ip_path_mtu_discovery and
5253 		 * copy the ulp info if any.
5254 		 */
5255 		ret_ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ?
5256 		    IPH_DF : 0;
5257 		if (ulp_info != NULL) {
5258 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5259 			    sizeof (iulp_t));
5260 		}
5261 		ret_ire->ire_mp = mp1;
5262 	} else {
5263 		/*
5264 		 * No IRE was found. Remove IRE mblk.
5265 		 */
5266 		mp->b_cont = mp1->b_cont;
5267 		freeb(mp1);
5268 	}
5269 
5270 	return (1);
5271 }
5272 
5273 /*
5274  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5275  * the final piece where we don't.  Return a pointer to the first mblk in the
5276  * result, and update the pointer to the next mblk to chew on.  If anything
5277  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5278  * NULL pointer.
5279  */
5280 mblk_t *
5281 ip_carve_mp(mblk_t **mpp, ssize_t len)
5282 {
5283 	mblk_t	*mp0;
5284 	mblk_t	*mp1;
5285 	mblk_t	*mp2;
5286 
5287 	if (!len || !mpp || !(mp0 = *mpp))
5288 		return (NULL);
5289 	/* If we aren't going to consume the first mblk, we need a dup. */
5290 	if (mp0->b_wptr - mp0->b_rptr > len) {
5291 		mp1 = dupb(mp0);
5292 		if (mp1) {
5293 			/* Partition the data between the two mblks. */
5294 			mp1->b_wptr = mp1->b_rptr + len;
5295 			mp0->b_rptr = mp1->b_wptr;
5296 			/*
5297 			 * after adjustments if mblk not consumed is now
5298 			 * unaligned, try to align it. If this fails free
5299 			 * all messages and let upper layer recover.
5300 			 */
5301 			if (!OK_32PTR(mp0->b_rptr)) {
5302 				if (!pullupmsg(mp0, -1)) {
5303 					freemsg(mp0);
5304 					freemsg(mp1);
5305 					*mpp = NULL;
5306 					return (NULL);
5307 				}
5308 			}
5309 		}
5310 		return (mp1);
5311 	}
5312 	/* Eat through as many mblks as we need to get len bytes. */
5313 	len -= mp0->b_wptr - mp0->b_rptr;
5314 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5315 		if (mp2->b_wptr - mp2->b_rptr > len) {
5316 			/*
5317 			 * We won't consume the entire last mblk.  Like
5318 			 * above, dup and partition it.
5319 			 */
5320 			mp1->b_cont = dupb(mp2);
5321 			mp1 = mp1->b_cont;
5322 			if (!mp1) {
5323 				/*
5324 				 * Trouble.  Rather than go to a lot of
5325 				 * trouble to clean up, we free the messages.
5326 				 * This won't be any worse than losing it on
5327 				 * the wire.
5328 				 */
5329 				freemsg(mp0);
5330 				freemsg(mp2);
5331 				*mpp = NULL;
5332 				return (NULL);
5333 			}
5334 			mp1->b_wptr = mp1->b_rptr + len;
5335 			mp2->b_rptr = mp1->b_wptr;
5336 			/*
5337 			 * after adjustments if mblk not consumed is now
5338 			 * unaligned, try to align it. If this fails free
5339 			 * all messages and let upper layer recover.
5340 			 */
5341 			if (!OK_32PTR(mp2->b_rptr)) {
5342 				if (!pullupmsg(mp2, -1)) {
5343 					freemsg(mp0);
5344 					freemsg(mp2);
5345 					*mpp = NULL;
5346 					return (NULL);
5347 				}
5348 			}
5349 			*mpp = mp2;
5350 			return (mp0);
5351 		}
5352 		/* Decrement len by the amount we just got. */
5353 		len -= mp2->b_wptr - mp2->b_rptr;
5354 	}
5355 	/*
5356 	 * len should be reduced to zero now.  If not our caller has
5357 	 * screwed up.
5358 	 */
5359 	if (len) {
5360 		/* Shouldn't happen! */
5361 		freemsg(mp0);
5362 		*mpp = NULL;
5363 		return (NULL);
5364 	}
5365 	/*
5366 	 * We consumed up to exactly the end of an mblk.  Detach the part
5367 	 * we are returning from the rest of the chain.
5368 	 */
5369 	mp1->b_cont = NULL;
5370 	*mpp = mp2;
5371 	return (mp0);
5372 }
5373 
5374 /* The ill stream is being unplumbed. Called from ip_close */
5375 int
5376 ip_modclose(ill_t *ill)
5377 {
5378 	boolean_t success;
5379 	ipsq_t	*ipsq;
5380 	ipif_t	*ipif;
5381 	queue_t	*q = ill->ill_rq;
5382 	ip_stack_t	*ipst = ill->ill_ipst;
5383 	clock_t timeout;
5384 
5385 	/*
5386 	 * Wait for the ACKs of all deferred control messages to be processed.
5387 	 * In particular, we wait for a potential capability reset initiated
5388 	 * in ip_sioctl_plink() to complete before proceeding.
5389 	 *
5390 	 * Note: we wait for at most ip_modclose_ackwait_ms (by default 3000 ms)
5391 	 * in case the driver never replies.
5392 	 */
5393 	timeout = lbolt + MSEC_TO_TICK(ip_modclose_ackwait_ms);
5394 	mutex_enter(&ill->ill_lock);
5395 	while (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
5396 		if (cv_timedwait(&ill->ill_cv, &ill->ill_lock, timeout) < 0) {
5397 			/* Timeout */
5398 			break;
5399 		}
5400 	}
5401 	mutex_exit(&ill->ill_lock);
5402 
5403 	/*
5404 	 * Forcibly enter the ipsq after some delay. This is to take
5405 	 * care of the case when some ioctl does not complete because
5406 	 * we sent a control message to the driver and it did not
5407 	 * send us a reply. We want to be able to at least unplumb
5408 	 * and replumb rather than force the user to reboot the system.
5409 	 */
5410 	success = ipsq_enter(ill, B_FALSE);
5411 
5412 	/*
5413 	 * Open/close/push/pop is guaranteed to be single threaded
5414 	 * per stream by STREAMS. FS guarantees that all references
5415 	 * from top are gone before close is called. So there can't
5416 	 * be another close thread that has set CONDEMNED on this ill.
5417 	 * and cause ipsq_enter to return failure.
5418 	 */
5419 	ASSERT(success);
5420 	ipsq = ill->ill_phyint->phyint_ipsq;
5421 
5422 	/*
5423 	 * Mark it condemned. No new reference will be made to this ill.
5424 	 * Lookup functions will return an error. Threads that try to
5425 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5426 	 * that the refcnt will drop down to zero.
5427 	 */
5428 	mutex_enter(&ill->ill_lock);
5429 	ill->ill_state_flags |= ILL_CONDEMNED;
5430 	for (ipif = ill->ill_ipif; ipif != NULL;
5431 	    ipif = ipif->ipif_next) {
5432 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5433 	}
5434 	/*
5435 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5436 	 * returns  error if ILL_CONDEMNED is set
5437 	 */
5438 	cv_broadcast(&ill->ill_cv);
5439 	mutex_exit(&ill->ill_lock);
5440 
5441 	/*
5442 	 * Send all the deferred DLPI messages downstream which came in
5443 	 * during the small window right before ipsq_enter(). We do this
5444 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5445 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5446 	 */
5447 	ill_dlpi_send_deferred(ill);
5448 
5449 	/*
5450 	 * Shut down fragmentation reassembly.
5451 	 * ill_frag_timer won't start a timer again.
5452 	 * Now cancel any existing timer
5453 	 */
5454 	(void) untimeout(ill->ill_frag_timer_id);
5455 	(void) ill_frag_timeout(ill, 0);
5456 
5457 	/*
5458 	 * If MOVE was in progress, clear the
5459 	 * move_in_progress fields also.
5460 	 */
5461 	if (ill->ill_move_in_progress) {
5462 		ILL_CLEAR_MOVE(ill);
5463 	}
5464 
5465 	/*
5466 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5467 	 * this ill. Then wait for the refcnts to drop to zero.
5468 	 * ill_is_quiescent checks whether the ill is really quiescent.
5469 	 * Then make sure that threads that are waiting to enter the
5470 	 * ipsq have seen the error returned by ipsq_enter and have
5471 	 * gone away. Then we call ill_delete_tail which does the
5472 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
5473 	 */
5474 	ill_delete(ill);
5475 	mutex_enter(&ill->ill_lock);
5476 	while (!ill_is_quiescent(ill))
5477 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5478 	while (ill->ill_waiters)
5479 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5480 
5481 	mutex_exit(&ill->ill_lock);
5482 
5483 	/*
5484 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
5485 	 * it held until the end of the function since the cleanup
5486 	 * below needs to be able to use the ip_stack_t.
5487 	 */
5488 	netstack_hold(ipst->ips_netstack);
5489 
5490 	/* qprocsoff is called in ill_delete_tail */
5491 	ill_delete_tail(ill);
5492 	ASSERT(ill->ill_ipst == NULL);
5493 
5494 	/*
5495 	 * Walk through all upper (conn) streams and qenable
5496 	 * those that have queued data.
5497 	 * close synchronization needs this to
5498 	 * be done to ensure that all upper layers blocked
5499 	 * due to flow control to the closing device
5500 	 * get unblocked.
5501 	 */
5502 	ip1dbg(("ip_wsrv: walking\n"));
5503 	conn_walk_drain(ipst);
5504 
5505 	mutex_enter(&ipst->ips_ip_mi_lock);
5506 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
5507 	mutex_exit(&ipst->ips_ip_mi_lock);
5508 
5509 	/*
5510 	 * credp could be null if the open didn't succeed and ip_modopen
5511 	 * itself calls ip_close.
5512 	 */
5513 	if (ill->ill_credp != NULL)
5514 		crfree(ill->ill_credp);
5515 
5516 	mutex_enter(&ill->ill_lock);
5517 	ill_nic_info_dispatch(ill);
5518 	mutex_exit(&ill->ill_lock);
5519 
5520 	/*
5521 	 * Now we are done with the module close pieces that
5522 	 * need the netstack_t.
5523 	 */
5524 	netstack_rele(ipst->ips_netstack);
5525 
5526 	mi_close_free((IDP)ill);
5527 	q->q_ptr = WR(q)->q_ptr = NULL;
5528 
5529 	ipsq_exit(ipsq, B_TRUE, B_TRUE);
5530 
5531 	return (0);
5532 }
5533 
5534 /*
5535  * This is called as part of close() for both IP and UDP
5536  * in order to quiesce the conn.
5537  */
5538 void
5539 ip_quiesce_conn(conn_t *connp)
5540 {
5541 	boolean_t	drain_cleanup_reqd = B_FALSE;
5542 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5543 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5544 	ip_stack_t	*ipst;
5545 
5546 	ASSERT(!IPCL_IS_TCP(connp));
5547 	ipst = connp->conn_netstack->netstack_ip;
5548 
5549 	/*
5550 	 * Mark the conn as closing, and this conn must not be
5551 	 * inserted in future into any list. Eg. conn_drain_insert(),
5552 	 * won't insert this conn into the conn_drain_list.
5553 	 * Similarly ill_pending_mp_add() will not add any mp to
5554 	 * the pending mp list, after this conn has started closing.
5555 	 *
5556 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5557 	 * cannot get set henceforth.
5558 	 */
5559 	mutex_enter(&connp->conn_lock);
5560 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5561 	connp->conn_state_flags |= CONN_CLOSING;
5562 	if (connp->conn_idl != NULL)
5563 		drain_cleanup_reqd = B_TRUE;
5564 	if (connp->conn_oper_pending_ill != NULL)
5565 		conn_ioctl_cleanup_reqd = B_TRUE;
5566 	if (connp->conn_ilg_inuse != 0)
5567 		ilg_cleanup_reqd = B_TRUE;
5568 	mutex_exit(&connp->conn_lock);
5569 
5570 	if (IPCL_IS_UDP(connp))
5571 		udp_quiesce_conn(connp);
5572 
5573 	if (conn_ioctl_cleanup_reqd)
5574 		conn_ioctl_cleanup(connp);
5575 
5576 	if (is_system_labeled() && connp->conn_anon_port) {
5577 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5578 		    connp->conn_mlp_type, connp->conn_ulp,
5579 		    ntohs(connp->conn_lport), B_FALSE);
5580 		connp->conn_anon_port = 0;
5581 	}
5582 	connp->conn_mlp_type = mlptSingle;
5583 
5584 	/*
5585 	 * Remove this conn from any fanout list it is on.
5586 	 * and then wait for any threads currently operating
5587 	 * on this endpoint to finish
5588 	 */
5589 	ipcl_hash_remove(connp);
5590 
5591 	/*
5592 	 * Remove this conn from the drain list, and do
5593 	 * any other cleanup that may be required.
5594 	 * (Only non-tcp streams may have a non-null conn_idl.
5595 	 * TCP streams are never flow controlled, and
5596 	 * conn_idl will be null)
5597 	 */
5598 	if (drain_cleanup_reqd)
5599 		conn_drain_tail(connp, B_TRUE);
5600 
5601 	if (connp->conn_rq == ipst->ips_ip_g_mrouter ||
5602 	    connp->conn_wq == ipst->ips_ip_g_mrouter)
5603 		(void) ip_mrouter_done(NULL, ipst);
5604 
5605 	if (ilg_cleanup_reqd)
5606 		ilg_delete_all(connp);
5607 
5608 	conn_delete_ire(connp, NULL);
5609 
5610 	/*
5611 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5612 	 * callers from write side can't be there now because close
5613 	 * is in progress. The only other caller is ipcl_walk
5614 	 * which checks for the condemned flag.
5615 	 */
5616 	mutex_enter(&connp->conn_lock);
5617 	connp->conn_state_flags |= CONN_CONDEMNED;
5618 	while (connp->conn_ref != 1)
5619 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5620 	connp->conn_state_flags |= CONN_QUIESCED;
5621 	mutex_exit(&connp->conn_lock);
5622 }
5623 
5624 /* ARGSUSED */
5625 int
5626 ip_close(queue_t *q, int flags)
5627 {
5628 	conn_t		*connp;
5629 
5630 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5631 
5632 	/*
5633 	 * Call the appropriate delete routine depending on whether this is
5634 	 * a module or device.
5635 	 */
5636 	if (WR(q)->q_next != NULL) {
5637 		/* This is a module close */
5638 		return (ip_modclose((ill_t *)q->q_ptr));
5639 	}
5640 
5641 	connp = q->q_ptr;
5642 	ip_quiesce_conn(connp);
5643 
5644 	qprocsoff(q);
5645 
5646 	/*
5647 	 * Now we are truly single threaded on this stream, and can
5648 	 * delete the things hanging off the connp, and finally the connp.
5649 	 * We removed this connp from the fanout list, it cannot be
5650 	 * accessed thru the fanouts, and we already waited for the
5651 	 * conn_ref to drop to 0. We are already in close, so
5652 	 * there cannot be any other thread from the top. qprocsoff
5653 	 * has completed, and service has completed or won't run in
5654 	 * future.
5655 	 */
5656 	ASSERT(connp->conn_ref == 1);
5657 
5658 	/*
5659 	 * A conn which was previously marked as IPCL_UDP cannot
5660 	 * retain the flag because it would have been cleared by
5661 	 * udp_close().
5662 	 */
5663 	ASSERT(!IPCL_IS_UDP(connp));
5664 
5665 	if (connp->conn_latch != NULL) {
5666 		IPLATCH_REFRELE(connp->conn_latch, connp->conn_netstack);
5667 		connp->conn_latch = NULL;
5668 	}
5669 	if (connp->conn_policy != NULL) {
5670 		IPPH_REFRELE(connp->conn_policy, connp->conn_netstack);
5671 		connp->conn_policy = NULL;
5672 	}
5673 	if (connp->conn_ipsec_opt_mp != NULL) {
5674 		freemsg(connp->conn_ipsec_opt_mp);
5675 		connp->conn_ipsec_opt_mp = NULL;
5676 	}
5677 
5678 	inet_minor_free(ip_minor_arena, connp->conn_dev);
5679 
5680 	connp->conn_ref--;
5681 	ipcl_conn_destroy(connp);
5682 
5683 	q->q_ptr = WR(q)->q_ptr = NULL;
5684 	return (0);
5685 }
5686 
5687 int
5688 ip_snmpmod_close(queue_t *q)
5689 {
5690 	conn_t *connp = Q_TO_CONN(q);
5691 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5692 
5693 	qprocsoff(q);
5694 
5695 	if (connp->conn_flags & IPCL_UDPMOD)
5696 		udp_close_free(connp);
5697 
5698 	if (connp->conn_cred != NULL) {
5699 		crfree(connp->conn_cred);
5700 		connp->conn_cred = NULL;
5701 	}
5702 	CONN_DEC_REF(connp);
5703 	q->q_ptr = WR(q)->q_ptr = NULL;
5704 	return (0);
5705 }
5706 
5707 /*
5708  * Write side put procedure for TCP module or UDP module instance.  TCP/UDP
5709  * as a module is only used for MIB browsers that push TCP/UDP over IP or ARP.
5710  * The only supported primitives are T_SVR4_OPTMGMT_REQ and T_OPTMGMT_REQ.
5711  * M_FLUSH messages and ioctls are only passed downstream; we don't flush our
5712  * queues as we never enqueue messages there and we don't handle any ioctls.
5713  * Everything else is freed.
5714  */
5715 void
5716 ip_snmpmod_wput(queue_t *q, mblk_t *mp)
5717 {
5718 	conn_t	*connp = q->q_ptr;
5719 	pfi_t	setfn;
5720 	pfi_t	getfn;
5721 
5722 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5723 
5724 	switch (DB_TYPE(mp)) {
5725 	case M_PROTO:
5726 	case M_PCPROTO:
5727 		if ((MBLKL(mp) >= sizeof (t_scalar_t)) &&
5728 		    ((((union T_primitives *)mp->b_rptr)->type ==
5729 		    T_SVR4_OPTMGMT_REQ) ||
5730 		    (((union T_primitives *)mp->b_rptr)->type ==
5731 		    T_OPTMGMT_REQ))) {
5732 			/*
5733 			 * This is the only TPI primitive supported. Its
5734 			 * handling does not require tcp_t, but it does require
5735 			 * conn_t to check permissions.
5736 			 */
5737 			cred_t	*cr = DB_CREDDEF(mp, connp->conn_cred);
5738 
5739 			if (connp->conn_flags & IPCL_TCPMOD) {
5740 				setfn = tcp_snmp_set;
5741 				getfn = tcp_snmp_get;
5742 			} else {
5743 				setfn = udp_snmp_set;
5744 				getfn = udp_snmp_get;
5745 			}
5746 			if (!snmpcom_req(q, mp, setfn, getfn, cr)) {
5747 				freemsg(mp);
5748 				return;
5749 			}
5750 		} else if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, ENOTSUP))
5751 		    != NULL)
5752 			qreply(q, mp);
5753 		break;
5754 	case M_FLUSH:
5755 	case M_IOCTL:
5756 		putnext(q, mp);
5757 		break;
5758 	default:
5759 		freemsg(mp);
5760 		break;
5761 	}
5762 }
5763 
5764 /* Return the IP checksum for the IP header at "iph". */
5765 uint16_t
5766 ip_csum_hdr(ipha_t *ipha)
5767 {
5768 	uint16_t	*uph;
5769 	uint32_t	sum;
5770 	int		opt_len;
5771 
5772 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
5773 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
5774 	uph = (uint16_t *)ipha;
5775 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
5776 	    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
5777 	if (opt_len > 0) {
5778 		do {
5779 			sum += uph[10];
5780 			sum += uph[11];
5781 			uph += 2;
5782 		} while (--opt_len);
5783 	}
5784 	sum = (sum & 0xFFFF) + (sum >> 16);
5785 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
5786 	if (sum == 0xffff)
5787 		sum = 0;
5788 	return ((uint16_t)sum);
5789 }
5790 
5791 /*
5792  * Called when the module is about to be unloaded
5793  */
5794 void
5795 ip_ddi_destroy(void)
5796 {
5797 	tnet_fini();
5798 
5799 	sctp_ddi_g_destroy();
5800 	tcp_ddi_g_destroy();
5801 	ipsec_policy_g_destroy();
5802 	ipcl_g_destroy();
5803 	ip_net_g_destroy();
5804 	ip_ire_g_fini();
5805 	inet_minor_destroy(ip_minor_arena);
5806 
5807 	netstack_unregister(NS_IP);
5808 }
5809 
5810 /*
5811  * First step in cleanup.
5812  */
5813 /* ARGSUSED */
5814 static void
5815 ip_stack_shutdown(netstackid_t stackid, void *arg)
5816 {
5817 	ip_stack_t *ipst = (ip_stack_t *)arg;
5818 
5819 #ifdef NS_DEBUG
5820 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
5821 #endif
5822 
5823 	/* Get rid of loopback interfaces and their IREs */
5824 	ip_loopback_cleanup(ipst);
5825 }
5826 
5827 /*
5828  * Free the IP stack instance.
5829  */
5830 static void
5831 ip_stack_fini(netstackid_t stackid, void *arg)
5832 {
5833 	ip_stack_t *ipst = (ip_stack_t *)arg;
5834 	int ret;
5835 
5836 #ifdef NS_DEBUG
5837 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5838 #endif
5839 	ipv4_hook_destroy(ipst);
5840 	ipv6_hook_destroy(ipst);
5841 	ip_net_destroy(ipst);
5842 
5843 	rw_destroy(&ipst->ips_srcid_lock);
5844 
5845 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5846 	ipst->ips_ip_mibkp = NULL;
5847 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5848 	ipst->ips_icmp_mibkp = NULL;
5849 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5850 	ipst->ips_ip_kstat = NULL;
5851 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5852 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5853 	ipst->ips_ip6_kstat = NULL;
5854 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5855 
5856 	nd_free(&ipst->ips_ip_g_nd);
5857 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5858 	ipst->ips_param_arr = NULL;
5859 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5860 	ipst->ips_ndp_arr = NULL;
5861 
5862 	ip_mrouter_stack_destroy(ipst);
5863 
5864 	mutex_destroy(&ipst->ips_ip_mi_lock);
5865 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5866 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5867 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5868 
5869 	ret = untimeout(ipst->ips_igmp_timeout_id);
5870 	if (ret == -1) {
5871 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5872 	} else {
5873 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5874 		ipst->ips_igmp_timeout_id = 0;
5875 	}
5876 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5877 	if (ret == -1) {
5878 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5879 	} else {
5880 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5881 		ipst->ips_igmp_slowtimeout_id = 0;
5882 	}
5883 	ret = untimeout(ipst->ips_mld_timeout_id);
5884 	if (ret == -1) {
5885 		ASSERT(ipst->ips_mld_timeout_id == 0);
5886 	} else {
5887 		ASSERT(ipst->ips_mld_timeout_id != 0);
5888 		ipst->ips_mld_timeout_id = 0;
5889 	}
5890 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5891 	if (ret == -1) {
5892 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5893 	} else {
5894 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5895 		ipst->ips_mld_slowtimeout_id = 0;
5896 	}
5897 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5898 	if (ret == -1) {
5899 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5900 	} else {
5901 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5902 		ipst->ips_ip_ire_expire_id = 0;
5903 	}
5904 
5905 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5906 	mutex_destroy(&ipst->ips_mld_timer_lock);
5907 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5908 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5909 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5910 	rw_destroy(&ipst->ips_ill_g_lock);
5911 
5912 	ip_ire_fini(ipst);
5913 	ip6_asp_free(ipst);
5914 	conn_drain_fini(ipst);
5915 	ipcl_destroy(ipst);
5916 
5917 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5918 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5919 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5920 	ipst->ips_ndp4 = NULL;
5921 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5922 	ipst->ips_ndp6 = NULL;
5923 
5924 	if (ipst->ips_loopback_ksp != NULL) {
5925 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5926 		ipst->ips_loopback_ksp = NULL;
5927 	}
5928 
5929 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5930 	ipst->ips_phyint_g_list = NULL;
5931 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5932 	ipst->ips_ill_g_heads = NULL;
5933 
5934 	kmem_free(ipst, sizeof (*ipst));
5935 }
5936 
5937 /*
5938  * Called when the IP kernel module is loaded into the kernel
5939  */
5940 void
5941 ip_ddi_init(void)
5942 {
5943 	TCP6_MAJ = ddi_name_to_major(TCP6);
5944 	TCP_MAJ	= ddi_name_to_major(TCP);
5945 	SCTP_MAJ = ddi_name_to_major(SCTP);
5946 	SCTP6_MAJ = ddi_name_to_major(SCTP6);
5947 
5948 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
5949 
5950 	/*
5951 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5952 	 * initial devices: ip, ip6, tcp, tcp6.
5953 	 */
5954 	if ((ip_minor_arena = inet_minor_create("ip_minor_arena",
5955 	    INET_MIN_DEV + 2, KM_SLEEP)) == NULL) {
5956 		cmn_err(CE_PANIC,
5957 		    "ip_ddi_init: ip_minor_arena creation failed\n");
5958 	}
5959 
5960 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5961 
5962 	ipcl_g_init();
5963 	ip_ire_g_init();
5964 	ip_net_g_init();
5965 
5966 #ifdef ILL_DEBUG
5967 	/* Default cleanup function */
5968 	ip_cleanup_func = ip_thread_exit;
5969 #endif
5970 
5971 	/*
5972 	 * We want to be informed each time a stack is created or
5973 	 * destroyed in the kernel, so we can maintain the
5974 	 * set of udp_stack_t's.
5975 	 */
5976 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
5977 	    ip_stack_fini);
5978 
5979 	ipsec_policy_g_init();
5980 	tcp_ddi_g_init();
5981 	sctp_ddi_g_init();
5982 
5983 	tnet_init();
5984 }
5985 
5986 /*
5987  * Initialize the IP stack instance.
5988  */
5989 static void *
5990 ip_stack_init(netstackid_t stackid, netstack_t *ns)
5991 {
5992 	ip_stack_t	*ipst;
5993 	ipparam_t	*pa;
5994 	ipndp_t		*na;
5995 
5996 #ifdef NS_DEBUG
5997 	printf("ip_stack_init(stack %d)\n", stackid);
5998 #endif
5999 
6000 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
6001 	ipst->ips_netstack = ns;
6002 
6003 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
6004 	    KM_SLEEP);
6005 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
6006 	    KM_SLEEP);
6007 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
6008 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
6009 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
6010 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
6011 
6012 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
6013 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
6014 	ipst->ips_igmp_deferred_next = INFINITY;
6015 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
6016 	ipst->ips_mld_deferred_next = INFINITY;
6017 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
6018 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
6019 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
6020 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
6021 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
6022 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
6023 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
6024 
6025 	ipcl_init(ipst);
6026 	ip_ire_init(ipst);
6027 	ip6_asp_init(ipst);
6028 	ipif_init(ipst);
6029 	conn_drain_init(ipst);
6030 	ip_mrouter_stack_init(ipst);
6031 
6032 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
6033 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
6034 
6035 	ipst->ips_ip_multirt_log_interval = 1000;
6036 
6037 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
6038 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
6039 	ipst->ips_ill_index = 1;
6040 
6041 	ipst->ips_saved_ip_g_forward = -1;
6042 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
6043 
6044 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
6045 	ipst->ips_param_arr = pa;
6046 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
6047 
6048 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
6049 	ipst->ips_ndp_arr = na;
6050 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
6051 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
6052 	    (caddr_t)&ipst->ips_ip_g_forward;
6053 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
6054 	    (caddr_t)&ipst->ips_ipv6_forward;
6055 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
6056 	    "ip_cgtp_filter") == 0);
6057 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
6058 	    (caddr_t)&ip_cgtp_filter;
6059 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_name,
6060 	    "ipmp_hook_emulation") == 0);
6061 	ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_data =
6062 	    (caddr_t)&ipst->ips_ipmp_hook_emulation;
6063 
6064 	(void) ip_param_register(&ipst->ips_ip_g_nd,
6065 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
6066 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
6067 
6068 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
6069 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
6070 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
6071 	ipst->ips_ip6_kstat =
6072 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
6073 
6074 	ipst->ips_ipmp_enable_failback = B_TRUE;
6075 
6076 	ipst->ips_ip_src_id = 1;
6077 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
6078 
6079 	ip_net_init(ipst, ns);
6080 	ipv4_hook_init(ipst);
6081 	ipv6_hook_init(ipst);
6082 
6083 	return (ipst);
6084 }
6085 
6086 /*
6087  * Allocate and initialize a DLPI template of the specified length.  (May be
6088  * called as writer.)
6089  */
6090 mblk_t *
6091 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
6092 {
6093 	mblk_t	*mp;
6094 
6095 	mp = allocb(len, BPRI_MED);
6096 	if (!mp)
6097 		return (NULL);
6098 
6099 	/*
6100 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
6101 	 * of which we don't seem to use) are sent with M_PCPROTO, and
6102 	 * that other DLPI are M_PROTO.
6103 	 */
6104 	if (prim == DL_INFO_REQ) {
6105 		mp->b_datap->db_type = M_PCPROTO;
6106 	} else {
6107 		mp->b_datap->db_type = M_PROTO;
6108 	}
6109 
6110 	mp->b_wptr = mp->b_rptr + len;
6111 	bzero(mp->b_rptr, len);
6112 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6113 	return (mp);
6114 }
6115 
6116 const char *
6117 dlpi_prim_str(int prim)
6118 {
6119 	switch (prim) {
6120 	case DL_INFO_REQ:	return ("DL_INFO_REQ");
6121 	case DL_INFO_ACK:	return ("DL_INFO_ACK");
6122 	case DL_ATTACH_REQ:	return ("DL_ATTACH_REQ");
6123 	case DL_DETACH_REQ:	return ("DL_DETACH_REQ");
6124 	case DL_BIND_REQ:	return ("DL_BIND_REQ");
6125 	case DL_BIND_ACK:	return ("DL_BIND_ACK");
6126 	case DL_UNBIND_REQ:	return ("DL_UNBIND_REQ");
6127 	case DL_OK_ACK:		return ("DL_OK_ACK");
6128 	case DL_ERROR_ACK:	return ("DL_ERROR_ACK");
6129 	case DL_ENABMULTI_REQ:	return ("DL_ENABMULTI_REQ");
6130 	case DL_DISABMULTI_REQ:	return ("DL_DISABMULTI_REQ");
6131 	case DL_PROMISCON_REQ:	return ("DL_PROMISCON_REQ");
6132 	case DL_PROMISCOFF_REQ:	return ("DL_PROMISCOFF_REQ");
6133 	case DL_UNITDATA_REQ:	return ("DL_UNITDATA_REQ");
6134 	case DL_UNITDATA_IND:	return ("DL_UNITDATA_IND");
6135 	case DL_UDERROR_IND:	return ("DL_UDERROR_IND");
6136 	case DL_PHYS_ADDR_REQ:	return ("DL_PHYS_ADDR_REQ");
6137 	case DL_PHYS_ADDR_ACK:	return ("DL_PHYS_ADDR_ACK");
6138 	case DL_SET_PHYS_ADDR_REQ:	return ("DL_SET_PHYS_ADDR_REQ");
6139 	case DL_NOTIFY_REQ:	return ("DL_NOTIFY_REQ");
6140 	case DL_NOTIFY_ACK:	return ("DL_NOTIFY_ACK");
6141 	case DL_NOTIFY_IND:	return ("DL_NOTIFY_IND");
6142 	case DL_CAPABILITY_REQ:	return ("DL_CAPABILITY_REQ");
6143 	case DL_CAPABILITY_ACK:	return ("DL_CAPABILITY_ACK");
6144 	case DL_CONTROL_REQ:	return ("DL_CONTROL_REQ");
6145 	case DL_CONTROL_ACK:	return ("DL_CONTROL_ACK");
6146 	default:		return ("<unknown primitive>");
6147 	}
6148 }
6149 
6150 const char *
6151 dlpi_err_str(int err)
6152 {
6153 	switch (err) {
6154 	case DL_ACCESS:		return ("DL_ACCESS");
6155 	case DL_BADADDR:	return ("DL_BADADDR");
6156 	case DL_BADCORR:	return ("DL_BADCORR");
6157 	case DL_BADDATA:	return ("DL_BADDATA");
6158 	case DL_BADPPA:		return ("DL_BADPPA");
6159 	case DL_BADPRIM:	return ("DL_BADPRIM");
6160 	case DL_BADQOSPARAM:	return ("DL_BADQOSPARAM");
6161 	case DL_BADQOSTYPE:	return ("DL_BADQOSTYPE");
6162 	case DL_BADSAP:		return ("DL_BADSAP");
6163 	case DL_BADTOKEN:	return ("DL_BADTOKEN");
6164 	case DL_BOUND:		return ("DL_BOUND");
6165 	case DL_INITFAILED:	return ("DL_INITFAILED");
6166 	case DL_NOADDR:		return ("DL_NOADDR");
6167 	case DL_NOTINIT:	return ("DL_NOTINIT");
6168 	case DL_OUTSTATE:	return ("DL_OUTSTATE");
6169 	case DL_SYSERR:		return ("DL_SYSERR");
6170 	case DL_UNSUPPORTED:	return ("DL_UNSUPPORTED");
6171 	case DL_UNDELIVERABLE:	return ("DL_UNDELIVERABLE");
6172 	case DL_NOTSUPPORTED :	return ("DL_NOTSUPPORTED ");
6173 	case DL_TOOMANY:	return ("DL_TOOMANY");
6174 	case DL_NOTENAB:	return ("DL_NOTENAB");
6175 	case DL_BUSY:		return ("DL_BUSY");
6176 	case DL_NOAUTO:		return ("DL_NOAUTO");
6177 	case DL_NOXIDAUTO:	return ("DL_NOXIDAUTO");
6178 	case DL_NOTESTAUTO:	return ("DL_NOTESTAUTO");
6179 	case DL_XIDAUTO:	return ("DL_XIDAUTO");
6180 	case DL_TESTAUTO:	return ("DL_TESTAUTO");
6181 	case DL_PENDING:	return ("DL_PENDING");
6182 	default:		return ("<unknown error>");
6183 	}
6184 }
6185 
6186 /*
6187  * Debug formatting routine.  Returns a character string representation of the
6188  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6189  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6190  *
6191  * Once the ndd table-printing interfaces are removed, this can be changed to
6192  * standard dotted-decimal form.
6193  */
6194 char *
6195 ip_dot_addr(ipaddr_t addr, char *buf)
6196 {
6197 	uint8_t *ap = (uint8_t *)&addr;
6198 
6199 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6200 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6201 	return (buf);
6202 }
6203 
6204 /*
6205  * Write the given MAC address as a printable string in the usual colon-
6206  * separated format.
6207  */
6208 const char *
6209 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6210 {
6211 	char *bp;
6212 
6213 	if (alen == 0 || buflen < 4)
6214 		return ("?");
6215 	bp = buf;
6216 	for (;;) {
6217 		/*
6218 		 * If there are more MAC address bytes available, but we won't
6219 		 * have any room to print them, then add "..." to the string
6220 		 * instead.  See below for the 'magic number' explanation.
6221 		 */
6222 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6223 			(void) strcpy(bp, "...");
6224 			break;
6225 		}
6226 		(void) sprintf(bp, "%02x", *addr++);
6227 		bp += 2;
6228 		if (--alen == 0)
6229 			break;
6230 		*bp++ = ':';
6231 		buflen -= 3;
6232 		/*
6233 		 * At this point, based on the first 'if' statement above,
6234 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6235 		 * buflen >= 4.  The first case leaves room for the final "xx"
6236 		 * number and trailing NUL byte.  The second leaves room for at
6237 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6238 		 * that statement.
6239 		 */
6240 	}
6241 	return (buf);
6242 }
6243 
6244 /*
6245  * Send an ICMP error after patching up the packet appropriately.  Returns
6246  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6247  */
6248 static boolean_t
6249 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6250     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6251     zoneid_t zoneid, ip_stack_t *ipst)
6252 {
6253 	ipha_t *ipha;
6254 	mblk_t *first_mp;
6255 	boolean_t secure;
6256 	unsigned char db_type;
6257 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6258 
6259 	first_mp = mp;
6260 	if (mctl_present) {
6261 		mp = mp->b_cont;
6262 		secure = ipsec_in_is_secure(first_mp);
6263 		ASSERT(mp != NULL);
6264 	} else {
6265 		/*
6266 		 * If this is an ICMP error being reported - which goes
6267 		 * up as M_CTLs, we need to convert them to M_DATA till
6268 		 * we finish checking with global policy because
6269 		 * ipsec_check_global_policy() assumes M_DATA as clear
6270 		 * and M_CTL as secure.
6271 		 */
6272 		db_type = DB_TYPE(mp);
6273 		DB_TYPE(mp) = M_DATA;
6274 		secure = B_FALSE;
6275 	}
6276 	/*
6277 	 * We are generating an icmp error for some inbound packet.
6278 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6279 	 * Before we generate an error, check with global policy
6280 	 * to see whether this is allowed to enter the system. As
6281 	 * there is no "conn", we are checking with global policy.
6282 	 */
6283 	ipha = (ipha_t *)mp->b_rptr;
6284 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6285 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6286 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6287 		if (first_mp == NULL)
6288 			return (B_FALSE);
6289 	}
6290 
6291 	if (!mctl_present)
6292 		DB_TYPE(mp) = db_type;
6293 
6294 	if (flags & IP_FF_SEND_ICMP) {
6295 		if (flags & IP_FF_HDR_COMPLETE) {
6296 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6297 				freemsg(first_mp);
6298 				return (B_TRUE);
6299 			}
6300 		}
6301 		if (flags & IP_FF_CKSUM) {
6302 			/*
6303 			 * Have to correct checksum since
6304 			 * the packet might have been
6305 			 * fragmented and the reassembly code in ip_rput
6306 			 * does not restore the IP checksum.
6307 			 */
6308 			ipha->ipha_hdr_checksum = 0;
6309 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6310 		}
6311 		switch (icmp_type) {
6312 		case ICMP_DEST_UNREACHABLE:
6313 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6314 			    ipst);
6315 			break;
6316 		default:
6317 			freemsg(first_mp);
6318 			break;
6319 		}
6320 	} else {
6321 		freemsg(first_mp);
6322 		return (B_FALSE);
6323 	}
6324 
6325 	return (B_TRUE);
6326 }
6327 
6328 /*
6329  * Used to send an ICMP error message when a packet is received for
6330  * a protocol that is not supported. The mblk passed as argument
6331  * is consumed by this function.
6332  */
6333 void
6334 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6335     ip_stack_t *ipst)
6336 {
6337 	mblk_t *mp;
6338 	ipha_t *ipha;
6339 	ill_t *ill;
6340 	ipsec_in_t *ii;
6341 
6342 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6343 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6344 
6345 	mp = ipsec_mp->b_cont;
6346 	ipsec_mp->b_cont = NULL;
6347 	ipha = (ipha_t *)mp->b_rptr;
6348 	/* Get ill from index in ipsec_in_t. */
6349 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6350 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6351 	    ipst);
6352 	if (ill != NULL) {
6353 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6354 			if (ip_fanout_send_icmp(q, mp, flags,
6355 			    ICMP_DEST_UNREACHABLE,
6356 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6357 				BUMP_MIB(ill->ill_ip_mib,
6358 				    ipIfStatsInUnknownProtos);
6359 			}
6360 		} else {
6361 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6362 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6363 			    0, B_FALSE, zoneid, ipst)) {
6364 				BUMP_MIB(ill->ill_ip_mib,
6365 				    ipIfStatsInUnknownProtos);
6366 			}
6367 		}
6368 		ill_refrele(ill);
6369 	} else { /* re-link for the freemsg() below. */
6370 		ipsec_mp->b_cont = mp;
6371 	}
6372 
6373 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6374 	freemsg(ipsec_mp);
6375 }
6376 
6377 /*
6378  * See if the inbound datagram has had IPsec processing applied to it.
6379  */
6380 boolean_t
6381 ipsec_in_is_secure(mblk_t *ipsec_mp)
6382 {
6383 	ipsec_in_t *ii;
6384 
6385 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6386 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6387 
6388 	if (ii->ipsec_in_loopback) {
6389 		return (ii->ipsec_in_secure);
6390 	} else {
6391 		return (ii->ipsec_in_ah_sa != NULL ||
6392 		    ii->ipsec_in_esp_sa != NULL ||
6393 		    ii->ipsec_in_decaps);
6394 	}
6395 }
6396 
6397 /*
6398  * Handle protocols with which IP is less intimate.  There
6399  * can be more than one stream bound to a particular
6400  * protocol.  When this is the case, normally each one gets a copy
6401  * of any incoming packets.
6402  *
6403  * IPSEC NOTE :
6404  *
6405  * Don't allow a secure packet going up a non-secure connection.
6406  * We don't allow this because
6407  *
6408  * 1) Reply might go out in clear which will be dropped at
6409  *    the sending side.
6410  * 2) If the reply goes out in clear it will give the
6411  *    adversary enough information for getting the key in
6412  *    most of the cases.
6413  *
6414  * Moreover getting a secure packet when we expect clear
6415  * implies that SA's were added without checking for
6416  * policy on both ends. This should not happen once ISAKMP
6417  * is used to negotiate SAs as SAs will be added only after
6418  * verifying the policy.
6419  *
6420  * NOTE : If the packet was tunneled and not multicast we only send
6421  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6422  * back to delivering packets to AF_INET6 raw sockets.
6423  *
6424  * IPQoS Notes:
6425  * Once we have determined the client, invoke IPPF processing.
6426  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6427  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6428  * ip_policy will be false.
6429  *
6430  * Zones notes:
6431  * Currently only applications in the global zone can create raw sockets for
6432  * protocols other than ICMP. So unlike the broadcast / multicast case of
6433  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6434  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6435  */
6436 static void
6437 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6438     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6439     zoneid_t zoneid)
6440 {
6441 	queue_t	*rq;
6442 	mblk_t	*mp1, *first_mp1;
6443 	uint_t	protocol = ipha->ipha_protocol;
6444 	ipaddr_t dst;
6445 	boolean_t one_only;
6446 	mblk_t *first_mp = mp;
6447 	boolean_t secure;
6448 	uint32_t ill_index;
6449 	conn_t	*connp, *first_connp, *next_connp;
6450 	connf_t	*connfp;
6451 	boolean_t shared_addr;
6452 	mib2_ipIfStatsEntry_t *mibptr;
6453 	ip_stack_t *ipst = recv_ill->ill_ipst;
6454 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6455 
6456 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6457 	if (mctl_present) {
6458 		mp = first_mp->b_cont;
6459 		secure = ipsec_in_is_secure(first_mp);
6460 		ASSERT(mp != NULL);
6461 	} else {
6462 		secure = B_FALSE;
6463 	}
6464 	dst = ipha->ipha_dst;
6465 	/*
6466 	 * If the packet was tunneled and not multicast we only send to it
6467 	 * the first match.
6468 	 */
6469 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6470 	    !CLASSD(dst));
6471 
6472 	shared_addr = (zoneid == ALL_ZONES);
6473 	if (shared_addr) {
6474 		/*
6475 		 * We don't allow multilevel ports for raw IP, so no need to
6476 		 * check for that here.
6477 		 */
6478 		zoneid = tsol_packet_to_zoneid(mp);
6479 	}
6480 
6481 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6482 	mutex_enter(&connfp->connf_lock);
6483 	connp = connfp->connf_head;
6484 	for (connp = connfp->connf_head; connp != NULL;
6485 	    connp = connp->conn_next) {
6486 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6487 		    zoneid) &&
6488 		    (!is_system_labeled() ||
6489 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6490 		    connp))) {
6491 			break;
6492 		}
6493 	}
6494 
6495 	if (connp == NULL || connp->conn_upq == NULL) {
6496 		/*
6497 		 * No one bound to these addresses.  Is
6498 		 * there a client that wants all
6499 		 * unclaimed datagrams?
6500 		 */
6501 		mutex_exit(&connfp->connf_lock);
6502 		/*
6503 		 * Check for IPPROTO_ENCAP...
6504 		 */
6505 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6506 			/*
6507 			 * If an IPsec mblk is here on a multicast
6508 			 * tunnel (using ip_mroute stuff), check policy here,
6509 			 * THEN ship off to ip_mroute_decap().
6510 			 *
6511 			 * BTW,  If I match a configured IP-in-IP
6512 			 * tunnel, this path will not be reached, and
6513 			 * ip_mroute_decap will never be called.
6514 			 */
6515 			first_mp = ipsec_check_global_policy(first_mp, connp,
6516 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6517 			if (first_mp != NULL) {
6518 				if (mctl_present)
6519 					freeb(first_mp);
6520 				ip_mroute_decap(q, mp, ill);
6521 			} /* Else we already freed everything! */
6522 		} else {
6523 			/*
6524 			 * Otherwise send an ICMP protocol unreachable.
6525 			 */
6526 			if (ip_fanout_send_icmp(q, first_mp, flags,
6527 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6528 			    mctl_present, zoneid, ipst)) {
6529 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6530 			}
6531 		}
6532 		return;
6533 	}
6534 	CONN_INC_REF(connp);
6535 	first_connp = connp;
6536 
6537 	/*
6538 	 * Only send message to one tunnel driver by immediately
6539 	 * terminating the loop.
6540 	 */
6541 	connp = one_only ? NULL : connp->conn_next;
6542 
6543 	for (;;) {
6544 		while (connp != NULL) {
6545 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6546 			    flags, zoneid) &&
6547 			    (!is_system_labeled() ||
6548 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6549 			    shared_addr, connp)))
6550 				break;
6551 			connp = connp->conn_next;
6552 		}
6553 
6554 		/*
6555 		 * Copy the packet.
6556 		 */
6557 		if (connp == NULL || connp->conn_upq == NULL ||
6558 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6559 		    ((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6560 			/*
6561 			 * No more interested clients or memory
6562 			 * allocation failed
6563 			 */
6564 			connp = first_connp;
6565 			break;
6566 		}
6567 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6568 		CONN_INC_REF(connp);
6569 		mutex_exit(&connfp->connf_lock);
6570 		rq = connp->conn_rq;
6571 		if (!canputnext(rq)) {
6572 			if (flags & IP_FF_RAWIP) {
6573 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6574 			} else {
6575 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6576 			}
6577 
6578 			freemsg(first_mp1);
6579 		} else {
6580 			/*
6581 			 * Don't enforce here if we're an actual tunnel -
6582 			 * let "tun" do it instead.
6583 			 */
6584 			if (!IPCL_IS_IPTUN(connp) &&
6585 			    (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6586 			    secure)) {
6587 				first_mp1 = ipsec_check_inbound_policy
6588 				    (first_mp1, connp, ipha, NULL,
6589 				    mctl_present);
6590 			}
6591 			if (first_mp1 != NULL) {
6592 				int in_flags = 0;
6593 				/*
6594 				 * ip_fanout_proto also gets called from
6595 				 * icmp_inbound_error_fanout, in which case
6596 				 * the msg type is M_CTL.  Don't add info
6597 				 * in this case for the time being. In future
6598 				 * when there is a need for knowing the
6599 				 * inbound iface index for ICMP error msgs,
6600 				 * then this can be changed.
6601 				 */
6602 				if (connp->conn_recvif)
6603 					in_flags = IPF_RECVIF;
6604 				/*
6605 				 * The ULP may support IP_RECVPKTINFO for both
6606 				 * IP v4 and v6 so pass the appropriate argument
6607 				 * based on conn IP version.
6608 				 */
6609 				if (connp->conn_ip_recvpktinfo) {
6610 					if (connp->conn_af_isv6) {
6611 						/*
6612 						 * V6 only needs index
6613 						 */
6614 						in_flags |= IPF_RECVIF;
6615 					} else {
6616 						/*
6617 						 * V4 needs index +
6618 						 * matching address.
6619 						 */
6620 						in_flags |= IPF_RECVADDR;
6621 					}
6622 				}
6623 				if ((in_flags != 0) &&
6624 				    (mp->b_datap->db_type != M_CTL)) {
6625 					/*
6626 					 * the actual data will be
6627 					 * contained in b_cont upon
6628 					 * successful return of the
6629 					 * following call else
6630 					 * original mblk is returned
6631 					 */
6632 					ASSERT(recv_ill != NULL);
6633 					mp1 = ip_add_info(mp1, recv_ill,
6634 					    in_flags, IPCL_ZONEID(connp), ipst);
6635 				}
6636 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6637 				if (mctl_present)
6638 					freeb(first_mp1);
6639 				putnext(rq, mp1);
6640 			}
6641 		}
6642 		mutex_enter(&connfp->connf_lock);
6643 		/* Follow the next pointer before releasing the conn. */
6644 		next_connp = connp->conn_next;
6645 		CONN_DEC_REF(connp);
6646 		connp = next_connp;
6647 	}
6648 
6649 	/* Last one.  Send it upstream. */
6650 	mutex_exit(&connfp->connf_lock);
6651 
6652 	/*
6653 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6654 	 * will be set to false.
6655 	 */
6656 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6657 		ill_index = ill->ill_phyint->phyint_ifindex;
6658 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6659 		if (mp == NULL) {
6660 			CONN_DEC_REF(connp);
6661 			if (mctl_present) {
6662 				freeb(first_mp);
6663 			}
6664 			return;
6665 		}
6666 	}
6667 
6668 	rq = connp->conn_rq;
6669 	if (!canputnext(rq)) {
6670 		if (flags & IP_FF_RAWIP) {
6671 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6672 		} else {
6673 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6674 		}
6675 
6676 		freemsg(first_mp);
6677 	} else {
6678 		if (IPCL_IS_IPTUN(connp)) {
6679 			/*
6680 			 * Tunneled packet.  We enforce policy in the tunnel
6681 			 * module itself.
6682 			 *
6683 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6684 			 * a policy check.
6685 			 */
6686 			putnext(rq, first_mp);
6687 			CONN_DEC_REF(connp);
6688 			return;
6689 		}
6690 
6691 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6692 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6693 			    ipha, NULL, mctl_present);
6694 		}
6695 
6696 		if (first_mp != NULL) {
6697 			int in_flags = 0;
6698 
6699 			/*
6700 			 * ip_fanout_proto also gets called
6701 			 * from icmp_inbound_error_fanout, in
6702 			 * which case the msg type is M_CTL.
6703 			 * Don't add info in this case for time
6704 			 * being. In future when there is a
6705 			 * need for knowing the inbound iface
6706 			 * index for ICMP error msgs, then this
6707 			 * can be changed
6708 			 */
6709 			if (connp->conn_recvif)
6710 				in_flags = IPF_RECVIF;
6711 			if (connp->conn_ip_recvpktinfo) {
6712 				if (connp->conn_af_isv6) {
6713 					/*
6714 					 * V6 only needs index
6715 					 */
6716 					in_flags |= IPF_RECVIF;
6717 				} else {
6718 					/*
6719 					 * V4 needs index +
6720 					 * matching address.
6721 					 */
6722 					in_flags |= IPF_RECVADDR;
6723 				}
6724 			}
6725 			if ((in_flags != 0) &&
6726 			    (mp->b_datap->db_type != M_CTL)) {
6727 
6728 				/*
6729 				 * the actual data will be contained in
6730 				 * b_cont upon successful return
6731 				 * of the following call else original
6732 				 * mblk is returned
6733 				 */
6734 				ASSERT(recv_ill != NULL);
6735 				mp = ip_add_info(mp, recv_ill,
6736 				    in_flags, IPCL_ZONEID(connp), ipst);
6737 			}
6738 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6739 			putnext(rq, mp);
6740 			if (mctl_present)
6741 				freeb(first_mp);
6742 		}
6743 	}
6744 	CONN_DEC_REF(connp);
6745 }
6746 
6747 /*
6748  * Fanout for TCP packets
6749  * The caller puts <fport, lport> in the ports parameter.
6750  *
6751  * IPQoS Notes
6752  * Before sending it to the client, invoke IPPF processing.
6753  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6754  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6755  * ip_policy is false.
6756  */
6757 static void
6758 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6759     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6760 {
6761 	mblk_t  *first_mp;
6762 	boolean_t secure;
6763 	uint32_t ill_index;
6764 	int	ip_hdr_len;
6765 	tcph_t	*tcph;
6766 	boolean_t syn_present = B_FALSE;
6767 	conn_t	*connp;
6768 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6769 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6770 
6771 	ASSERT(recv_ill != NULL);
6772 
6773 	first_mp = mp;
6774 	if (mctl_present) {
6775 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6776 		mp = first_mp->b_cont;
6777 		secure = ipsec_in_is_secure(first_mp);
6778 		ASSERT(mp != NULL);
6779 	} else {
6780 		secure = B_FALSE;
6781 	}
6782 
6783 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6784 
6785 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6786 	    zoneid, ipst)) == NULL) {
6787 		/*
6788 		 * No connected connection or listener. Send a
6789 		 * TH_RST via tcp_xmit_listeners_reset.
6790 		 */
6791 
6792 		/* Initiate IPPf processing, if needed. */
6793 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6794 			uint32_t ill_index;
6795 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6796 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6797 			if (first_mp == NULL)
6798 				return;
6799 		}
6800 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6801 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6802 		    zoneid));
6803 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6804 		    ipst->ips_netstack->netstack_tcp);
6805 		return;
6806 	}
6807 
6808 	/*
6809 	 * Allocate the SYN for the TCP connection here itself
6810 	 */
6811 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6812 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6813 		if (IPCL_IS_TCP(connp)) {
6814 			squeue_t *sqp;
6815 
6816 			/*
6817 			 * For fused tcp loopback, assign the eager's
6818 			 * squeue to be that of the active connect's.
6819 			 * Note that we don't check for IP_FF_LOOPBACK
6820 			 * here since this routine gets called only
6821 			 * for loopback (unlike the IPv6 counterpart).
6822 			 */
6823 			ASSERT(Q_TO_CONN(q) != NULL);
6824 			if (do_tcp_fusion &&
6825 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6826 			    !secure &&
6827 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy &&
6828 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6829 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6830 				sqp = Q_TO_CONN(q)->conn_sqp;
6831 			} else {
6832 				sqp = IP_SQUEUE_GET(lbolt);
6833 			}
6834 
6835 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6836 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6837 			syn_present = B_TRUE;
6838 		}
6839 	}
6840 
6841 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6842 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6843 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6844 		if ((flags & TH_RST) || (flags & TH_URG)) {
6845 			CONN_DEC_REF(connp);
6846 			freemsg(first_mp);
6847 			return;
6848 		}
6849 		if (flags & TH_ACK) {
6850 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6851 			    ipst->ips_netstack->netstack_tcp);
6852 			CONN_DEC_REF(connp);
6853 			return;
6854 		}
6855 
6856 		CONN_DEC_REF(connp);
6857 		freemsg(first_mp);
6858 		return;
6859 	}
6860 
6861 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6862 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6863 		    NULL, mctl_present);
6864 		if (first_mp == NULL) {
6865 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6866 			CONN_DEC_REF(connp);
6867 			return;
6868 		}
6869 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6870 			ASSERT(syn_present);
6871 			if (mctl_present) {
6872 				ASSERT(first_mp != mp);
6873 				first_mp->b_datap->db_struioflag |=
6874 				    STRUIO_POLICY;
6875 			} else {
6876 				ASSERT(first_mp == mp);
6877 				mp->b_datap->db_struioflag &=
6878 				    ~STRUIO_EAGER;
6879 				mp->b_datap->db_struioflag |=
6880 				    STRUIO_POLICY;
6881 			}
6882 		} else {
6883 			/*
6884 			 * Discard first_mp early since we're dealing with a
6885 			 * fully-connected conn_t and tcp doesn't do policy in
6886 			 * this case.
6887 			 */
6888 			if (mctl_present) {
6889 				freeb(first_mp);
6890 				mctl_present = B_FALSE;
6891 			}
6892 			first_mp = mp;
6893 		}
6894 	}
6895 
6896 	/*
6897 	 * Initiate policy processing here if needed. If we get here from
6898 	 * icmp_inbound_error_fanout, ip_policy is false.
6899 	 */
6900 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6901 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6902 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6903 		if (mp == NULL) {
6904 			CONN_DEC_REF(connp);
6905 			if (mctl_present)
6906 				freeb(first_mp);
6907 			return;
6908 		} else if (mctl_present) {
6909 			ASSERT(first_mp != mp);
6910 			first_mp->b_cont = mp;
6911 		} else {
6912 			first_mp = mp;
6913 		}
6914 	}
6915 
6916 
6917 
6918 	/* Handle socket options. */
6919 	if (!syn_present &&
6920 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6921 		/* Add header */
6922 		ASSERT(recv_ill != NULL);
6923 		/*
6924 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6925 		 * IPF_RECVIF.
6926 		 */
6927 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6928 		    ipst);
6929 		if (mp == NULL) {
6930 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6931 			CONN_DEC_REF(connp);
6932 			if (mctl_present)
6933 				freeb(first_mp);
6934 			return;
6935 		} else if (mctl_present) {
6936 			/*
6937 			 * ip_add_info might return a new mp.
6938 			 */
6939 			ASSERT(first_mp != mp);
6940 			first_mp->b_cont = mp;
6941 		} else {
6942 			first_mp = mp;
6943 		}
6944 	}
6945 
6946 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6947 	if (IPCL_IS_TCP(connp)) {
6948 		(*ip_input_proc)(connp->conn_sqp, first_mp,
6949 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
6950 	} else {
6951 		putnext(connp->conn_rq, first_mp);
6952 		CONN_DEC_REF(connp);
6953 	}
6954 }
6955 
6956 /*
6957  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
6958  * We are responsible for disposing of mp, such as by freemsg() or putnext()
6959  * Caller is responsible for dropping references to the conn, and freeing
6960  * first_mp.
6961  *
6962  * IPQoS Notes
6963  * Before sending it to the client, invoke IPPF processing. Policy processing
6964  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
6965  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
6966  * ip_wput_local, ip_policy is false.
6967  */
6968 static void
6969 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
6970     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
6971     boolean_t ip_policy)
6972 {
6973 	boolean_t	mctl_present = (first_mp != NULL);
6974 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
6975 	uint32_t	ill_index;
6976 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6977 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6978 
6979 	ASSERT(ill != NULL);
6980 
6981 	if (mctl_present)
6982 		first_mp->b_cont = mp;
6983 	else
6984 		first_mp = mp;
6985 
6986 	if (CONN_UDP_FLOWCTLD(connp)) {
6987 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
6988 		freemsg(first_mp);
6989 		return;
6990 	}
6991 
6992 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6993 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6994 		    NULL, mctl_present);
6995 		if (first_mp == NULL) {
6996 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
6997 			return;	/* Freed by ipsec_check_inbound_policy(). */
6998 		}
6999 	}
7000 	if (mctl_present)
7001 		freeb(first_mp);
7002 
7003 	/* Handle options. */
7004 	if (connp->conn_recvif)
7005 		in_flags = IPF_RECVIF;
7006 	/*
7007 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
7008 	 * passed to ip_add_info is based on IP version of connp.
7009 	 */
7010 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
7011 		if (connp->conn_af_isv6) {
7012 			/*
7013 			 * V6 only needs index
7014 			 */
7015 			in_flags |= IPF_RECVIF;
7016 		} else {
7017 			/*
7018 			 * V4 needs index + matching address.
7019 			 */
7020 			in_flags |= IPF_RECVADDR;
7021 		}
7022 	}
7023 
7024 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
7025 		in_flags |= IPF_RECVSLLA;
7026 
7027 	/*
7028 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7029 	 * freed if the packet is dropped. The caller will do so.
7030 	 */
7031 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7032 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7033 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7034 		if (mp == NULL) {
7035 			return;
7036 		}
7037 	}
7038 	if ((in_flags != 0) &&
7039 	    (mp->b_datap->db_type != M_CTL)) {
7040 		/*
7041 		 * The actual data will be contained in b_cont
7042 		 * upon successful return of the following call
7043 		 * else original mblk is returned
7044 		 */
7045 		ASSERT(recv_ill != NULL);
7046 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7047 		    ipst);
7048 	}
7049 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7050 	/* Send it upstream */
7051 	CONN_UDP_RECV(connp, mp);
7052 }
7053 
7054 /*
7055  * Fanout for UDP packets.
7056  * The caller puts <fport, lport> in the ports parameter.
7057  *
7058  * If SO_REUSEADDR is set all multicast and broadcast packets
7059  * will be delivered to all streams bound to the same port.
7060  *
7061  * Zones notes:
7062  * Multicast and broadcast packets will be distributed to streams in all zones.
7063  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7064  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7065  * packets. To maintain this behavior with multiple zones, the conns are grouped
7066  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7067  * each zone. If unset, all the following conns in the same zone are skipped.
7068  */
7069 static void
7070 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7071     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7072     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7073 {
7074 	uint32_t	dstport, srcport;
7075 	ipaddr_t	dst;
7076 	mblk_t		*first_mp;
7077 	boolean_t	secure;
7078 	in6_addr_t	v6src;
7079 	conn_t		*connp;
7080 	connf_t		*connfp;
7081 	conn_t		*first_connp;
7082 	conn_t		*next_connp;
7083 	mblk_t		*mp1, *first_mp1;
7084 	ipaddr_t	src;
7085 	zoneid_t	last_zoneid;
7086 	boolean_t	reuseaddr;
7087 	boolean_t	shared_addr;
7088 	ip_stack_t	*ipst;
7089 
7090 	ASSERT(recv_ill != NULL);
7091 	ipst = recv_ill->ill_ipst;
7092 
7093 	first_mp = mp;
7094 	if (mctl_present) {
7095 		mp = first_mp->b_cont;
7096 		first_mp->b_cont = NULL;
7097 		secure = ipsec_in_is_secure(first_mp);
7098 		ASSERT(mp != NULL);
7099 	} else {
7100 		first_mp = NULL;
7101 		secure = B_FALSE;
7102 	}
7103 
7104 	/* Extract ports in net byte order */
7105 	dstport = htons(ntohl(ports) & 0xFFFF);
7106 	srcport = htons(ntohl(ports) >> 16);
7107 	dst = ipha->ipha_dst;
7108 	src = ipha->ipha_src;
7109 
7110 	shared_addr = (zoneid == ALL_ZONES);
7111 	if (shared_addr) {
7112 		/*
7113 		 * No need to handle exclusive-stack zones since ALL_ZONES
7114 		 * only applies to the shared stack.
7115 		 */
7116 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7117 		if (zoneid == ALL_ZONES)
7118 			zoneid = tsol_packet_to_zoneid(mp);
7119 	}
7120 
7121 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7122 	mutex_enter(&connfp->connf_lock);
7123 	connp = connfp->connf_head;
7124 	if (!broadcast && !CLASSD(dst)) {
7125 		/*
7126 		 * Not broadcast or multicast. Send to the one (first)
7127 		 * client we find. No need to check conn_wantpacket()
7128 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7129 		 * IPv4 unicast packets.
7130 		 */
7131 		while ((connp != NULL) &&
7132 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7133 		    !IPCL_ZONE_MATCH(connp, zoneid))) {
7134 			connp = connp->conn_next;
7135 		}
7136 
7137 		if (connp == NULL || connp->conn_upq == NULL)
7138 			goto notfound;
7139 
7140 		if (is_system_labeled() &&
7141 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7142 		    connp))
7143 			goto notfound;
7144 
7145 		CONN_INC_REF(connp);
7146 		mutex_exit(&connfp->connf_lock);
7147 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7148 		    flags, recv_ill, ip_policy);
7149 		IP_STAT(ipst, ip_udp_fannorm);
7150 		CONN_DEC_REF(connp);
7151 		return;
7152 	}
7153 
7154 	/*
7155 	 * Broadcast and multicast case
7156 	 *
7157 	 * Need to check conn_wantpacket().
7158 	 * If SO_REUSEADDR has been set on the first we send the
7159 	 * packet to all clients that have joined the group and
7160 	 * match the port.
7161 	 */
7162 
7163 	while (connp != NULL) {
7164 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7165 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7166 		    (!is_system_labeled() ||
7167 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7168 		    connp)))
7169 			break;
7170 		connp = connp->conn_next;
7171 	}
7172 
7173 	if (connp == NULL || connp->conn_upq == NULL)
7174 		goto notfound;
7175 
7176 	first_connp = connp;
7177 	/*
7178 	 * When SO_REUSEADDR is not set, send the packet only to the first
7179 	 * matching connection in its zone by keeping track of the zoneid.
7180 	 */
7181 	reuseaddr = first_connp->conn_reuseaddr;
7182 	last_zoneid = first_connp->conn_zoneid;
7183 
7184 	CONN_INC_REF(connp);
7185 	connp = connp->conn_next;
7186 	for (;;) {
7187 		while (connp != NULL) {
7188 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7189 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7190 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7191 			    (!is_system_labeled() ||
7192 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7193 			    shared_addr, connp)))
7194 				break;
7195 			connp = connp->conn_next;
7196 		}
7197 		/*
7198 		 * Just copy the data part alone. The mctl part is
7199 		 * needed just for verifying policy and it is never
7200 		 * sent up.
7201 		 */
7202 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7203 		    ((mp1 = copymsg(mp)) == NULL))) {
7204 			/*
7205 			 * No more interested clients or memory
7206 			 * allocation failed
7207 			 */
7208 			connp = first_connp;
7209 			break;
7210 		}
7211 		if (connp->conn_zoneid != last_zoneid) {
7212 			/*
7213 			 * Update the zoneid so that the packet isn't sent to
7214 			 * any more conns in the same zone unless SO_REUSEADDR
7215 			 * is set.
7216 			 */
7217 			reuseaddr = connp->conn_reuseaddr;
7218 			last_zoneid = connp->conn_zoneid;
7219 		}
7220 		if (first_mp != NULL) {
7221 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7222 			    ipsec_info_type == IPSEC_IN);
7223 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7224 			    ipst->ips_netstack);
7225 			if (first_mp1 == NULL) {
7226 				freemsg(mp1);
7227 				connp = first_connp;
7228 				break;
7229 			}
7230 		} else {
7231 			first_mp1 = NULL;
7232 		}
7233 		CONN_INC_REF(connp);
7234 		mutex_exit(&connfp->connf_lock);
7235 		/*
7236 		 * IPQoS notes: We don't send the packet for policy
7237 		 * processing here, will do it for the last one (below).
7238 		 * i.e. we do it per-packet now, but if we do policy
7239 		 * processing per-conn, then we would need to do it
7240 		 * here too.
7241 		 */
7242 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7243 		    ipha, flags, recv_ill, B_FALSE);
7244 		mutex_enter(&connfp->connf_lock);
7245 		/* Follow the next pointer before releasing the conn. */
7246 		next_connp = connp->conn_next;
7247 		IP_STAT(ipst, ip_udp_fanmb);
7248 		CONN_DEC_REF(connp);
7249 		connp = next_connp;
7250 	}
7251 
7252 	/* Last one.  Send it upstream. */
7253 	mutex_exit(&connfp->connf_lock);
7254 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7255 	    recv_ill, ip_policy);
7256 	IP_STAT(ipst, ip_udp_fanmb);
7257 	CONN_DEC_REF(connp);
7258 	return;
7259 
7260 notfound:
7261 
7262 	mutex_exit(&connfp->connf_lock);
7263 	IP_STAT(ipst, ip_udp_fanothers);
7264 	/*
7265 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7266 	 * have already been matched above, since they live in the IPv4
7267 	 * fanout tables. This implies we only need to
7268 	 * check for IPv6 in6addr_any endpoints here.
7269 	 * Thus we compare using ipv6_all_zeros instead of the destination
7270 	 * address, except for the multicast group membership lookup which
7271 	 * uses the IPv4 destination.
7272 	 */
7273 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7274 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7275 	mutex_enter(&connfp->connf_lock);
7276 	connp = connfp->connf_head;
7277 	if (!broadcast && !CLASSD(dst)) {
7278 		while (connp != NULL) {
7279 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7280 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7281 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7282 			    !connp->conn_ipv6_v6only)
7283 				break;
7284 			connp = connp->conn_next;
7285 		}
7286 
7287 		if (connp != NULL && is_system_labeled() &&
7288 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7289 		    connp))
7290 			connp = NULL;
7291 
7292 		if (connp == NULL || connp->conn_upq == NULL) {
7293 			/*
7294 			 * No one bound to this port.  Is
7295 			 * there a client that wants all
7296 			 * unclaimed datagrams?
7297 			 */
7298 			mutex_exit(&connfp->connf_lock);
7299 
7300 			if (mctl_present)
7301 				first_mp->b_cont = mp;
7302 			else
7303 				first_mp = mp;
7304 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7305 			    connf_head != NULL) {
7306 				ip_fanout_proto(q, first_mp, ill, ipha,
7307 				    flags | IP_FF_RAWIP, mctl_present,
7308 				    ip_policy, recv_ill, zoneid);
7309 			} else {
7310 				if (ip_fanout_send_icmp(q, first_mp, flags,
7311 				    ICMP_DEST_UNREACHABLE,
7312 				    ICMP_PORT_UNREACHABLE,
7313 				    mctl_present, zoneid, ipst)) {
7314 					BUMP_MIB(ill->ill_ip_mib,
7315 					    udpIfStatsNoPorts);
7316 				}
7317 			}
7318 			return;
7319 		}
7320 
7321 		CONN_INC_REF(connp);
7322 		mutex_exit(&connfp->connf_lock);
7323 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7324 		    flags, recv_ill, ip_policy);
7325 		CONN_DEC_REF(connp);
7326 		return;
7327 	}
7328 	/*
7329 	 * IPv4 multicast packet being delivered to an AF_INET6
7330 	 * in6addr_any endpoint.
7331 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7332 	 * and not conn_wantpacket_v6() since any multicast membership is
7333 	 * for an IPv4-mapped multicast address.
7334 	 * The packet is sent to all clients in all zones that have joined the
7335 	 * group and match the port.
7336 	 */
7337 	while (connp != NULL) {
7338 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7339 		    srcport, v6src) &&
7340 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7341 		    (!is_system_labeled() ||
7342 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7343 		    connp)))
7344 			break;
7345 		connp = connp->conn_next;
7346 	}
7347 
7348 	if (connp == NULL || connp->conn_upq == NULL) {
7349 		/*
7350 		 * No one bound to this port.  Is
7351 		 * there a client that wants all
7352 		 * unclaimed datagrams?
7353 		 */
7354 		mutex_exit(&connfp->connf_lock);
7355 
7356 		if (mctl_present)
7357 			first_mp->b_cont = mp;
7358 		else
7359 			first_mp = mp;
7360 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7361 		    NULL) {
7362 			ip_fanout_proto(q, first_mp, ill, ipha,
7363 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7364 			    recv_ill, zoneid);
7365 		} else {
7366 			/*
7367 			 * We used to attempt to send an icmp error here, but
7368 			 * since this is known to be a multicast packet
7369 			 * and we don't send icmp errors in response to
7370 			 * multicast, just drop the packet and give up sooner.
7371 			 */
7372 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7373 			freemsg(first_mp);
7374 		}
7375 		return;
7376 	}
7377 
7378 	first_connp = connp;
7379 
7380 	CONN_INC_REF(connp);
7381 	connp = connp->conn_next;
7382 	for (;;) {
7383 		while (connp != NULL) {
7384 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7385 			    ipv6_all_zeros, srcport, v6src) &&
7386 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7387 			    (!is_system_labeled() ||
7388 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7389 			    shared_addr, connp)))
7390 				break;
7391 			connp = connp->conn_next;
7392 		}
7393 		/*
7394 		 * Just copy the data part alone. The mctl part is
7395 		 * needed just for verifying policy and it is never
7396 		 * sent up.
7397 		 */
7398 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7399 		    ((mp1 = copymsg(mp)) == NULL))) {
7400 			/*
7401 			 * No more intested clients or memory
7402 			 * allocation failed
7403 			 */
7404 			connp = first_connp;
7405 			break;
7406 		}
7407 		if (first_mp != NULL) {
7408 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7409 			    ipsec_info_type == IPSEC_IN);
7410 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7411 			    ipst->ips_netstack);
7412 			if (first_mp1 == NULL) {
7413 				freemsg(mp1);
7414 				connp = first_connp;
7415 				break;
7416 			}
7417 		} else {
7418 			first_mp1 = NULL;
7419 		}
7420 		CONN_INC_REF(connp);
7421 		mutex_exit(&connfp->connf_lock);
7422 		/*
7423 		 * IPQoS notes: We don't send the packet for policy
7424 		 * processing here, will do it for the last one (below).
7425 		 * i.e. we do it per-packet now, but if we do policy
7426 		 * processing per-conn, then we would need to do it
7427 		 * here too.
7428 		 */
7429 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7430 		    ipha, flags, recv_ill, B_FALSE);
7431 		mutex_enter(&connfp->connf_lock);
7432 		/* Follow the next pointer before releasing the conn. */
7433 		next_connp = connp->conn_next;
7434 		CONN_DEC_REF(connp);
7435 		connp = next_connp;
7436 	}
7437 
7438 	/* Last one.  Send it upstream. */
7439 	mutex_exit(&connfp->connf_lock);
7440 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7441 	    recv_ill, ip_policy);
7442 	CONN_DEC_REF(connp);
7443 }
7444 
7445 /*
7446  * Complete the ip_wput header so that it
7447  * is possible to generate ICMP
7448  * errors.
7449  */
7450 int
7451 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7452 {
7453 	ire_t *ire;
7454 
7455 	if (ipha->ipha_src == INADDR_ANY) {
7456 		ire = ire_lookup_local(zoneid, ipst);
7457 		if (ire == NULL) {
7458 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7459 			return (1);
7460 		}
7461 		ipha->ipha_src = ire->ire_addr;
7462 		ire_refrele(ire);
7463 	}
7464 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7465 	ipha->ipha_hdr_checksum = 0;
7466 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7467 	return (0);
7468 }
7469 
7470 /*
7471  * Nobody should be sending
7472  * packets up this stream
7473  */
7474 static void
7475 ip_lrput(queue_t *q, mblk_t *mp)
7476 {
7477 	mblk_t *mp1;
7478 
7479 	switch (mp->b_datap->db_type) {
7480 	case M_FLUSH:
7481 		/* Turn around */
7482 		if (*mp->b_rptr & FLUSHW) {
7483 			*mp->b_rptr &= ~FLUSHR;
7484 			qreply(q, mp);
7485 			return;
7486 		}
7487 		break;
7488 	}
7489 	/* Could receive messages that passed through ar_rput */
7490 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7491 		mp1->b_prev = mp1->b_next = NULL;
7492 	freemsg(mp);
7493 }
7494 
7495 /* Nobody should be sending packets down this stream */
7496 /* ARGSUSED */
7497 void
7498 ip_lwput(queue_t *q, mblk_t *mp)
7499 {
7500 	freemsg(mp);
7501 }
7502 
7503 /*
7504  * Move the first hop in any source route to ipha_dst and remove that part of
7505  * the source route.  Called by other protocols.  Errors in option formatting
7506  * are ignored - will be handled by ip_wput_options Return the final
7507  * destination (either ipha_dst or the last entry in a source route.)
7508  */
7509 ipaddr_t
7510 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7511 {
7512 	ipoptp_t	opts;
7513 	uchar_t		*opt;
7514 	uint8_t		optval;
7515 	uint8_t		optlen;
7516 	ipaddr_t	dst;
7517 	int		i;
7518 	ire_t		*ire;
7519 	ip_stack_t	*ipst = ns->netstack_ip;
7520 
7521 	ip2dbg(("ip_massage_options\n"));
7522 	dst = ipha->ipha_dst;
7523 	for (optval = ipoptp_first(&opts, ipha);
7524 	    optval != IPOPT_EOL;
7525 	    optval = ipoptp_next(&opts)) {
7526 		opt = opts.ipoptp_cur;
7527 		switch (optval) {
7528 			uint8_t off;
7529 		case IPOPT_SSRR:
7530 		case IPOPT_LSRR:
7531 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7532 				ip1dbg(("ip_massage_options: bad src route\n"));
7533 				break;
7534 			}
7535 			optlen = opts.ipoptp_len;
7536 			off = opt[IPOPT_OFFSET];
7537 			off--;
7538 		redo_srr:
7539 			if (optlen < IP_ADDR_LEN ||
7540 			    off > optlen - IP_ADDR_LEN) {
7541 				/* End of source route */
7542 				ip1dbg(("ip_massage_options: end of SR\n"));
7543 				break;
7544 			}
7545 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7546 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7547 			    ntohl(dst)));
7548 			/*
7549 			 * Check if our address is present more than
7550 			 * once as consecutive hops in source route.
7551 			 * XXX verify per-interface ip_forwarding
7552 			 * for source route?
7553 			 */
7554 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7555 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7556 			if (ire != NULL) {
7557 				ire_refrele(ire);
7558 				off += IP_ADDR_LEN;
7559 				goto redo_srr;
7560 			}
7561 			if (dst == htonl(INADDR_LOOPBACK)) {
7562 				ip1dbg(("ip_massage_options: loopback addr in "
7563 				    "source route!\n"));
7564 				break;
7565 			}
7566 			/*
7567 			 * Update ipha_dst to be the first hop and remove the
7568 			 * first hop from the source route (by overwriting
7569 			 * part of the option with NOP options).
7570 			 */
7571 			ipha->ipha_dst = dst;
7572 			/* Put the last entry in dst */
7573 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7574 			    3;
7575 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7576 
7577 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7578 			    ntohl(dst)));
7579 			/* Move down and overwrite */
7580 			opt[IP_ADDR_LEN] = opt[0];
7581 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7582 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7583 			for (i = 0; i < IP_ADDR_LEN; i++)
7584 				opt[i] = IPOPT_NOP;
7585 			break;
7586 		}
7587 	}
7588 	return (dst);
7589 }
7590 
7591 /*
7592  * This function's job is to forward data to the reverse tunnel (FA->HA)
7593  * after doing a few checks. It is assumed that the incoming interface
7594  * of the packet is always different than the outgoing interface and the
7595  * ire_type of the found ire has to be a non-resolver type.
7596  *
7597  * IPQoS notes
7598  * IP policy is invoked twice for a forwarded packet, once on the read side
7599  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
7600  * enabled.
7601  */
7602 static void
7603 ip_mrtun_forward(ire_t *ire, ill_t *in_ill, mblk_t *mp)
7604 {
7605 	ipha_t		*ipha;
7606 	queue_t		*q;
7607 	uint32_t 	pkt_len;
7608 #define	rptr    ((uchar_t *)ipha)
7609 	uint32_t 	sum;
7610 	uint32_t 	max_frag;
7611 	mblk_t		*first_mp;
7612 	uint32_t	ill_index;
7613 	ipxmit_state_t	pktxmit_state;
7614 	ill_t		*out_ill;
7615 	ip_stack_t	*ipst = in_ill->ill_ipst;
7616 
7617 	ASSERT(ire != NULL);
7618 	ASSERT(ire->ire_ipif->ipif_net_type == IRE_IF_NORESOLVER);
7619 	ASSERT(ire->ire_stq != NULL);
7620 
7621 	/* Initiate read side IPPF processing */
7622 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
7623 		ill_index = in_ill->ill_phyint->phyint_ifindex;
7624 		ip_process(IPP_FWD_IN, &mp, ill_index);
7625 		if (mp == NULL) {
7626 			ip2dbg(("ip_mrtun_forward: inbound pkt "
7627 			    "dropped during IPPF processing\n"));
7628 			return;
7629 		}
7630 	}
7631 
7632 	if (((in_ill->ill_flags & ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
7633 	    ILLF_ROUTER) == 0) ||
7634 	    (in_ill == (ill_t *)ire->ire_stq->q_ptr)) {
7635 		BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsForwProhibits);
7636 		ip0dbg(("ip_mrtun_forward: Can't forward :"
7637 		    "forwarding is not turned on\n"));
7638 		goto drop_pkt;
7639 	}
7640 
7641 	/*
7642 	 * Don't forward if the interface is down
7643 	 */
7644 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
7645 		goto discard_pkt;
7646 	}
7647 
7648 	ipha = (ipha_t *)mp->b_rptr;
7649 	pkt_len = ntohs(ipha->ipha_length);
7650 	/* Adjust the checksum to reflect the ttl decrement. */
7651 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
7652 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
7653 	if (ipha->ipha_ttl-- <= 1) {
7654 		if (ip_csum_hdr(ipha)) {
7655 			BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInCksumErrs);
7656 			goto drop_pkt;
7657 		}
7658 		q = ire->ire_stq;
7659 		if ((first_mp = allocb(sizeof (ipsec_info_t),
7660 		    BPRI_HI)) == NULL) {
7661 			goto discard_pkt;
7662 		}
7663 		BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsForwProhibits);
7664 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
7665 		/* Sent by forwarding path, and router is global zone */
7666 		icmp_time_exceeded(q, first_mp, ICMP_TTL_EXCEEDED,
7667 		    GLOBAL_ZONEID, ipst);
7668 		return;
7669 	}
7670 
7671 	/* Get the ill_index of the ILL */
7672 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
7673 
7674 	/*
7675 	 * This location is chosen for the placement of the forwarding hook
7676 	 * because at this point we know that we have a path out for the
7677 	 * packet but haven't yet applied any logic (such as fragmenting)
7678 	 * that happen as part of transmitting the packet out.
7679 	 */
7680 	out_ill = ire->ire_ipif->ipif_ill;
7681 
7682 	DTRACE_PROBE4(ip4__forwarding__start,
7683 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
7684 
7685 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
7686 	    ipst->ips_ipv4firewall_forwarding,
7687 	    in_ill, out_ill, ipha, mp, mp, ipst);
7688 
7689 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
7690 
7691 	if (mp == NULL)
7692 		return;
7693 	pkt_len = ntohs(ipha->ipha_length);
7694 
7695 	/*
7696 	 * ip_mrtun_forward is only used by foreign agent to reverse
7697 	 * tunnel the incoming packet. So it does not do any option
7698 	 * processing for source routing.
7699 	 */
7700 	max_frag = ire->ire_max_frag;
7701 	if (pkt_len > max_frag) {
7702 		/*
7703 		 * It needs fragging on its way out.  We haven't
7704 		 * verified the header checksum yet.  Since we
7705 		 * are going to put a surely good checksum in the
7706 		 * outgoing header, we have to make sure that it
7707 		 * was good coming in.
7708 		 */
7709 		if (ip_csum_hdr(ipha)) {
7710 			BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInCksumErrs);
7711 			goto drop_pkt;
7712 		}
7713 
7714 		/* Initiate write side IPPF processing */
7715 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
7716 			ip_process(IPP_FWD_OUT, &mp, ill_index);
7717 			if (mp == NULL) {
7718 				ip2dbg(("ip_mrtun_forward: outbound pkt "\
7719 				    "dropped/deferred during ip policy "\
7720 				    "processing\n"));
7721 				return;
7722 			}
7723 		}
7724 		if ((first_mp = allocb(sizeof (ipsec_info_t),
7725 		    BPRI_HI)) == NULL) {
7726 			goto discard_pkt;
7727 		}
7728 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
7729 		mp = first_mp;
7730 
7731 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID, ipst);
7732 		return;
7733 	}
7734 
7735 	ip2dbg(("ip_mrtun_forward: ire type (%d)\n", ire->ire_type));
7736 
7737 	ASSERT(ire->ire_ipif != NULL);
7738 
7739 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
7740 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
7741 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
7742 	    ipst->ips_ipv4firewall_physical_out,
7743 	    NULL, out_ill, ipha, mp, mp, ipst);
7744 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
7745 	if (mp == NULL)
7746 		return;
7747 
7748 	/* Now send the packet to the tunnel interface */
7749 	mp->b_prev = SET_BPREV_FLAG(IPP_FWD_OUT);
7750 	q = ire->ire_stq;
7751 	pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_FALSE);
7752 	if ((pktxmit_state == SEND_FAILED) ||
7753 	    (pktxmit_state == LLHDR_RESLV_FAILED)) {
7754 		ip2dbg(("ip_mrtun_forward: failed to send packet to ill %p\n",
7755 		    q->q_ptr));
7756 	}
7757 
7758 	return;
7759 discard_pkt:
7760 	BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInDiscards);
7761 drop_pkt:;
7762 	ip2dbg(("ip_mrtun_forward: dropping pkt\n"));
7763 	freemsg(mp);
7764 #undef	rptr
7765 }
7766 
7767 /*
7768  * Fills the ipsec_out_t data structure with appropriate fields and
7769  * prepends it to mp which contains the IP hdr + data that was meant
7770  * to be forwarded. Please note that ipsec_out_info data structure
7771  * is used here to communicate the outgoing ill path at ip_wput()
7772  * for the ICMP error packet. This has nothing to do with ipsec IP
7773  * security. ipsec_out_t is really used to pass the info to the module
7774  * IP where this information cannot be extracted from conn.
7775  * This functions is called by ip_mrtun_forward().
7776  */
7777 void
7778 ip_ipsec_out_prepend(mblk_t *first_mp, mblk_t *mp, ill_t *xmit_ill)
7779 {
7780 	ipsec_out_t	*io;
7781 
7782 	ASSERT(xmit_ill != NULL);
7783 	first_mp->b_datap->db_type = M_CTL;
7784 	first_mp->b_wptr += sizeof (ipsec_info_t);
7785 	/*
7786 	 * This is to pass info to ip_wput in absence of conn.
7787 	 * ipsec_out_secure will be B_FALSE because of this.
7788 	 * Thus ipsec_out_secure being B_FALSE indicates that
7789 	 * this is not IPSEC security related information.
7790 	 */
7791 	bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
7792 	io = (ipsec_out_t *)first_mp->b_rptr;
7793 	io->ipsec_out_type = IPSEC_OUT;
7794 	io->ipsec_out_len = sizeof (ipsec_out_t);
7795 	first_mp->b_cont = mp;
7796 	io->ipsec_out_ill_index =
7797 	    xmit_ill->ill_phyint->phyint_ifindex;
7798 	io->ipsec_out_xmit_if = B_TRUE;
7799 	io->ipsec_out_ns = xmit_ill->ill_ipst->ips_netstack;
7800 }
7801 
7802 /*
7803  * Return the network mask
7804  * associated with the specified address.
7805  */
7806 ipaddr_t
7807 ip_net_mask(ipaddr_t addr)
7808 {
7809 	uchar_t	*up = (uchar_t *)&addr;
7810 	ipaddr_t mask = 0;
7811 	uchar_t	*maskp = (uchar_t *)&mask;
7812 
7813 #if defined(__i386) || defined(__amd64)
7814 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7815 #endif
7816 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7817 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7818 #endif
7819 	if (CLASSD(addr)) {
7820 		maskp[0] = 0xF0;
7821 		return (mask);
7822 	}
7823 	if (addr == 0)
7824 		return (0);
7825 	maskp[0] = 0xFF;
7826 	if ((up[0] & 0x80) == 0)
7827 		return (mask);
7828 
7829 	maskp[1] = 0xFF;
7830 	if ((up[0] & 0xC0) == 0x80)
7831 		return (mask);
7832 
7833 	maskp[2] = 0xFF;
7834 	if ((up[0] & 0xE0) == 0xC0)
7835 		return (mask);
7836 
7837 	/* Must be experimental or multicast, indicate as much */
7838 	return ((ipaddr_t)0);
7839 }
7840 
7841 /*
7842  * Select an ill for the packet by considering load spreading across
7843  * a different ill in the group if dst_ill is part of some group.
7844  */
7845 ill_t *
7846 ip_newroute_get_dst_ill(ill_t *dst_ill)
7847 {
7848 	ill_t *ill;
7849 
7850 	/*
7851 	 * We schedule irrespective of whether the source address is
7852 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7853 	 */
7854 	ill = illgrp_scheduler(dst_ill);
7855 	if (ill == NULL)
7856 		return (NULL);
7857 
7858 	/*
7859 	 * For groups with names ip_sioctl_groupname ensures that all
7860 	 * ills are of same type. For groups without names, ifgrp_insert
7861 	 * ensures this.
7862 	 */
7863 	ASSERT(dst_ill->ill_type == ill->ill_type);
7864 
7865 	return (ill);
7866 }
7867 
7868 /*
7869  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7870  */
7871 ill_t *
7872 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6,
7873     ip_stack_t *ipst)
7874 {
7875 	ill_t *ret_ill;
7876 
7877 	ASSERT(ifindex != 0);
7878 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7879 	    ipst);
7880 	if (ret_ill == NULL ||
7881 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7882 		if (isv6) {
7883 			if (ill != NULL) {
7884 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7885 			} else {
7886 				BUMP_MIB(&ipst->ips_ip6_mib,
7887 				    ipIfStatsOutDiscards);
7888 			}
7889 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7890 			    "bad ifindex %d.\n", ifindex));
7891 		} else {
7892 			if (ill != NULL) {
7893 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7894 			} else {
7895 				BUMP_MIB(&ipst->ips_ip_mib,
7896 				    ipIfStatsOutDiscards);
7897 			}
7898 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7899 			    "bad ifindex %d.\n", ifindex));
7900 		}
7901 		if (ret_ill != NULL)
7902 			ill_refrele(ret_ill);
7903 		freemsg(first_mp);
7904 		return (NULL);
7905 	}
7906 
7907 	return (ret_ill);
7908 }
7909 
7910 /*
7911  * IPv4 -
7912  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7913  * out a packet to a destination address for which we do not have specific
7914  * (or sufficient) routing information.
7915  *
7916  * NOTE : These are the scopes of some of the variables that point at IRE,
7917  *	  which needs to be followed while making any future modifications
7918  *	  to avoid memory leaks.
7919  *
7920  *	- ire and sire are the entries looked up initially by
7921  *	  ire_ftable_lookup.
7922  *	- ipif_ire is used to hold the interface ire associated with
7923  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7924  *	  it before branching out to error paths.
7925  *	- save_ire is initialized before ire_create, so that ire returned
7926  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7927  *	  before breaking out of the switch.
7928  *
7929  *	Thus on failures, we have to REFRELE only ire and sire, if they
7930  *	are not NULL.
7931  */
7932 void
7933 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, ill_t *in_ill, conn_t *connp,
7934     zoneid_t zoneid, ip_stack_t *ipst)
7935 {
7936 	areq_t	*areq;
7937 	ipaddr_t gw = 0;
7938 	ire_t	*ire = NULL;
7939 	mblk_t	*res_mp;
7940 	ipaddr_t *addrp;
7941 	ipaddr_t nexthop_addr;
7942 	ipif_t  *src_ipif = NULL;
7943 	ill_t	*dst_ill = NULL;
7944 	ipha_t  *ipha;
7945 	ire_t	*sire = NULL;
7946 	mblk_t	*first_mp;
7947 	ire_t	*save_ire;
7948 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7949 	ushort_t ire_marks = 0;
7950 	boolean_t mctl_present;
7951 	ipsec_out_t *io;
7952 	mblk_t	*saved_mp;
7953 	ire_t	*first_sire = NULL;
7954 	mblk_t	*copy_mp = NULL;
7955 	mblk_t	*xmit_mp = NULL;
7956 	ipaddr_t save_dst;
7957 	uint32_t multirt_flags =
7958 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7959 	boolean_t multirt_is_resolvable;
7960 	boolean_t multirt_resolve_next;
7961 	boolean_t do_attach_ill = B_FALSE;
7962 	boolean_t ip_nexthop = B_FALSE;
7963 	tsol_ire_gw_secattr_t *attrp = NULL;
7964 	tsol_gcgrp_t *gcgrp = NULL;
7965 	tsol_gcgrp_addr_t ga;
7966 
7967 	if (ip_debug > 2) {
7968 		/* ip1dbg */
7969 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7970 	}
7971 
7972 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7973 	if (mctl_present) {
7974 		io = (ipsec_out_t *)first_mp->b_rptr;
7975 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7976 		ASSERT(zoneid == io->ipsec_out_zoneid);
7977 		ASSERT(zoneid != ALL_ZONES);
7978 	}
7979 
7980 	ipha = (ipha_t *)mp->b_rptr;
7981 
7982 	/* All multicast lookups come through ip_newroute_ipif() */
7983 	if (CLASSD(dst)) {
7984 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7985 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7986 		freemsg(first_mp);
7987 		return;
7988 	}
7989 
7990 	if (mctl_present && io->ipsec_out_attach_if) {
7991 		/* ip_grab_attach_ill returns a held ill */
7992 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7993 		    io->ipsec_out_ill_index, B_FALSE, ipst);
7994 
7995 		/* Failure case frees things for us. */
7996 		if (attach_ill == NULL)
7997 			return;
7998 
7999 		/*
8000 		 * Check if we need an ire that will not be
8001 		 * looked up by anybody else i.e. HIDDEN.
8002 		 */
8003 		if (ill_is_probeonly(attach_ill))
8004 			ire_marks = IRE_MARK_HIDDEN;
8005 	}
8006 	if (mctl_present && io->ipsec_out_ip_nexthop) {
8007 		ip_nexthop = B_TRUE;
8008 		nexthop_addr = io->ipsec_out_nexthop_addr;
8009 	}
8010 	/*
8011 	 * If this IRE is created for forwarding or it is not for
8012 	 * traffic for congestion controlled protocols, mark it as temporary.
8013 	 */
8014 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
8015 		ire_marks |= IRE_MARK_TEMPORARY;
8016 
8017 	/*
8018 	 * Get what we can from ire_ftable_lookup which will follow an IRE
8019 	 * chain until it gets the most specific information available.
8020 	 * For example, we know that there is no IRE_CACHE for this dest,
8021 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
8022 	 * ire_ftable_lookup will look up the gateway, etc.
8023 	 * Check if in_ill != NULL. If it is true, the packet must be
8024 	 * from an incoming interface where RTA_SRCIFP is set.
8025 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
8026 	 * to the destination, of equal netmask length in the forward table,
8027 	 * will be recursively explored. If no information is available
8028 	 * for the final gateway of that route, we force the returned ire
8029 	 * to be equal to sire using MATCH_IRE_PARENT.
8030 	 * At least, in this case we have a starting point (in the buckets)
8031 	 * to look for other routes to the destination in the forward table.
8032 	 * This is actually used only for multirouting, where a list
8033 	 * of routes has to be processed in sequence.
8034 	 *
8035 	 * In the process of coming up with the most specific information,
8036 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
8037 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
8038 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
8039 	 * Two caveats when handling incomplete ire's in ip_newroute:
8040 	 * - we should be careful when accessing its ire_nce (specifically
8041 	 *   the nce_res_mp) ast it might change underneath our feet, and,
8042 	 * - not all legacy code path callers are prepared to handle
8043 	 *   incomplete ire's, so we should not create/add incomplete
8044 	 *   ire_cache entries here. (See discussion about temporary solution
8045 	 *   further below).
8046 	 *
8047 	 * In order to minimize packet dropping, and to preserve existing
8048 	 * behavior, we treat this case as if there were no IRE_CACHE for the
8049 	 * gateway, and instead use the IF_RESOLVER ire to send out
8050 	 * another request to ARP (this is achieved by passing the
8051 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
8052 	 * arp response comes back in ip_wput_nondata, we will create
8053 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
8054 	 *
8055 	 * Note that this is a temporary solution; the correct solution is
8056 	 * to create an incomplete  per-dst ire_cache entry, and send the
8057 	 * packet out when the gw's nce is resolved. In order to achieve this,
8058 	 * all packet processing must have been completed prior to calling
8059 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
8060 	 * to be modified to accomodate this solution.
8061 	 */
8062 	if (in_ill != NULL) {
8063 		ire = ire_srcif_table_lookup(dst, IRE_IF_RESOLVER, NULL,
8064 		    in_ill, MATCH_IRE_TYPE);
8065 	} else if (ip_nexthop) {
8066 		/*
8067 		 * The first time we come here, we look for an IRE_INTERFACE
8068 		 * entry for the specified nexthop, set the dst to be the
8069 		 * nexthop address and create an IRE_CACHE entry for the
8070 		 * nexthop. The next time around, we are able to find an
8071 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
8072 		 * nexthop address and create an IRE_CACHE entry for the
8073 		 * destination address via the specified nexthop.
8074 		 */
8075 		ire = ire_cache_lookup(nexthop_addr, zoneid,
8076 		    MBLK_GETLABEL(mp), ipst);
8077 		if (ire != NULL) {
8078 			gw = nexthop_addr;
8079 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
8080 		} else {
8081 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
8082 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
8083 			    MBLK_GETLABEL(mp),
8084 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
8085 			    ipst);
8086 			if (ire != NULL) {
8087 				dst = nexthop_addr;
8088 			}
8089 		}
8090 	} else if (attach_ill == NULL) {
8091 		ire = ire_ftable_lookup(dst, 0, 0, 0,
8092 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
8093 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
8094 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
8095 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
8096 		    ipst);
8097 	} else {
8098 		/*
8099 		 * attach_ill is set only for communicating with
8100 		 * on-link hosts. So, don't look for DEFAULT.
8101 		 */
8102 		ipif_t	*attach_ipif;
8103 
8104 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
8105 		if (attach_ipif == NULL) {
8106 			ill_refrele(attach_ill);
8107 			goto icmp_err_ret;
8108 		}
8109 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
8110 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
8111 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
8112 		    MATCH_IRE_SECATTR, ipst);
8113 		ipif_refrele(attach_ipif);
8114 	}
8115 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
8116 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
8117 
8118 	/*
8119 	 * This loop is run only once in most cases.
8120 	 * We loop to resolve further routes only when the destination
8121 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8122 	 */
8123 	do {
8124 		/* Clear the previous iteration's values */
8125 		if (src_ipif != NULL) {
8126 			ipif_refrele(src_ipif);
8127 			src_ipif = NULL;
8128 		}
8129 		if (dst_ill != NULL) {
8130 			ill_refrele(dst_ill);
8131 			dst_ill = NULL;
8132 		}
8133 
8134 		multirt_resolve_next = B_FALSE;
8135 		/*
8136 		 * We check if packets have to be multirouted.
8137 		 * In this case, given the current <ire, sire> couple,
8138 		 * we look for the next suitable <ire, sire>.
8139 		 * This check is done in ire_multirt_lookup(),
8140 		 * which applies various criteria to find the next route
8141 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
8142 		 * unchanged if it detects it has not been tried yet.
8143 		 */
8144 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8145 			ip3dbg(("ip_newroute: starting next_resolution "
8146 			    "with first_mp %p, tag %d\n",
8147 			    (void *)first_mp,
8148 			    MULTIRT_DEBUG_TAGGED(first_mp)));
8149 
8150 			ASSERT(sire != NULL);
8151 			multirt_is_resolvable =
8152 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
8153 			    MBLK_GETLABEL(mp), ipst);
8154 
8155 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
8156 			    "ire %p, sire %p\n",
8157 			    multirt_is_resolvable,
8158 			    (void *)ire, (void *)sire));
8159 
8160 			if (!multirt_is_resolvable) {
8161 				/*
8162 				 * No more multirt route to resolve; give up
8163 				 * (all routes resolved or no more
8164 				 * resolvable routes).
8165 				 */
8166 				if (ire != NULL) {
8167 					ire_refrele(ire);
8168 					ire = NULL;
8169 				}
8170 			} else {
8171 				ASSERT(sire != NULL);
8172 				ASSERT(ire != NULL);
8173 				/*
8174 				 * We simply use first_sire as a flag that
8175 				 * indicates if a resolvable multirt route
8176 				 * has already been found.
8177 				 * If it is not the case, we may have to send
8178 				 * an ICMP error to report that the
8179 				 * destination is unreachable.
8180 				 * We do not IRE_REFHOLD first_sire.
8181 				 */
8182 				if (first_sire == NULL) {
8183 					first_sire = sire;
8184 				}
8185 			}
8186 		}
8187 		if (ire == NULL) {
8188 			if (ip_debug > 3) {
8189 				/* ip2dbg */
8190 				pr_addr_dbg("ip_newroute: "
8191 				    "can't resolve %s\n", AF_INET, &dst);
8192 			}
8193 			ip3dbg(("ip_newroute: "
8194 			    "ire %p, sire %p, first_sire %p\n",
8195 			    (void *)ire, (void *)sire, (void *)first_sire));
8196 
8197 			if (sire != NULL) {
8198 				ire_refrele(sire);
8199 				sire = NULL;
8200 			}
8201 
8202 			if (first_sire != NULL) {
8203 				/*
8204 				 * At least one multirt route has been found
8205 				 * in the same call to ip_newroute();
8206 				 * there is no need to report an ICMP error.
8207 				 * first_sire was not IRE_REFHOLDed.
8208 				 */
8209 				MULTIRT_DEBUG_UNTAG(first_mp);
8210 				freemsg(first_mp);
8211 				return;
8212 			}
8213 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8214 			    RTA_DST, ipst);
8215 			if (attach_ill != NULL)
8216 				ill_refrele(attach_ill);
8217 			goto icmp_err_ret;
8218 		}
8219 
8220 		/*
8221 		 * When RTA_SRCIFP is used to add a route, then an interface
8222 		 * route is added in the source interface's routing table.
8223 		 * If the outgoing interface of this route is of type
8224 		 * IRE_IF_RESOLVER, then upon creation of the ire,
8225 		 * ire_nce->nce_res_mp is set to NULL.
8226 		 * Later, when this route is first used for forwarding
8227 		 * a packet, ip_newroute() is called
8228 		 * to resolve the hardware address of the outgoing ipif.
8229 		 * We do not come here for IRE_IF_NORESOLVER entries in the
8230 		 * source interface based table. We only come here if the
8231 		 * outgoing interface is a resolver interface and we don't
8232 		 * have the ire_nce->nce_res_mp information yet.
8233 		 * If in_ill is not null that means it is called from
8234 		 * ip_rput.
8235 		 */
8236 
8237 		ASSERT(ire->ire_in_ill == NULL ||
8238 		    (ire->ire_type == IRE_IF_RESOLVER &&
8239 		    ire->ire_nce != NULL && ire->ire_nce->nce_res_mp == NULL));
8240 
8241 		/*
8242 		 * Verify that the returned IRE does not have either
8243 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8244 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8245 		 */
8246 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8247 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8248 			if (attach_ill != NULL)
8249 				ill_refrele(attach_ill);
8250 			goto icmp_err_ret;
8251 		}
8252 		/*
8253 		 * Increment the ire_ob_pkt_count field for ire if it is an
8254 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8255 		 * increment the same for the parent IRE, sire, if it is some
8256 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, and HOST)
8257 		 */
8258 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8259 			UPDATE_OB_PKT_COUNT(ire);
8260 			ire->ire_last_used_time = lbolt;
8261 		}
8262 
8263 		if (sire != NULL) {
8264 			gw = sire->ire_gateway_addr;
8265 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8266 			    IRE_INTERFACE)) == 0);
8267 			UPDATE_OB_PKT_COUNT(sire);
8268 			sire->ire_last_used_time = lbolt;
8269 		}
8270 		/*
8271 		 * We have a route to reach the destination.
8272 		 *
8273 		 * 1) If the interface is part of ill group, try to get a new
8274 		 *    ill taking load spreading into account.
8275 		 *
8276 		 * 2) After selecting the ill, get a source address that
8277 		 *    might create good inbound load spreading.
8278 		 *    ipif_select_source does this for us.
8279 		 *
8280 		 * If the application specified the ill (ifindex), we still
8281 		 * load spread. Only if the packets needs to go out
8282 		 * specifically on a given ill e.g. binding to
8283 		 * IPIF_NOFAILOVER address, then we don't try to use a
8284 		 * different ill for load spreading.
8285 		 */
8286 		if (attach_ill == NULL) {
8287 			/*
8288 			 * Don't perform outbound load spreading in the
8289 			 * case of an RTF_MULTIRT route, as we actually
8290 			 * typically want to replicate outgoing packets
8291 			 * through particular interfaces.
8292 			 */
8293 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8294 				dst_ill = ire->ire_ipif->ipif_ill;
8295 				/* for uniformity */
8296 				ill_refhold(dst_ill);
8297 			} else {
8298 				/*
8299 				 * If we are here trying to create an IRE_CACHE
8300 				 * for an offlink destination and have the
8301 				 * IRE_CACHE for the next hop and the latter is
8302 				 * using virtual IP source address selection i.e
8303 				 * it's ire->ire_ipif is pointing to a virtual
8304 				 * network interface (vni) then
8305 				 * ip_newroute_get_dst_ll() will return the vni
8306 				 * interface as the dst_ill. Since the vni is
8307 				 * virtual i.e not associated with any physical
8308 				 * interface, it cannot be the dst_ill, hence
8309 				 * in such a case call ip_newroute_get_dst_ll()
8310 				 * with the stq_ill instead of the ire_ipif ILL.
8311 				 * The function returns a refheld ill.
8312 				 */
8313 				if ((ire->ire_type == IRE_CACHE) &&
8314 				    IS_VNI(ire->ire_ipif->ipif_ill))
8315 					dst_ill = ip_newroute_get_dst_ill(
8316 					    ire->ire_stq->q_ptr);
8317 				else
8318 					dst_ill = ip_newroute_get_dst_ill(
8319 					    ire->ire_ipif->ipif_ill);
8320 			}
8321 			if (dst_ill == NULL) {
8322 				if (ip_debug > 2) {
8323 					pr_addr_dbg("ip_newroute: "
8324 					    "no dst ill for dst"
8325 					    " %s\n", AF_INET, &dst);
8326 				}
8327 				goto icmp_err_ret;
8328 			}
8329 		} else {
8330 			dst_ill = ire->ire_ipif->ipif_ill;
8331 			/* for uniformity */
8332 			ill_refhold(dst_ill);
8333 			/*
8334 			 * We should have found a route matching ill as we
8335 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
8336 			 * Rather than asserting, when there is a mismatch,
8337 			 * we just drop the packet.
8338 			 */
8339 			if (dst_ill != attach_ill) {
8340 				ip0dbg(("ip_newroute: Packet dropped as "
8341 				    "IPIF_NOFAILOVER ill is %s, "
8342 				    "ire->ire_ipif->ipif_ill is %s\n",
8343 				    attach_ill->ill_name,
8344 				    dst_ill->ill_name));
8345 				ill_refrele(attach_ill);
8346 				goto icmp_err_ret;
8347 			}
8348 		}
8349 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
8350 		if (attach_ill != NULL) {
8351 			ill_refrele(attach_ill);
8352 			attach_ill = NULL;
8353 			do_attach_ill = B_TRUE;
8354 		}
8355 		ASSERT(dst_ill != NULL);
8356 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8357 
8358 		/*
8359 		 * Pick the best source address from dst_ill.
8360 		 *
8361 		 * 1) If it is part of a multipathing group, we would
8362 		 *    like to spread the inbound packets across different
8363 		 *    interfaces. ipif_select_source picks a random source
8364 		 *    across the different ills in the group.
8365 		 *
8366 		 * 2) If it is not part of a multipathing group, we try
8367 		 *    to pick the source address from the destination
8368 		 *    route. Clustering assumes that when we have multiple
8369 		 *    prefixes hosted on an interface, the prefix of the
8370 		 *    source address matches the prefix of the destination
8371 		 *    route. We do this only if the address is not
8372 		 *    DEPRECATED.
8373 		 *
8374 		 * 3) If the conn is in a different zone than the ire, we
8375 		 *    need to pick a source address from the right zone.
8376 		 *
8377 		 * NOTE : If we hit case (1) above, the prefix of the source
8378 		 *	  address picked may not match the prefix of the
8379 		 *	  destination routes prefix as ipif_select_source
8380 		 *	  does not look at "dst" while picking a source
8381 		 *	  address.
8382 		 *	  If we want the same behavior as (2), we will need
8383 		 *	  to change the behavior of ipif_select_source.
8384 		 */
8385 		ASSERT(src_ipif == NULL);
8386 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8387 			/*
8388 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8389 			 * Check that the ipif matching the requested source
8390 			 * address still exists.
8391 			 */
8392 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8393 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8394 		}
8395 		if (src_ipif == NULL) {
8396 			ire_marks |= IRE_MARK_USESRC_CHECK;
8397 			if ((dst_ill->ill_group != NULL) ||
8398 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8399 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8400 			    ire->ire_zoneid != ALL_ZONES) ||
8401 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8402 				/*
8403 				 * If the destination is reachable via a
8404 				 * given gateway, the selected source address
8405 				 * should be in the same subnet as the gateway.
8406 				 * Otherwise, the destination is not reachable.
8407 				 *
8408 				 * If there are no interfaces on the same subnet
8409 				 * as the destination, ipif_select_source gives
8410 				 * first non-deprecated interface which might be
8411 				 * on a different subnet than the gateway.
8412 				 * This is not desirable. Hence pass the dst_ire
8413 				 * source address to ipif_select_source.
8414 				 * It is sure that the destination is reachable
8415 				 * with the dst_ire source address subnet.
8416 				 * So passing dst_ire source address to
8417 				 * ipif_select_source will make sure that the
8418 				 * selected source will be on the same subnet
8419 				 * as dst_ire source address.
8420 				 */
8421 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8422 				src_ipif = ipif_select_source(dst_ill, saddr,
8423 				    zoneid);
8424 				if (src_ipif == NULL) {
8425 					if (ip_debug > 2) {
8426 						pr_addr_dbg("ip_newroute: "
8427 						    "no src for dst %s ",
8428 						    AF_INET, &dst);
8429 						printf("through interface %s\n",
8430 						    dst_ill->ill_name);
8431 					}
8432 					goto icmp_err_ret;
8433 				}
8434 			} else {
8435 				src_ipif = ire->ire_ipif;
8436 				ASSERT(src_ipif != NULL);
8437 				/* hold src_ipif for uniformity */
8438 				ipif_refhold(src_ipif);
8439 			}
8440 		}
8441 
8442 		/*
8443 		 * Assign a source address while we have the conn.
8444 		 * We can't have ip_wput_ire pick a source address when the
8445 		 * packet returns from arp since we need to look at
8446 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8447 		 * going through arp.
8448 		 *
8449 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8450 		 *	  it uses ip6i to store this information.
8451 		 */
8452 		if (ipha->ipha_src == INADDR_ANY &&
8453 		    (connp == NULL || !connp->conn_unspec_src)) {
8454 			ipha->ipha_src = src_ipif->ipif_src_addr;
8455 		}
8456 		if (ip_debug > 3) {
8457 			/* ip2dbg */
8458 			pr_addr_dbg("ip_newroute: first hop %s\n",
8459 			    AF_INET, &gw);
8460 		}
8461 		ip2dbg(("\tire type %s (%d)\n",
8462 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8463 
8464 		/*
8465 		 * The TTL of multirouted packets is bounded by the
8466 		 * ip_multirt_ttl ndd variable.
8467 		 */
8468 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8469 			/* Force TTL of multirouted packets */
8470 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8471 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8472 				ip2dbg(("ip_newroute: forcing multirt TTL "
8473 				    "to %d (was %d), dst 0x%08x\n",
8474 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8475 				    ntohl(sire->ire_addr)));
8476 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8477 			}
8478 		}
8479 		/*
8480 		 * At this point in ip_newroute(), ire is either the
8481 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8482 		 * destination or an IRE_INTERFACE type that should be used
8483 		 * to resolve an on-subnet destination or an on-subnet
8484 		 * next-hop gateway.
8485 		 *
8486 		 * In the IRE_CACHE case, we have the following :
8487 		 *
8488 		 * 1) src_ipif - used for getting a source address.
8489 		 *
8490 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8491 		 *    means packets using this IRE_CACHE will go out on
8492 		 *    dst_ill.
8493 		 *
8494 		 * 3) The IRE sire will point to the prefix that is the
8495 		 *    longest  matching route for the destination. These
8496 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8497 		 *
8498 		 *    The newly created IRE_CACHE entry for the off-subnet
8499 		 *    destination is tied to both the prefix route and the
8500 		 *    interface route used to resolve the next-hop gateway
8501 		 *    via the ire_phandle and ire_ihandle fields,
8502 		 *    respectively.
8503 		 *
8504 		 * In the IRE_INTERFACE case, we have the following :
8505 		 *
8506 		 * 1) src_ipif - used for getting a source address.
8507 		 *
8508 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8509 		 *    means packets using the IRE_CACHE that we will build
8510 		 *    here will go out on dst_ill.
8511 		 *
8512 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8513 		 *    to be created will only be tied to the IRE_INTERFACE
8514 		 *    that was derived from the ire_ihandle field.
8515 		 *
8516 		 *    If sire is non-NULL, it means the destination is
8517 		 *    off-link and we will first create the IRE_CACHE for the
8518 		 *    gateway. Next time through ip_newroute, we will create
8519 		 *    the IRE_CACHE for the final destination as described
8520 		 *    above.
8521 		 *
8522 		 * In both cases, after the current resolution has been
8523 		 * completed (or possibly initialised, in the IRE_INTERFACE
8524 		 * case), the loop may be re-entered to attempt the resolution
8525 		 * of another RTF_MULTIRT route.
8526 		 *
8527 		 * When an IRE_CACHE entry for the off-subnet destination is
8528 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8529 		 * for further processing in emission loops.
8530 		 */
8531 		save_ire = ire;
8532 		switch (ire->ire_type) {
8533 		case IRE_CACHE: {
8534 			ire_t	*ipif_ire;
8535 			mblk_t	*ire_fp_mp;
8536 
8537 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8538 			if (gw == 0)
8539 				gw = ire->ire_gateway_addr;
8540 			/*
8541 			 * We need 3 ire's to create a new cache ire for an
8542 			 * off-link destination from the cache ire of the
8543 			 * gateway.
8544 			 *
8545 			 *	1. The prefix ire 'sire' (Note that this does
8546 			 *	   not apply to the conn_nexthop_set case)
8547 			 *	2. The cache ire of the gateway 'ire'
8548 			 *	3. The interface ire 'ipif_ire'
8549 			 *
8550 			 * We have (1) and (2). We lookup (3) below.
8551 			 *
8552 			 * If there is no interface route to the gateway,
8553 			 * it is a race condition, where we found the cache
8554 			 * but the interface route has been deleted.
8555 			 */
8556 			if (ip_nexthop) {
8557 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8558 			} else {
8559 				ipif_ire =
8560 				    ire_ihandle_lookup_offlink(ire, sire);
8561 			}
8562 			if (ipif_ire == NULL) {
8563 				ip1dbg(("ip_newroute: "
8564 				    "ire_ihandle_lookup_offlink failed\n"));
8565 				goto icmp_err_ret;
8566 			}
8567 			/*
8568 			 * XXX We are using the same res_mp
8569 			 * (DL_UNITDATA_REQ) though the save_ire is not
8570 			 * pointing at the same ill.
8571 			 * This is incorrect. We need to send it up to the
8572 			 * resolver to get the right res_mp. For ethernets
8573 			 * this may be okay (ill_type == DL_ETHER).
8574 			 */
8575 			res_mp = save_ire->ire_nce->nce_res_mp;
8576 			ire_fp_mp = NULL;
8577 
8578 			/*
8579 			 * Check cached gateway IRE for any security
8580 			 * attributes; if found, associate the gateway
8581 			 * credentials group to the destination IRE.
8582 			 */
8583 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8584 				mutex_enter(&attrp->igsa_lock);
8585 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8586 					GCGRP_REFHOLD(gcgrp);
8587 				mutex_exit(&attrp->igsa_lock);
8588 			}
8589 
8590 			ire = ire_create(
8591 			    (uchar_t *)&dst,		/* dest address */
8592 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8593 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8594 			    (uchar_t *)&gw,		/* gateway address */
8595 			    NULL,
8596 			    &save_ire->ire_max_frag,
8597 			    ire_fp_mp,			/* Fast Path header */
8598 			    dst_ill->ill_rq,		/* recv-from queue */
8599 			    dst_ill->ill_wq,		/* send-to queue */
8600 			    IRE_CACHE,			/* IRE type */
8601 			    res_mp,
8602 			    src_ipif,
8603 			    in_ill,			/* incoming ill */
8604 			    (sire != NULL) ?
8605 			    sire->ire_mask : 0, 	/* Parent mask */
8606 			    (sire != NULL) ?
8607 			    sire->ire_phandle : 0,	/* Parent handle */
8608 			    ipif_ire->ire_ihandle,	/* Interface handle */
8609 			    (sire != NULL) ? (sire->ire_flags &
8610 			    (RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8611 			    (sire != NULL) ?
8612 			    &(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8613 			    NULL,
8614 			    gcgrp,
8615 			    ipst);
8616 
8617 			if (ire == NULL) {
8618 				if (gcgrp != NULL) {
8619 					GCGRP_REFRELE(gcgrp);
8620 					gcgrp = NULL;
8621 				}
8622 				ire_refrele(ipif_ire);
8623 				ire_refrele(save_ire);
8624 				break;
8625 			}
8626 
8627 			/* reference now held by IRE */
8628 			gcgrp = NULL;
8629 
8630 			ire->ire_marks |= ire_marks;
8631 
8632 			/*
8633 			 * Prevent sire and ipif_ire from getting deleted.
8634 			 * The newly created ire is tied to both of them via
8635 			 * the phandle and ihandle respectively.
8636 			 */
8637 			if (sire != NULL) {
8638 				IRB_REFHOLD(sire->ire_bucket);
8639 				/* Has it been removed already ? */
8640 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8641 					IRB_REFRELE(sire->ire_bucket);
8642 					ire_refrele(ipif_ire);
8643 					ire_refrele(save_ire);
8644 					break;
8645 				}
8646 			}
8647 
8648 			IRB_REFHOLD(ipif_ire->ire_bucket);
8649 			/* Has it been removed already ? */
8650 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8651 				IRB_REFRELE(ipif_ire->ire_bucket);
8652 				if (sire != NULL)
8653 					IRB_REFRELE(sire->ire_bucket);
8654 				ire_refrele(ipif_ire);
8655 				ire_refrele(save_ire);
8656 				break;
8657 			}
8658 
8659 			xmit_mp = first_mp;
8660 			/*
8661 			 * In the case of multirouting, a copy
8662 			 * of the packet is done before its sending.
8663 			 * The copy is used to attempt another
8664 			 * route resolution, in a next loop.
8665 			 */
8666 			if (ire->ire_flags & RTF_MULTIRT) {
8667 				copy_mp = copymsg(first_mp);
8668 				if (copy_mp != NULL) {
8669 					xmit_mp = copy_mp;
8670 					MULTIRT_DEBUG_TAG(first_mp);
8671 				}
8672 			}
8673 			ire_add_then_send(q, ire, xmit_mp);
8674 			ire_refrele(save_ire);
8675 
8676 			/* Assert that sire is not deleted yet. */
8677 			if (sire != NULL) {
8678 				ASSERT(sire->ire_ptpn != NULL);
8679 				IRB_REFRELE(sire->ire_bucket);
8680 			}
8681 
8682 			/* Assert that ipif_ire is not deleted yet. */
8683 			ASSERT(ipif_ire->ire_ptpn != NULL);
8684 			IRB_REFRELE(ipif_ire->ire_bucket);
8685 			ire_refrele(ipif_ire);
8686 
8687 			/*
8688 			 * If copy_mp is not NULL, multirouting was
8689 			 * requested. We loop to initiate a next
8690 			 * route resolution attempt, starting from sire.
8691 			 */
8692 			if (copy_mp != NULL) {
8693 				/*
8694 				 * Search for the next unresolved
8695 				 * multirt route.
8696 				 */
8697 				copy_mp = NULL;
8698 				ipif_ire = NULL;
8699 				ire = NULL;
8700 				multirt_resolve_next = B_TRUE;
8701 				continue;
8702 			}
8703 			if (sire != NULL)
8704 				ire_refrele(sire);
8705 			ipif_refrele(src_ipif);
8706 			ill_refrele(dst_ill);
8707 			return;
8708 		}
8709 		case IRE_IF_NORESOLVER: {
8710 			/*
8711 			 * We have what we need to build an IRE_CACHE.
8712 			 *
8713 			 * Create a new res_mp with the IP gateway address
8714 			 * in destination address in the DLPI hdr if the
8715 			 * physical length is exactly 4 bytes.
8716 			 */
8717 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
8718 				uchar_t *addr;
8719 
8720 				if (gw)
8721 					addr = (uchar_t *)&gw;
8722 				else
8723 					addr = (uchar_t *)&dst;
8724 
8725 				res_mp = ill_dlur_gen(addr,
8726 				    dst_ill->ill_phys_addr_length,
8727 				    dst_ill->ill_sap,
8728 				    dst_ill->ill_sap_length);
8729 
8730 				if (res_mp == NULL) {
8731 					ip1dbg(("ip_newroute: res_mp NULL\n"));
8732 					break;
8733 				}
8734 			} else if (dst_ill->ill_resolver_mp == NULL) {
8735 				ip1dbg(("ip_newroute: dst_ill %p "
8736 				    "for IF_NORESOLV ire %p has "
8737 				    "no ill_resolver_mp\n",
8738 				    (void *)dst_ill, (void *)ire));
8739 				break;
8740 			} else {
8741 				res_mp = NULL;
8742 			}
8743 
8744 			/*
8745 			 * TSol note: We are creating the ire cache for the
8746 			 * destination 'dst'. If 'dst' is offlink, going
8747 			 * through the first hop 'gw', the security attributes
8748 			 * of 'dst' must be set to point to the gateway
8749 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8750 			 * is possible that 'dst' is a potential gateway that is
8751 			 * referenced by some route that has some security
8752 			 * attributes. Thus in the former case, we need to do a
8753 			 * gcgrp_lookup of 'gw' while in the latter case we
8754 			 * need to do gcgrp_lookup of 'dst' itself.
8755 			 */
8756 			ga.ga_af = AF_INET;
8757 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8758 			    &ga.ga_addr);
8759 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8760 
8761 			ire = ire_create(
8762 			    (uchar_t *)&dst,		/* dest address */
8763 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8764 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8765 			    (uchar_t *)&gw,		/* gateway address */
8766 			    NULL,
8767 			    &save_ire->ire_max_frag,
8768 			    NULL,			/* Fast Path header */
8769 			    dst_ill->ill_rq,		/* recv-from queue */
8770 			    dst_ill->ill_wq,		/* send-to queue */
8771 			    IRE_CACHE,
8772 			    res_mp,
8773 			    src_ipif,
8774 			    in_ill,			/* Incoming ill */
8775 			    save_ire->ire_mask,		/* Parent mask */
8776 			    (sire != NULL) ?		/* Parent handle */
8777 			    sire->ire_phandle : 0,
8778 			    save_ire->ire_ihandle,	/* Interface handle */
8779 			    (sire != NULL) ? sire->ire_flags &
8780 			    (RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8781 			    &(save_ire->ire_uinfo),
8782 			    NULL,
8783 			    gcgrp,
8784 			    ipst);
8785 
8786 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN)
8787 				freeb(res_mp);
8788 
8789 			if (ire == NULL) {
8790 				if (gcgrp != NULL) {
8791 					GCGRP_REFRELE(gcgrp);
8792 					gcgrp = NULL;
8793 				}
8794 				ire_refrele(save_ire);
8795 				break;
8796 			}
8797 
8798 			/* reference now held by IRE */
8799 			gcgrp = NULL;
8800 
8801 			ire->ire_marks |= ire_marks;
8802 
8803 			/* Prevent save_ire from getting deleted */
8804 			IRB_REFHOLD(save_ire->ire_bucket);
8805 			/* Has it been removed already ? */
8806 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8807 				IRB_REFRELE(save_ire->ire_bucket);
8808 				ire_refrele(save_ire);
8809 				break;
8810 			}
8811 
8812 			/*
8813 			 * In the case of multirouting, a copy
8814 			 * of the packet is made before it is sent.
8815 			 * The copy is used in the next
8816 			 * loop to attempt another resolution.
8817 			 */
8818 			xmit_mp = first_mp;
8819 			if ((sire != NULL) &&
8820 			    (sire->ire_flags & RTF_MULTIRT)) {
8821 				copy_mp = copymsg(first_mp);
8822 				if (copy_mp != NULL) {
8823 					xmit_mp = copy_mp;
8824 					MULTIRT_DEBUG_TAG(first_mp);
8825 				}
8826 			}
8827 			ire_add_then_send(q, ire, xmit_mp);
8828 
8829 			/* Assert that it is not deleted yet. */
8830 			ASSERT(save_ire->ire_ptpn != NULL);
8831 			IRB_REFRELE(save_ire->ire_bucket);
8832 			ire_refrele(save_ire);
8833 
8834 			if (copy_mp != NULL) {
8835 				/*
8836 				 * If we found a (no)resolver, we ignore any
8837 				 * trailing top priority IRE_CACHE in further
8838 				 * loops. This ensures that we do not omit any
8839 				 * (no)resolver.
8840 				 * This IRE_CACHE, if any, will be processed
8841 				 * by another thread entering ip_newroute().
8842 				 * IRE_CACHE entries, if any, will be processed
8843 				 * by another thread entering ip_newroute(),
8844 				 * (upon resolver response, for instance).
8845 				 * This aims to force parallel multirt
8846 				 * resolutions as soon as a packet must be sent.
8847 				 * In the best case, after the tx of only one
8848 				 * packet, all reachable routes are resolved.
8849 				 * Otherwise, the resolution of all RTF_MULTIRT
8850 				 * routes would require several emissions.
8851 				 */
8852 				multirt_flags &= ~MULTIRT_CACHEGW;
8853 
8854 				/*
8855 				 * Search for the next unresolved multirt
8856 				 * route.
8857 				 */
8858 				copy_mp = NULL;
8859 				save_ire = NULL;
8860 				ire = NULL;
8861 				multirt_resolve_next = B_TRUE;
8862 				continue;
8863 			}
8864 
8865 			/*
8866 			 * Don't need sire anymore
8867 			 */
8868 			if (sire != NULL)
8869 				ire_refrele(sire);
8870 
8871 			ipif_refrele(src_ipif);
8872 			ill_refrele(dst_ill);
8873 			return;
8874 		}
8875 		case IRE_IF_RESOLVER:
8876 			/*
8877 			 * We can't build an IRE_CACHE yet, but at least we
8878 			 * found a resolver that can help.
8879 			 */
8880 			res_mp = dst_ill->ill_resolver_mp;
8881 			if (!OK_RESOLVER_MP(res_mp))
8882 				break;
8883 
8884 			/*
8885 			 * To be at this point in the code with a non-zero gw
8886 			 * means that dst is reachable through a gateway that
8887 			 * we have never resolved.  By changing dst to the gw
8888 			 * addr we resolve the gateway first.
8889 			 * When ire_add_then_send() tries to put the IP dg
8890 			 * to dst, it will reenter ip_newroute() at which
8891 			 * time we will find the IRE_CACHE for the gw and
8892 			 * create another IRE_CACHE in case IRE_CACHE above.
8893 			 */
8894 			if (gw != INADDR_ANY) {
8895 				/*
8896 				 * The source ipif that was determined above was
8897 				 * relative to the destination address, not the
8898 				 * gateway's. If src_ipif was not taken out of
8899 				 * the IRE_IF_RESOLVER entry, we'll need to call
8900 				 * ipif_select_source() again.
8901 				 */
8902 				if (src_ipif != ire->ire_ipif) {
8903 					ipif_refrele(src_ipif);
8904 					src_ipif = ipif_select_source(dst_ill,
8905 					    gw, zoneid);
8906 					if (src_ipif == NULL) {
8907 						if (ip_debug > 2) {
8908 							pr_addr_dbg(
8909 							    "ip_newroute: no "
8910 							    "src for gw %s ",
8911 							    AF_INET, &gw);
8912 							printf("through "
8913 							    "interface %s\n",
8914 							    dst_ill->ill_name);
8915 						}
8916 						goto icmp_err_ret;
8917 					}
8918 				}
8919 				save_dst = dst;
8920 				dst = gw;
8921 				gw = INADDR_ANY;
8922 			}
8923 
8924 			/*
8925 			 * We obtain a partial IRE_CACHE which we will pass
8926 			 * along with the resolver query.  When the response
8927 			 * comes back it will be there ready for us to add.
8928 			 * The ire_max_frag is atomically set under the
8929 			 * irebucket lock in ire_add_v[46].
8930 			 */
8931 
8932 			ire = ire_create_mp(
8933 			    (uchar_t *)&dst,		/* dest address */
8934 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8935 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8936 			    (uchar_t *)&gw,		/* gateway address */
8937 			    NULL,			/* no in_src_addr */
8938 			    NULL,			/* ire_max_frag */
8939 			    NULL,			/* Fast Path header */
8940 			    dst_ill->ill_rq,		/* recv-from queue */
8941 			    dst_ill->ill_wq,		/* send-to queue */
8942 			    IRE_CACHE,
8943 			    NULL,
8944 			    src_ipif,			/* Interface ipif */
8945 			    in_ill,			/* Incoming ILL */
8946 			    save_ire->ire_mask,		/* Parent mask */
8947 			    0,
8948 			    save_ire->ire_ihandle,	/* Interface handle */
8949 			    0,				/* flags if any */
8950 			    &(save_ire->ire_uinfo),
8951 			    NULL,
8952 			    NULL,
8953 			    ipst);
8954 
8955 			if (ire == NULL) {
8956 				ire_refrele(save_ire);
8957 				break;
8958 			}
8959 
8960 			if ((sire != NULL) &&
8961 			    (sire->ire_flags & RTF_MULTIRT)) {
8962 				copy_mp = copymsg(first_mp);
8963 				if (copy_mp != NULL)
8964 					MULTIRT_DEBUG_TAG(copy_mp);
8965 			}
8966 
8967 			ire->ire_marks |= ire_marks;
8968 
8969 			/*
8970 			 * Construct message chain for the resolver
8971 			 * of the form:
8972 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8973 			 * Packet could contain a IPSEC_OUT mp.
8974 			 *
8975 			 * NOTE : ire will be added later when the response
8976 			 * comes back from ARP. If the response does not
8977 			 * come back, ARP frees the packet. For this reason,
8978 			 * we can't REFHOLD the bucket of save_ire to prevent
8979 			 * deletions. We may not be able to REFRELE the bucket
8980 			 * if the response never comes back. Thus, before
8981 			 * adding the ire, ire_add_v4 will make sure that the
8982 			 * interface route does not get deleted. This is the
8983 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8984 			 * where we can always prevent deletions because of
8985 			 * the synchronous nature of adding IRES i.e
8986 			 * ire_add_then_send is called after creating the IRE.
8987 			 */
8988 			ASSERT(ire->ire_mp != NULL);
8989 			ire->ire_mp->b_cont = first_mp;
8990 			/* Have saved_mp handy, for cleanup if canput fails */
8991 			saved_mp = mp;
8992 			mp = copyb(res_mp);
8993 			if (mp == NULL) {
8994 				/* Prepare for cleanup */
8995 				mp = saved_mp; /* pkt */
8996 				ire_delete(ire); /* ire_mp */
8997 				ire = NULL;
8998 				ire_refrele(save_ire);
8999 				if (copy_mp != NULL) {
9000 					MULTIRT_DEBUG_UNTAG(copy_mp);
9001 					freemsg(copy_mp);
9002 					copy_mp = NULL;
9003 				}
9004 				break;
9005 			}
9006 			linkb(mp, ire->ire_mp);
9007 
9008 			/*
9009 			 * Fill in the source and dest addrs for the resolver.
9010 			 * NOTE: this depends on memory layouts imposed by
9011 			 * ill_init().
9012 			 */
9013 			areq = (areq_t *)mp->b_rptr;
9014 			addrp = (ipaddr_t *)((char *)areq +
9015 			    areq->areq_sender_addr_offset);
9016 			if (do_attach_ill) {
9017 				/*
9018 				 * This is bind to no failover case.
9019 				 * arp packet also must go out on attach_ill.
9020 				 */
9021 				ASSERT(ipha->ipha_src != NULL);
9022 				*addrp = ipha->ipha_src;
9023 			} else {
9024 				*addrp = save_ire->ire_src_addr;
9025 			}
9026 
9027 			ire_refrele(save_ire);
9028 			addrp = (ipaddr_t *)((char *)areq +
9029 			    areq->areq_target_addr_offset);
9030 			*addrp = dst;
9031 			/* Up to the resolver. */
9032 			if (canputnext(dst_ill->ill_rq) &&
9033 			    !(dst_ill->ill_arp_closing)) {
9034 				putnext(dst_ill->ill_rq, mp);
9035 				ire = NULL;
9036 				if (copy_mp != NULL) {
9037 					/*
9038 					 * If we found a resolver, we ignore
9039 					 * any trailing top priority IRE_CACHE
9040 					 * in the further loops. This ensures
9041 					 * that we do not omit any resolver.
9042 					 * IRE_CACHE entries, if any, will be
9043 					 * processed next time we enter
9044 					 * ip_newroute().
9045 					 */
9046 					multirt_flags &= ~MULTIRT_CACHEGW;
9047 					/*
9048 					 * Search for the next unresolved
9049 					 * multirt route.
9050 					 */
9051 					first_mp = copy_mp;
9052 					copy_mp = NULL;
9053 					/* Prepare the next resolution loop. */
9054 					mp = first_mp;
9055 					EXTRACT_PKT_MP(mp, first_mp,
9056 					    mctl_present);
9057 					if (mctl_present)
9058 						io = (ipsec_out_t *)
9059 						    first_mp->b_rptr;
9060 					ipha = (ipha_t *)mp->b_rptr;
9061 
9062 					ASSERT(sire != NULL);
9063 
9064 					dst = save_dst;
9065 					multirt_resolve_next = B_TRUE;
9066 					continue;
9067 				}
9068 
9069 				if (sire != NULL)
9070 					ire_refrele(sire);
9071 
9072 				/*
9073 				 * The response will come back in ip_wput
9074 				 * with db_type IRE_DB_TYPE.
9075 				 */
9076 				ipif_refrele(src_ipif);
9077 				ill_refrele(dst_ill);
9078 				return;
9079 			} else {
9080 				/* Prepare for cleanup */
9081 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
9082 				    mp);
9083 				mp->b_cont = NULL;
9084 				freeb(mp); /* areq */
9085 				/*
9086 				 * this is an ire that is not added to the
9087 				 * cache. ire_freemblk will handle the release
9088 				 * of any resources associated with the ire.
9089 				 */
9090 				ire_delete(ire); /* ire_mp */
9091 				mp = saved_mp; /* pkt */
9092 				ire = NULL;
9093 				if (copy_mp != NULL) {
9094 					MULTIRT_DEBUG_UNTAG(copy_mp);
9095 					freemsg(copy_mp);
9096 					copy_mp = NULL;
9097 				}
9098 				break;
9099 			}
9100 		default:
9101 			break;
9102 		}
9103 	} while (multirt_resolve_next);
9104 
9105 	ip1dbg(("ip_newroute: dropped\n"));
9106 	/* Did this packet originate externally? */
9107 	if (mp->b_prev) {
9108 		mp->b_next = NULL;
9109 		mp->b_prev = NULL;
9110 		if (in_ill != NULL) {
9111 			BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInDiscards);
9112 		} else {
9113 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
9114 		}
9115 	} else {
9116 		if (dst_ill != NULL) {
9117 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
9118 		} else {
9119 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
9120 		}
9121 	}
9122 	ASSERT(copy_mp == NULL);
9123 	MULTIRT_DEBUG_UNTAG(first_mp);
9124 	freemsg(first_mp);
9125 	if (ire != NULL)
9126 		ire_refrele(ire);
9127 	if (sire != NULL)
9128 		ire_refrele(sire);
9129 	if (src_ipif != NULL)
9130 		ipif_refrele(src_ipif);
9131 	if (dst_ill != NULL)
9132 		ill_refrele(dst_ill);
9133 	return;
9134 
9135 icmp_err_ret:
9136 	ip1dbg(("ip_newroute: no route\n"));
9137 	if (src_ipif != NULL)
9138 		ipif_refrele(src_ipif);
9139 	if (dst_ill != NULL)
9140 		ill_refrele(dst_ill);
9141 	if (sire != NULL)
9142 		ire_refrele(sire);
9143 	/* Did this packet originate externally? */
9144 	if (mp->b_prev) {
9145 		mp->b_next = NULL;
9146 		mp->b_prev = NULL;
9147 		if (in_ill != NULL) {
9148 			BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInNoRoutes);
9149 		} else {
9150 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
9151 		}
9152 		q = WR(q);
9153 	} else {
9154 		/*
9155 		 * There is no outgoing ill, so just increment the
9156 		 * system MIB.
9157 		 */
9158 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
9159 		/*
9160 		 * Since ip_wput() isn't close to finished, we fill
9161 		 * in enough of the header for credible error reporting.
9162 		 */
9163 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
9164 			/* Failed */
9165 			MULTIRT_DEBUG_UNTAG(first_mp);
9166 			freemsg(first_mp);
9167 			if (ire != NULL)
9168 				ire_refrele(ire);
9169 			return;
9170 		}
9171 	}
9172 
9173 	/*
9174 	 * At this point we will have ire only if RTF_BLACKHOLE
9175 	 * or RTF_REJECT flags are set on the IRE. It will not
9176 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9177 	 */
9178 	if (ire != NULL) {
9179 		if (ire->ire_flags & RTF_BLACKHOLE) {
9180 			ire_refrele(ire);
9181 			MULTIRT_DEBUG_UNTAG(first_mp);
9182 			freemsg(first_mp);
9183 			return;
9184 		}
9185 		ire_refrele(ire);
9186 	}
9187 	if (ip_source_routed(ipha, ipst)) {
9188 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
9189 		    zoneid, ipst);
9190 		return;
9191 	}
9192 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9193 }
9194 
9195 ip_opt_info_t zero_info;
9196 
9197 /*
9198  * IPv4 -
9199  * ip_newroute_ipif is called by ip_wput_multicast and
9200  * ip_rput_forward_multicast whenever we need to send
9201  * out a packet to a destination address for which we do not have specific
9202  * routing information. It is used when the packet will be sent out
9203  * on a specific interface. It is also called by ip_wput() when IP_XMIT_IF
9204  * socket option is set or icmp error message wants to go out on a particular
9205  * interface for a unicast packet.
9206  *
9207  * In most cases, the destination address is resolved thanks to the ipif
9208  * intrinsic resolver. However, there are some cases where the call to
9209  * ip_newroute_ipif must take into account the potential presence of
9210  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
9211  * that uses the interface. This is specified through flags,
9212  * which can be a combination of:
9213  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
9214  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
9215  *   and flags. Additionally, the packet source address has to be set to
9216  *   the specified address. The caller is thus expected to set this flag
9217  *   if the packet has no specific source address yet.
9218  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
9219  *   flag, the resulting ire will inherit the flag. All unresolved routes
9220  *   to the destination must be explored in the same call to
9221  *   ip_newroute_ipif().
9222  */
9223 static void
9224 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
9225     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
9226 {
9227 	areq_t	*areq;
9228 	ire_t	*ire = NULL;
9229 	mblk_t	*res_mp;
9230 	ipaddr_t *addrp;
9231 	mblk_t *first_mp;
9232 	ire_t	*save_ire = NULL;
9233 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
9234 	ipif_t	*src_ipif = NULL;
9235 	ushort_t ire_marks = 0;
9236 	ill_t	*dst_ill = NULL;
9237 	boolean_t mctl_present;
9238 	ipsec_out_t *io;
9239 	ipha_t *ipha;
9240 	int	ihandle = 0;
9241 	mblk_t	*saved_mp;
9242 	ire_t   *fire = NULL;
9243 	mblk_t  *copy_mp = NULL;
9244 	boolean_t multirt_resolve_next;
9245 	ipaddr_t ipha_dst;
9246 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
9247 
9248 	/*
9249 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
9250 	 * here for uniformity
9251 	 */
9252 	ipif_refhold(ipif);
9253 
9254 	/*
9255 	 * This loop is run only once in most cases.
9256 	 * We loop to resolve further routes only when the destination
9257 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
9258 	 */
9259 	do {
9260 		if (dst_ill != NULL) {
9261 			ill_refrele(dst_ill);
9262 			dst_ill = NULL;
9263 		}
9264 		if (src_ipif != NULL) {
9265 			ipif_refrele(src_ipif);
9266 			src_ipif = NULL;
9267 		}
9268 		multirt_resolve_next = B_FALSE;
9269 
9270 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9271 		    ipif->ipif_ill->ill_name));
9272 
9273 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
9274 		if (mctl_present)
9275 			io = (ipsec_out_t *)first_mp->b_rptr;
9276 
9277 		ipha = (ipha_t *)mp->b_rptr;
9278 
9279 		/*
9280 		 * Save the packet destination address, we may need it after
9281 		 * the packet has been consumed.
9282 		 */
9283 		ipha_dst = ipha->ipha_dst;
9284 
9285 		/*
9286 		 * If the interface is a pt-pt interface we look for an
9287 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9288 		 * local_address and the pt-pt destination address. Otherwise
9289 		 * we just match the local address.
9290 		 * NOTE: dst could be different than ipha->ipha_dst in case
9291 		 * of sending igmp multicast packets over a point-to-point
9292 		 * connection.
9293 		 * Thus we must be careful enough to check ipha_dst to be a
9294 		 * multicast address, otherwise it will take xmit_if path for
9295 		 * multicast packets resulting into kernel stack overflow by
9296 		 * repeated calls to ip_newroute_ipif from ire_send().
9297 		 */
9298 		if (CLASSD(ipha_dst) &&
9299 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9300 			goto err_ret;
9301 		}
9302 
9303 		/*
9304 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9305 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9306 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9307 		 * propagate its flags to the new ire.
9308 		 */
9309 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9310 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9311 			ip2dbg(("ip_newroute_ipif: "
9312 			    "ipif_lookup_multi_ire("
9313 			    "ipif %p, dst %08x) = fire %p\n",
9314 			    (void *)ipif, ntohl(dst), (void *)fire));
9315 		}
9316 
9317 		if (mctl_present && io->ipsec_out_attach_if) {
9318 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
9319 			    io->ipsec_out_ill_index, B_FALSE, ipst);
9320 
9321 			/* Failure case frees things for us. */
9322 			if (attach_ill == NULL) {
9323 				ipif_refrele(ipif);
9324 				if (fire != NULL)
9325 					ire_refrele(fire);
9326 				return;
9327 			}
9328 
9329 			/*
9330 			 * Check if we need an ire that will not be
9331 			 * looked up by anybody else i.e. HIDDEN.
9332 			 */
9333 			if (ill_is_probeonly(attach_ill)) {
9334 				ire_marks = IRE_MARK_HIDDEN;
9335 			}
9336 			/*
9337 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
9338 			 * case.
9339 			 */
9340 			dst_ill = ipif->ipif_ill;
9341 			/* attach_ill has been refheld by ip_grab_attach_ill */
9342 			ASSERT(dst_ill == attach_ill);
9343 		} else {
9344 			/*
9345 			 * If this is set by IP_XMIT_IF, then make sure that
9346 			 * ipif is pointing to the same ill as the IP_XMIT_IF
9347 			 * specified ill.
9348 			 */
9349 			ASSERT((connp == NULL) ||
9350 			    (connp->conn_xmit_if_ill == NULL) ||
9351 			    (connp->conn_xmit_if_ill == ipif->ipif_ill));
9352 			/*
9353 			 * If the interface belongs to an interface group,
9354 			 * make sure the next possible interface in the group
9355 			 * is used.  This encourages load spreading among
9356 			 * peers in an interface group.
9357 			 * Note: load spreading is disabled for RTF_MULTIRT
9358 			 * routes.
9359 			 */
9360 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9361 			    (fire->ire_flags & RTF_MULTIRT)) {
9362 				/*
9363 				 * Don't perform outbound load spreading
9364 				 * in the case of an RTF_MULTIRT issued route,
9365 				 * we actually typically want to replicate
9366 				 * outgoing packets through particular
9367 				 * interfaces.
9368 				 */
9369 				dst_ill = ipif->ipif_ill;
9370 				ill_refhold(dst_ill);
9371 			} else {
9372 				dst_ill = ip_newroute_get_dst_ill(
9373 				    ipif->ipif_ill);
9374 			}
9375 			if (dst_ill == NULL) {
9376 				if (ip_debug > 2) {
9377 					pr_addr_dbg("ip_newroute_ipif: "
9378 					    "no dst ill for dst %s\n",
9379 					    AF_INET, &dst);
9380 				}
9381 				goto err_ret;
9382 			}
9383 		}
9384 
9385 		/*
9386 		 * Pick a source address preferring non-deprecated ones.
9387 		 * Unlike ip_newroute, we don't do any source address
9388 		 * selection here since for multicast it really does not help
9389 		 * in inbound load spreading as in the unicast case.
9390 		 */
9391 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9392 		    (fire->ire_flags & RTF_SETSRC)) {
9393 			/*
9394 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9395 			 * on that interface. This ire has RTF_SETSRC flag, so
9396 			 * the source address of the packet must be changed.
9397 			 * Check that the ipif matching the requested source
9398 			 * address still exists.
9399 			 */
9400 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9401 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9402 		}
9403 		if (((ipif->ipif_flags & IPIF_DEPRECATED) ||
9404 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9405 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9406 		    (src_ipif == NULL)) {
9407 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9408 			if (src_ipif == NULL) {
9409 				if (ip_debug > 2) {
9410 					/* ip1dbg */
9411 					pr_addr_dbg("ip_newroute_ipif: "
9412 					    "no src for dst %s",
9413 					    AF_INET, &dst);
9414 				}
9415 				ip1dbg((" through interface %s\n",
9416 				    dst_ill->ill_name));
9417 				goto err_ret;
9418 			}
9419 			ipif_refrele(ipif);
9420 			ipif = src_ipif;
9421 			ipif_refhold(ipif);
9422 		}
9423 		if (src_ipif == NULL) {
9424 			src_ipif = ipif;
9425 			ipif_refhold(src_ipif);
9426 		}
9427 
9428 		/*
9429 		 * Assign a source address while we have the conn.
9430 		 * We can't have ip_wput_ire pick a source address when the
9431 		 * packet returns from arp since conn_unspec_src might be set
9432 		 * and we loose the conn when going through arp.
9433 		 */
9434 		if (ipha->ipha_src == INADDR_ANY &&
9435 		    (connp == NULL || !connp->conn_unspec_src)) {
9436 			ipha->ipha_src = src_ipif->ipif_src_addr;
9437 		}
9438 
9439 		/*
9440 		 * In case of IP_XMIT_IF, it is possible that the outgoing
9441 		 * interface does not have an interface ire.
9442 		 * Example: Thousands of mobileip PPP interfaces to mobile
9443 		 * nodes. We don't want to create interface ires because
9444 		 * packets from other mobile nodes must not take the route
9445 		 * via interface ires to the visiting mobile node without
9446 		 * going through the home agent, in absence of mobileip
9447 		 * route optimization.
9448 		 */
9449 		if (CLASSD(ipha_dst) && (connp == NULL ||
9450 		    connp->conn_xmit_if_ill == NULL) &&
9451 		    infop->ip_opt_ill_index == 0) {
9452 			/* ipif_to_ire returns an held ire */
9453 			ire = ipif_to_ire(ipif);
9454 			if (ire == NULL)
9455 				goto err_ret;
9456 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9457 				goto err_ret;
9458 			/*
9459 			 * ihandle is needed when the ire is added to
9460 			 * cache table.
9461 			 */
9462 			save_ire = ire;
9463 			ihandle = save_ire->ire_ihandle;
9464 
9465 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9466 			    "flags %04x\n",
9467 			    (void *)ire, (void *)ipif, flags));
9468 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9469 			    (fire->ire_flags & RTF_MULTIRT)) {
9470 				/*
9471 				 * As requested by flags, an IRE_OFFSUBNET was
9472 				 * looked up on that interface. This ire has
9473 				 * RTF_MULTIRT flag, so the resolution loop will
9474 				 * be re-entered to resolve additional routes on
9475 				 * other interfaces. For that purpose, a copy of
9476 				 * the packet is performed at this point.
9477 				 */
9478 				fire->ire_last_used_time = lbolt;
9479 				copy_mp = copymsg(first_mp);
9480 				if (copy_mp) {
9481 					MULTIRT_DEBUG_TAG(copy_mp);
9482 				}
9483 			}
9484 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9485 			    (fire->ire_flags & RTF_SETSRC)) {
9486 				/*
9487 				 * As requested by flags, an IRE_OFFSUBET was
9488 				 * looked up on that interface. This ire has
9489 				 * RTF_SETSRC flag, so the source address of the
9490 				 * packet must be changed.
9491 				 */
9492 				ipha->ipha_src = fire->ire_src_addr;
9493 			}
9494 		} else {
9495 			ASSERT((connp == NULL) ||
9496 			    (connp->conn_xmit_if_ill != NULL) ||
9497 			    (connp->conn_dontroute) ||
9498 			    infop->ip_opt_ill_index != 0);
9499 			/*
9500 			 * The only ways we can come here are:
9501 			 * 1) IP_XMIT_IF socket option is set
9502 			 * 2) ICMP error message generated from
9503 			 *    ip_mrtun_forward() routine and it needs
9504 			 *    to go through the specified ill.
9505 			 * 3) SO_DONTROUTE socket option is set
9506 			 * 4) IP_PKTINFO option is passed in as ancillary data.
9507 			 * In all cases, the new ire will not be added
9508 			 * into cache table.
9509 			 */
9510 			ire_marks |= IRE_MARK_NOADD;
9511 		}
9512 
9513 		switch (ipif->ipif_net_type) {
9514 		case IRE_IF_NORESOLVER: {
9515 			/* We have what we need to build an IRE_CACHE. */
9516 			mblk_t	*res_mp;
9517 
9518 			/*
9519 			 * Create a new res_mp with the
9520 			 * IP gateway address as destination address in the
9521 			 * DLPI hdr if the physical length is exactly 4 bytes.
9522 			 */
9523 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
9524 				res_mp = ill_dlur_gen((uchar_t *)&dst,
9525 				    dst_ill->ill_phys_addr_length,
9526 				    dst_ill->ill_sap,
9527 				    dst_ill->ill_sap_length);
9528 			} else if (dst_ill->ill_resolver_mp == NULL) {
9529 				ip1dbg(("ip_newroute: dst_ill %p "
9530 				    "for IF_NORESOLV ire %p has "
9531 				    "no ill_resolver_mp\n",
9532 				    (void *)dst_ill, (void *)ire));
9533 				break;
9534 			} else {
9535 				/* use the value set in ip_ll_subnet_defaults */
9536 				res_mp = ill_dlur_gen(NULL,
9537 				    dst_ill->ill_phys_addr_length,
9538 				    dst_ill->ill_sap,
9539 				    dst_ill->ill_sap_length);
9540 			}
9541 
9542 			if (res_mp == NULL)
9543 				break;
9544 			/*
9545 			 * The new ire inherits the IRE_OFFSUBNET flags
9546 			 * and source address, if this was requested.
9547 			 */
9548 			ire = ire_create(
9549 			    (uchar_t *)&dst,		/* dest address */
9550 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9551 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9552 			    NULL,			/* gateway address */
9553 			    NULL,
9554 			    &ipif->ipif_mtu,
9555 			    NULL,			/* Fast Path header */
9556 			    dst_ill->ill_rq,		/* recv-from queue */
9557 			    dst_ill->ill_wq,		/* send-to queue */
9558 			    IRE_CACHE,
9559 			    res_mp,
9560 			    src_ipif,
9561 			    NULL,
9562 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9563 			    (fire != NULL) ?		/* Parent handle */
9564 			    fire->ire_phandle : 0,
9565 			    ihandle,			/* Interface handle */
9566 			    (fire != NULL) ?
9567 			    (fire->ire_flags &
9568 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9569 			    (save_ire == NULL ? &ire_uinfo_null :
9570 			    &save_ire->ire_uinfo),
9571 			    NULL,
9572 			    NULL,
9573 			    ipst);
9574 
9575 			freeb(res_mp);
9576 
9577 			if (ire == NULL) {
9578 				if (save_ire != NULL)
9579 					ire_refrele(save_ire);
9580 				break;
9581 			}
9582 
9583 			ire->ire_marks |= ire_marks;
9584 
9585 			/*
9586 			 * If IRE_MARK_NOADD is set then we need to convert
9587 			 * the max_fragp to a useable value now. This is
9588 			 * normally done in ire_add_v[46]. We also need to
9589 			 * associate the ire with an nce (normally would be
9590 			 * done in ip_wput_nondata()).
9591 			 *
9592 			 * Note that IRE_MARK_NOADD packets created here
9593 			 * do not have a non-null ire_mp pointer. The null
9594 			 * value of ire_bucket indicates that they were
9595 			 * never added.
9596 			 */
9597 			if (ire->ire_marks & IRE_MARK_NOADD) {
9598 				uint_t  max_frag;
9599 
9600 				max_frag = *ire->ire_max_fragp;
9601 				ire->ire_max_fragp = NULL;
9602 				ire->ire_max_frag = max_frag;
9603 
9604 				if ((ire->ire_nce = ndp_lookup_v4(
9605 				    ire_to_ill(ire),
9606 				    (ire->ire_gateway_addr != INADDR_ANY ?
9607 				    &ire->ire_gateway_addr : &ire->ire_addr),
9608 				    B_FALSE)) == NULL) {
9609 					if (save_ire != NULL)
9610 						ire_refrele(save_ire);
9611 					break;
9612 				}
9613 				ASSERT(ire->ire_nce->nce_state ==
9614 				    ND_REACHABLE);
9615 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9616 			}
9617 
9618 			/* Prevent save_ire from getting deleted */
9619 			if (save_ire != NULL) {
9620 				IRB_REFHOLD(save_ire->ire_bucket);
9621 				/* Has it been removed already ? */
9622 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9623 					IRB_REFRELE(save_ire->ire_bucket);
9624 					ire_refrele(save_ire);
9625 					break;
9626 				}
9627 			}
9628 
9629 			ire_add_then_send(q, ire, first_mp);
9630 
9631 			/* Assert that save_ire is not deleted yet. */
9632 			if (save_ire != NULL) {
9633 				ASSERT(save_ire->ire_ptpn != NULL);
9634 				IRB_REFRELE(save_ire->ire_bucket);
9635 				ire_refrele(save_ire);
9636 				save_ire = NULL;
9637 			}
9638 			if (fire != NULL) {
9639 				ire_refrele(fire);
9640 				fire = NULL;
9641 			}
9642 
9643 			/*
9644 			 * the resolution loop is re-entered if this
9645 			 * was requested through flags and if we
9646 			 * actually are in a multirouting case.
9647 			 */
9648 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9649 				boolean_t need_resolve =
9650 				    ire_multirt_need_resolve(ipha_dst,
9651 				    MBLK_GETLABEL(copy_mp), ipst);
9652 				if (!need_resolve) {
9653 					MULTIRT_DEBUG_UNTAG(copy_mp);
9654 					freemsg(copy_mp);
9655 					copy_mp = NULL;
9656 				} else {
9657 					/*
9658 					 * ipif_lookup_group() calls
9659 					 * ire_lookup_multi() that uses
9660 					 * ire_ftable_lookup() to find
9661 					 * an IRE_INTERFACE for the group.
9662 					 * In the multirt case,
9663 					 * ire_lookup_multi() then invokes
9664 					 * ire_multirt_lookup() to find
9665 					 * the next resolvable ire.
9666 					 * As a result, we obtain an new
9667 					 * interface, derived from the
9668 					 * next ire.
9669 					 */
9670 					ipif_refrele(ipif);
9671 					ipif = ipif_lookup_group(ipha_dst,
9672 					    zoneid, ipst);
9673 					ip2dbg(("ip_newroute_ipif: "
9674 					    "multirt dst %08x, ipif %p\n",
9675 					    htonl(dst), (void *)ipif));
9676 					if (ipif != NULL) {
9677 						mp = copy_mp;
9678 						copy_mp = NULL;
9679 						multirt_resolve_next = B_TRUE;
9680 						continue;
9681 					} else {
9682 						freemsg(copy_mp);
9683 					}
9684 				}
9685 			}
9686 			if (ipif != NULL)
9687 				ipif_refrele(ipif);
9688 			ill_refrele(dst_ill);
9689 			ipif_refrele(src_ipif);
9690 			return;
9691 		}
9692 		case IRE_IF_RESOLVER:
9693 			/*
9694 			 * We can't build an IRE_CACHE yet, but at least
9695 			 * we found a resolver that can help.
9696 			 */
9697 			res_mp = dst_ill->ill_resolver_mp;
9698 			if (!OK_RESOLVER_MP(res_mp))
9699 				break;
9700 
9701 			/*
9702 			 * We obtain a partial IRE_CACHE which we will pass
9703 			 * along with the resolver query.  When the response
9704 			 * comes back it will be there ready for us to add.
9705 			 * The new ire inherits the IRE_OFFSUBNET flags
9706 			 * and source address, if this was requested.
9707 			 * The ire_max_frag is atomically set under the
9708 			 * irebucket lock in ire_add_v[46]. Only in the
9709 			 * case of IRE_MARK_NOADD, we set it here itself.
9710 			 */
9711 			ire = ire_create_mp(
9712 			    (uchar_t *)&dst,		/* dest address */
9713 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9714 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9715 			    NULL,			/* gateway address */
9716 			    NULL,			/* no in_src_addr */
9717 			    (ire_marks & IRE_MARK_NOADD) ?
9718 			    ipif->ipif_mtu : 0,	/* max_frag */
9719 			    NULL,			/* Fast path header */
9720 			    dst_ill->ill_rq,		/* recv-from queue */
9721 			    dst_ill->ill_wq,		/* send-to queue */
9722 			    IRE_CACHE,
9723 			    NULL,	/* let ire_nce_init figure res_mp out */
9724 			    src_ipif,
9725 			    NULL,
9726 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9727 			    (fire != NULL) ?		/* Parent handle */
9728 			    fire->ire_phandle : 0,
9729 			    ihandle,			/* Interface handle */
9730 			    (fire != NULL) ?		/* flags if any */
9731 			    (fire->ire_flags &
9732 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9733 			    (save_ire == NULL ? &ire_uinfo_null :
9734 			    &save_ire->ire_uinfo),
9735 			    NULL,
9736 			    NULL,
9737 			    ipst);
9738 
9739 			if (save_ire != NULL) {
9740 				ire_refrele(save_ire);
9741 				save_ire = NULL;
9742 			}
9743 			if (ire == NULL)
9744 				break;
9745 
9746 			ire->ire_marks |= ire_marks;
9747 			/*
9748 			 * Construct message chain for the resolver of the
9749 			 * form:
9750 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9751 			 *
9752 			 * NOTE : ire will be added later when the response
9753 			 * comes back from ARP. If the response does not
9754 			 * come back, ARP frees the packet. For this reason,
9755 			 * we can't REFHOLD the bucket of save_ire to prevent
9756 			 * deletions. We may not be able to REFRELE the
9757 			 * bucket if the response never comes back.
9758 			 * Thus, before adding the ire, ire_add_v4 will make
9759 			 * sure that the interface route does not get deleted.
9760 			 * This is the only case unlike ip_newroute_v6,
9761 			 * ip_newroute_ipif_v6 where we can always prevent
9762 			 * deletions because ire_add_then_send is called after
9763 			 * creating the IRE.
9764 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9765 			 * does not add this IRE into the IRE CACHE.
9766 			 */
9767 			ASSERT(ire->ire_mp != NULL);
9768 			ire->ire_mp->b_cont = first_mp;
9769 			/* Have saved_mp handy, for cleanup if canput fails */
9770 			saved_mp = mp;
9771 			mp = copyb(res_mp);
9772 			if (mp == NULL) {
9773 				/* Prepare for cleanup */
9774 				mp = saved_mp; /* pkt */
9775 				ire_delete(ire); /* ire_mp */
9776 				ire = NULL;
9777 				if (copy_mp != NULL) {
9778 					MULTIRT_DEBUG_UNTAG(copy_mp);
9779 					freemsg(copy_mp);
9780 					copy_mp = NULL;
9781 				}
9782 				break;
9783 			}
9784 			linkb(mp, ire->ire_mp);
9785 
9786 			/*
9787 			 * Fill in the source and dest addrs for the resolver.
9788 			 * NOTE: this depends on memory layouts imposed by
9789 			 * ill_init().
9790 			 */
9791 			areq = (areq_t *)mp->b_rptr;
9792 			addrp = (ipaddr_t *)((char *)areq +
9793 			    areq->areq_sender_addr_offset);
9794 			*addrp = ire->ire_src_addr;
9795 			addrp = (ipaddr_t *)((char *)areq +
9796 			    areq->areq_target_addr_offset);
9797 			*addrp = dst;
9798 			/* Up to the resolver. */
9799 			if (canputnext(dst_ill->ill_rq) &&
9800 			    !(dst_ill->ill_arp_closing)) {
9801 				putnext(dst_ill->ill_rq, mp);
9802 				/*
9803 				 * The response will come back in ip_wput
9804 				 * with db_type IRE_DB_TYPE.
9805 				 */
9806 			} else {
9807 				mp->b_cont = NULL;
9808 				freeb(mp); /* areq */
9809 				ire_delete(ire); /* ire_mp */
9810 				saved_mp->b_next = NULL;
9811 				saved_mp->b_prev = NULL;
9812 				freemsg(first_mp); /* pkt */
9813 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9814 			}
9815 
9816 			if (fire != NULL) {
9817 				ire_refrele(fire);
9818 				fire = NULL;
9819 			}
9820 
9821 
9822 			/*
9823 			 * The resolution loop is re-entered if this was
9824 			 * requested through flags and we actually are
9825 			 * in a multirouting case.
9826 			 */
9827 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9828 				boolean_t need_resolve =
9829 				    ire_multirt_need_resolve(ipha_dst,
9830 				    MBLK_GETLABEL(copy_mp), ipst);
9831 				if (!need_resolve) {
9832 					MULTIRT_DEBUG_UNTAG(copy_mp);
9833 					freemsg(copy_mp);
9834 					copy_mp = NULL;
9835 				} else {
9836 					/*
9837 					 * ipif_lookup_group() calls
9838 					 * ire_lookup_multi() that uses
9839 					 * ire_ftable_lookup() to find
9840 					 * an IRE_INTERFACE for the group.
9841 					 * In the multirt case,
9842 					 * ire_lookup_multi() then invokes
9843 					 * ire_multirt_lookup() to find
9844 					 * the next resolvable ire.
9845 					 * As a result, we obtain an new
9846 					 * interface, derived from the
9847 					 * next ire.
9848 					 */
9849 					ipif_refrele(ipif);
9850 					ipif = ipif_lookup_group(ipha_dst,
9851 					    zoneid, ipst);
9852 					if (ipif != NULL) {
9853 						mp = copy_mp;
9854 						copy_mp = NULL;
9855 						multirt_resolve_next = B_TRUE;
9856 						continue;
9857 					} else {
9858 						freemsg(copy_mp);
9859 					}
9860 				}
9861 			}
9862 			if (ipif != NULL)
9863 				ipif_refrele(ipif);
9864 			ill_refrele(dst_ill);
9865 			ipif_refrele(src_ipif);
9866 			return;
9867 		default:
9868 			break;
9869 		}
9870 	} while (multirt_resolve_next);
9871 
9872 err_ret:
9873 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9874 	if (fire != NULL)
9875 		ire_refrele(fire);
9876 	ipif_refrele(ipif);
9877 	/* Did this packet originate externally? */
9878 	if (dst_ill != NULL)
9879 		ill_refrele(dst_ill);
9880 	if (src_ipif != NULL)
9881 		ipif_refrele(src_ipif);
9882 	if (mp->b_prev || mp->b_next) {
9883 		mp->b_next = NULL;
9884 		mp->b_prev = NULL;
9885 	} else {
9886 		/*
9887 		 * Since ip_wput() isn't close to finished, we fill
9888 		 * in enough of the header for credible error reporting.
9889 		 */
9890 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9891 			/* Failed */
9892 			freemsg(first_mp);
9893 			if (ire != NULL)
9894 				ire_refrele(ire);
9895 			return;
9896 		}
9897 	}
9898 	/*
9899 	 * At this point we will have ire only if RTF_BLACKHOLE
9900 	 * or RTF_REJECT flags are set on the IRE. It will not
9901 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9902 	 */
9903 	if (ire != NULL) {
9904 		if (ire->ire_flags & RTF_BLACKHOLE) {
9905 			ire_refrele(ire);
9906 			freemsg(first_mp);
9907 			return;
9908 		}
9909 		ire_refrele(ire);
9910 	}
9911 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9912 }
9913 
9914 /* Name/Value Table Lookup Routine */
9915 char *
9916 ip_nv_lookup(nv_t *nv, int value)
9917 {
9918 	if (!nv)
9919 		return (NULL);
9920 	for (; nv->nv_name; nv++) {
9921 		if (nv->nv_value == value)
9922 			return (nv->nv_name);
9923 	}
9924 	return ("unknown");
9925 }
9926 
9927 /*
9928  * This is a module open, i.e. this is a control stream for access
9929  * to a DLPI device.  We allocate an ill_t as the instance data in
9930  * this case.
9931  */
9932 int
9933 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9934 {
9935 	ill_t	*ill;
9936 	int	err;
9937 	zoneid_t zoneid;
9938 	netstack_t *ns;
9939 	ip_stack_t *ipst;
9940 
9941 	/*
9942 	 * Prevent unprivileged processes from pushing IP so that
9943 	 * they can't send raw IP.
9944 	 */
9945 	if (secpolicy_net_rawaccess(credp) != 0)
9946 		return (EPERM);
9947 
9948 	ns = netstack_find_by_cred(credp);
9949 	ASSERT(ns != NULL);
9950 	ipst = ns->netstack_ip;
9951 	ASSERT(ipst != NULL);
9952 
9953 	/*
9954 	 * For exclusive stacks we set the zoneid to zero
9955 	 * to make IP operate as if in the global zone.
9956 	 */
9957 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9958 		zoneid = GLOBAL_ZONEID;
9959 	else
9960 		zoneid = crgetzoneid(credp);
9961 
9962 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9963 	q->q_ptr = WR(q)->q_ptr = ill;
9964 	ill->ill_ipst = ipst;
9965 	ill->ill_zoneid = zoneid;
9966 
9967 	/*
9968 	 * ill_init initializes the ill fields and then sends down
9969 	 * down a DL_INFO_REQ after calling qprocson.
9970 	 */
9971 	err = ill_init(q, ill);
9972 	if (err != 0) {
9973 		mi_free(ill);
9974 		netstack_rele(ipst->ips_netstack);
9975 		q->q_ptr = NULL;
9976 		WR(q)->q_ptr = NULL;
9977 		return (err);
9978 	}
9979 
9980 	/* ill_init initializes the ipsq marking this thread as writer */
9981 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
9982 	/* Wait for the DL_INFO_ACK */
9983 	mutex_enter(&ill->ill_lock);
9984 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9985 		/*
9986 		 * Return value of 0 indicates a pending signal.
9987 		 */
9988 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9989 		if (err == 0) {
9990 			mutex_exit(&ill->ill_lock);
9991 			(void) ip_close(q, 0);
9992 			return (EINTR);
9993 		}
9994 	}
9995 	mutex_exit(&ill->ill_lock);
9996 
9997 	/*
9998 	 * ip_rput_other could have set an error  in ill_error on
9999 	 * receipt of M_ERROR.
10000 	 */
10001 
10002 	err = ill->ill_error;
10003 	if (err != 0) {
10004 		(void) ip_close(q, 0);
10005 		return (err);
10006 	}
10007 
10008 	ill->ill_credp = credp;
10009 	crhold(credp);
10010 
10011 	mutex_enter(&ipst->ips_ip_mi_lock);
10012 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
10013 	    credp);
10014 	mutex_exit(&ipst->ips_ip_mi_lock);
10015 	if (err) {
10016 		(void) ip_close(q, 0);
10017 		return (err);
10018 	}
10019 	return (0);
10020 }
10021 
10022 /* IP open routine. */
10023 int
10024 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
10025 {
10026 	conn_t 		*connp;
10027 	major_t		maj;
10028 	zoneid_t	zoneid;
10029 	netstack_t	*ns;
10030 	ip_stack_t	*ipst;
10031 
10032 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
10033 
10034 	/* Allow reopen. */
10035 	if (q->q_ptr != NULL)
10036 		return (0);
10037 
10038 	if (sflag & MODOPEN) {
10039 		/* This is a module open */
10040 		return (ip_modopen(q, devp, flag, sflag, credp));
10041 	}
10042 
10043 	ns = netstack_find_by_cred(credp);
10044 	ASSERT(ns != NULL);
10045 	ipst = ns->netstack_ip;
10046 	ASSERT(ipst != NULL);
10047 
10048 	/*
10049 	 * For exclusive stacks we set the zoneid to zero
10050 	 * to make IP operate as if in the global zone.
10051 	 */
10052 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
10053 		zoneid = GLOBAL_ZONEID;
10054 	else
10055 		zoneid = crgetzoneid(credp);
10056 
10057 	/*
10058 	 * We are opening as a device. This is an IP client stream, and we
10059 	 * allocate an conn_t as the instance data.
10060 	 */
10061 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
10062 
10063 	/*
10064 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
10065 	 * done by netstack_find_by_cred()
10066 	 */
10067 	netstack_rele(ipst->ips_netstack);
10068 
10069 	connp->conn_zoneid = zoneid;
10070 
10071 	connp->conn_upq = q;
10072 	q->q_ptr = WR(q)->q_ptr = connp;
10073 
10074 	if (flag & SO_SOCKSTR)
10075 		connp->conn_flags |= IPCL_SOCKET;
10076 
10077 	/* Minor tells us which /dev entry was opened */
10078 	if (geteminor(*devp) == IPV6_MINOR) {
10079 		connp->conn_flags |= IPCL_ISV6;
10080 		connp->conn_af_isv6 = B_TRUE;
10081 		ip_setqinfo(q, geteminor(*devp), B_FALSE, ipst);
10082 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
10083 	} else {
10084 		connp->conn_af_isv6 = B_FALSE;
10085 		connp->conn_pkt_isv6 = B_FALSE;
10086 	}
10087 
10088 	if ((connp->conn_dev = inet_minor_alloc(ip_minor_arena)) == 0) {
10089 		/* CONN_DEC_REF takes care of netstack_rele() */
10090 		q->q_ptr = WR(q)->q_ptr = NULL;
10091 		CONN_DEC_REF(connp);
10092 		return (EBUSY);
10093 	}
10094 
10095 	maj = getemajor(*devp);
10096 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
10097 
10098 	/*
10099 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
10100 	 */
10101 	connp->conn_cred = credp;
10102 	crhold(connp->conn_cred);
10103 
10104 	/*
10105 	 * If the caller has the process-wide flag set, then default to MAC
10106 	 * exempt mode.  This allows read-down to unlabeled hosts.
10107 	 */
10108 	if (getpflags(NET_MAC_AWARE, credp) != 0)
10109 		connp->conn_mac_exempt = B_TRUE;
10110 
10111 	/*
10112 	 * This should only happen for ndd, netstat, raw socket or other SCTP
10113 	 * administrative ops.  In these cases, we just need a normal conn_t
10114 	 * with ulp set to IPPROTO_SCTP.  All other ops are trapped and
10115 	 * an error will be returned.
10116 	 */
10117 	if (maj != SCTP_MAJ && maj != SCTP6_MAJ) {
10118 		connp->conn_rq = q;
10119 		connp->conn_wq = WR(q);
10120 	} else {
10121 		connp->conn_ulp = IPPROTO_SCTP;
10122 		connp->conn_rq = connp->conn_wq = NULL;
10123 	}
10124 	/* Non-zero default values */
10125 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
10126 
10127 	/*
10128 	 * Make the conn globally visible to walkers
10129 	 */
10130 	mutex_enter(&connp->conn_lock);
10131 	connp->conn_state_flags &= ~CONN_INCIPIENT;
10132 	mutex_exit(&connp->conn_lock);
10133 	ASSERT(connp->conn_ref == 1);
10134 
10135 	qprocson(q);
10136 
10137 	return (0);
10138 }
10139 
10140 /*
10141  * Change q_qinfo based on the value of isv6.
10142  * This can not called on an ill queue.
10143  * Note that there is no race since either q_qinfo works for conn queues - it
10144  * is just an optimization to enter the best wput routine directly.
10145  */
10146 void
10147 ip_setqinfo(queue_t *q, minor_t minor, boolean_t bump_mib, ip_stack_t *ipst)
10148 {
10149 	ASSERT(q->q_flag & QREADR);
10150 	ASSERT(WR(q)->q_next == NULL);
10151 	ASSERT(q->q_ptr != NULL);
10152 
10153 	if (minor == IPV6_MINOR)  {
10154 		if (bump_mib) {
10155 			BUMP_MIB(&ipst->ips_ip6_mib,
10156 			    ipIfStatsOutSwitchIPVersion);
10157 		}
10158 		q->q_qinfo = &rinit_ipv6;
10159 		WR(q)->q_qinfo = &winit_ipv6;
10160 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_TRUE;
10161 	} else {
10162 		if (bump_mib) {
10163 			BUMP_MIB(&ipst->ips_ip_mib,
10164 			    ipIfStatsOutSwitchIPVersion);
10165 		}
10166 		q->q_qinfo = &iprinit;
10167 		WR(q)->q_qinfo = &ipwinit;
10168 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_FALSE;
10169 	}
10170 
10171 }
10172 
10173 /*
10174  * See if IPsec needs loading because of the options in mp.
10175  */
10176 static boolean_t
10177 ipsec_opt_present(mblk_t *mp)
10178 {
10179 	uint8_t *optcp, *next_optcp, *opt_endcp;
10180 	struct opthdr *opt;
10181 	struct T_opthdr *topt;
10182 	int opthdr_len;
10183 	t_uscalar_t optname, optlevel;
10184 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
10185 	ipsec_req_t *ipsr;
10186 
10187 	/*
10188 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
10189 	 * return TRUE.
10190 	 */
10191 
10192 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
10193 	opt_endcp = optcp + tor->OPT_length;
10194 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
10195 		opthdr_len = sizeof (struct T_opthdr);
10196 	} else {		/* O_OPTMGMT_REQ */
10197 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
10198 		opthdr_len = sizeof (struct opthdr);
10199 	}
10200 	for (; optcp < opt_endcp; optcp = next_optcp) {
10201 		if (optcp + opthdr_len > opt_endcp)
10202 			return (B_FALSE);	/* Not enough option header. */
10203 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
10204 			topt = (struct T_opthdr *)optcp;
10205 			optlevel = topt->level;
10206 			optname = topt->name;
10207 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
10208 		} else {
10209 			opt = (struct opthdr *)optcp;
10210 			optlevel = opt->level;
10211 			optname = opt->name;
10212 			next_optcp = optcp + opthdr_len +
10213 			    _TPI_ALIGN_OPT(opt->len);
10214 		}
10215 		if ((next_optcp < optcp) || /* wraparound pointer space */
10216 		    ((next_optcp >= opt_endcp) && /* last option bad len */
10217 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
10218 			return (B_FALSE); /* bad option buffer */
10219 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
10220 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
10221 			/*
10222 			 * Check to see if it's an all-bypass or all-zeroes
10223 			 * IPsec request.  Don't bother loading IPsec if
10224 			 * the socket doesn't want to use it.  (A good example
10225 			 * is a bypass request.)
10226 			 *
10227 			 * Basically, if any of the non-NEVER bits are set,
10228 			 * load IPsec.
10229 			 */
10230 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
10231 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
10232 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
10233 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
10234 			    != 0)
10235 				return (B_TRUE);
10236 		}
10237 	}
10238 	return (B_FALSE);
10239 }
10240 
10241 /*
10242  * If conn is is waiting for ipsec to finish loading, kick it.
10243  */
10244 /* ARGSUSED */
10245 static void
10246 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
10247 {
10248 	t_scalar_t	optreq_prim;
10249 	mblk_t		*mp;
10250 	cred_t		*cr;
10251 	int		err = 0;
10252 
10253 	/*
10254 	 * This function is called, after ipsec loading is complete.
10255 	 * Since IP checks exclusively and atomically (i.e it prevents
10256 	 * ipsec load from completing until ip_optcom_req completes)
10257 	 * whether ipsec load is complete, there cannot be a race with IP
10258 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
10259 	 */
10260 	mutex_enter(&connp->conn_lock);
10261 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
10262 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
10263 		mp = connp->conn_ipsec_opt_mp;
10264 		connp->conn_ipsec_opt_mp = NULL;
10265 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
10266 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
10267 		mutex_exit(&connp->conn_lock);
10268 
10269 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
10270 
10271 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
10272 		if (optreq_prim == T_OPTMGMT_REQ) {
10273 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10274 			    &ip_opt_obj);
10275 		} else {
10276 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
10277 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10278 			    &ip_opt_obj);
10279 		}
10280 		if (err != EINPROGRESS)
10281 			CONN_OPER_PENDING_DONE(connp);
10282 		return;
10283 	}
10284 	mutex_exit(&connp->conn_lock);
10285 }
10286 
10287 /*
10288  * Called from the ipsec_loader thread, outside any perimeter, to tell
10289  * ip qenable any of the queues waiting for the ipsec loader to
10290  * complete.
10291  */
10292 void
10293 ip_ipsec_load_complete(ipsec_stack_t *ipss)
10294 {
10295 	netstack_t *ns = ipss->ipsec_netstack;
10296 
10297 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
10298 }
10299 
10300 /*
10301  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10302  * determines the grp on which it has to become exclusive, queues the mp
10303  * and sq draining restarts the optmgmt
10304  */
10305 static boolean_t
10306 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10307 {
10308 	conn_t *connp = Q_TO_CONN(q);
10309 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
10310 
10311 	/*
10312 	 * Take IPsec requests and treat them special.
10313 	 */
10314 	if (ipsec_opt_present(mp)) {
10315 		/* First check if IPsec is loaded. */
10316 		mutex_enter(&ipss->ipsec_loader_lock);
10317 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
10318 			mutex_exit(&ipss->ipsec_loader_lock);
10319 			return (B_FALSE);
10320 		}
10321 		mutex_enter(&connp->conn_lock);
10322 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10323 
10324 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10325 		connp->conn_ipsec_opt_mp = mp;
10326 		mutex_exit(&connp->conn_lock);
10327 		mutex_exit(&ipss->ipsec_loader_lock);
10328 
10329 		ipsec_loader_loadnow(ipss);
10330 		return (B_TRUE);
10331 	}
10332 	return (B_FALSE);
10333 }
10334 
10335 /*
10336  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10337  * all of them are copied to the conn_t. If the req is "zero", the policy is
10338  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10339  * fields.
10340  * We keep only the latest setting of the policy and thus policy setting
10341  * is not incremental/cumulative.
10342  *
10343  * Requests to set policies with multiple alternative actions will
10344  * go through a different API.
10345  */
10346 int
10347 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10348 {
10349 	uint_t ah_req = 0;
10350 	uint_t esp_req = 0;
10351 	uint_t se_req = 0;
10352 	ipsec_selkey_t sel;
10353 	ipsec_act_t *actp = NULL;
10354 	uint_t nact;
10355 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
10356 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
10357 	ipsec_policy_root_t *pr;
10358 	ipsec_policy_head_t *ph;
10359 	int fam;
10360 	boolean_t is_pol_reset;
10361 	int error = 0;
10362 	netstack_t	*ns = connp->conn_netstack;
10363 	ip_stack_t	*ipst = ns->netstack_ip;
10364 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10365 
10366 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10367 
10368 	/*
10369 	 * The IP_SEC_OPT option does not allow variable length parameters,
10370 	 * hence a request cannot be NULL.
10371 	 */
10372 	if (req == NULL)
10373 		return (EINVAL);
10374 
10375 	ah_req = req->ipsr_ah_req;
10376 	esp_req = req->ipsr_esp_req;
10377 	se_req = req->ipsr_self_encap_req;
10378 
10379 	/*
10380 	 * Are we dealing with a request to reset the policy (i.e.
10381 	 * zero requests).
10382 	 */
10383 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10384 	    (esp_req & REQ_MASK) == 0 &&
10385 	    (se_req & REQ_MASK) == 0);
10386 
10387 	if (!is_pol_reset) {
10388 		/*
10389 		 * If we couldn't load IPsec, fail with "protocol
10390 		 * not supported".
10391 		 * IPsec may not have been loaded for a request with zero
10392 		 * policies, so we don't fail in this case.
10393 		 */
10394 		mutex_enter(&ipss->ipsec_loader_lock);
10395 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10396 			mutex_exit(&ipss->ipsec_loader_lock);
10397 			return (EPROTONOSUPPORT);
10398 		}
10399 		mutex_exit(&ipss->ipsec_loader_lock);
10400 
10401 		/*
10402 		 * Test for valid requests. Invalid algorithms
10403 		 * need to be tested by IPSEC code because new
10404 		 * algorithms can be added dynamically.
10405 		 */
10406 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10407 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10408 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10409 			return (EINVAL);
10410 		}
10411 
10412 		/*
10413 		 * Only privileged users can issue these
10414 		 * requests.
10415 		 */
10416 		if (((ah_req & IPSEC_PREF_NEVER) ||
10417 		    (esp_req & IPSEC_PREF_NEVER) ||
10418 		    (se_req & IPSEC_PREF_NEVER)) &&
10419 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10420 			return (EPERM);
10421 		}
10422 
10423 		/*
10424 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10425 		 * are mutually exclusive.
10426 		 */
10427 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10428 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10429 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10430 			/* Both of them are set */
10431 			return (EINVAL);
10432 		}
10433 	}
10434 
10435 	mutex_enter(&connp->conn_lock);
10436 
10437 	/*
10438 	 * If we have already cached policies in ip_bind_connected*(), don't
10439 	 * let them change now. We cache policies for connections
10440 	 * whose src,dst [addr, port] is known.
10441 	 */
10442 	if (connp->conn_policy_cached) {
10443 		mutex_exit(&connp->conn_lock);
10444 		return (EINVAL);
10445 	}
10446 
10447 	/*
10448 	 * We have a zero policies, reset the connection policy if already
10449 	 * set. This will cause the connection to inherit the
10450 	 * global policy, if any.
10451 	 */
10452 	if (is_pol_reset) {
10453 		if (connp->conn_policy != NULL) {
10454 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10455 			connp->conn_policy = NULL;
10456 		}
10457 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10458 		connp->conn_in_enforce_policy = B_FALSE;
10459 		connp->conn_out_enforce_policy = B_FALSE;
10460 		mutex_exit(&connp->conn_lock);
10461 		return (0);
10462 	}
10463 
10464 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10465 	    ipst->ips_netstack);
10466 	if (ph == NULL)
10467 		goto enomem;
10468 
10469 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10470 	if (actp == NULL)
10471 		goto enomem;
10472 
10473 	/*
10474 	 * Always allocate IPv4 policy entries, since they can also
10475 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10476 	 */
10477 	bzero(&sel, sizeof (sel));
10478 	sel.ipsl_valid = IPSL_IPV4;
10479 
10480 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10481 	    ipst->ips_netstack);
10482 	if (pin4 == NULL)
10483 		goto enomem;
10484 
10485 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10486 	    ipst->ips_netstack);
10487 	if (pout4 == NULL)
10488 		goto enomem;
10489 
10490 	if (connp->conn_pkt_isv6) {
10491 		/*
10492 		 * We're looking at a v6 socket, also allocate the
10493 		 * v6-specific entries...
10494 		 */
10495 		sel.ipsl_valid = IPSL_IPV6;
10496 		pin6 = ipsec_policy_create(&sel, actp, nact,
10497 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10498 		if (pin6 == NULL)
10499 			goto enomem;
10500 
10501 		pout6 = ipsec_policy_create(&sel, actp, nact,
10502 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10503 		if (pout6 == NULL)
10504 			goto enomem;
10505 
10506 		/*
10507 		 * .. and file them away in the right place.
10508 		 */
10509 		fam = IPSEC_AF_V6;
10510 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10511 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10512 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10513 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10514 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10515 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10516 	}
10517 
10518 	ipsec_actvec_free(actp, nact);
10519 
10520 	/*
10521 	 * File the v4 policies.
10522 	 */
10523 	fam = IPSEC_AF_V4;
10524 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10525 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10526 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10527 
10528 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10529 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10530 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10531 
10532 	/*
10533 	 * If the requests need security, set enforce_policy.
10534 	 * If the requests are IPSEC_PREF_NEVER, one should
10535 	 * still set conn_out_enforce_policy so that an ipsec_out
10536 	 * gets attached in ip_wput. This is needed so that
10537 	 * for connections that we don't cache policy in ip_bind,
10538 	 * if global policy matches in ip_wput_attach_policy, we
10539 	 * don't wrongly inherit global policy. Similarly, we need
10540 	 * to set conn_in_enforce_policy also so that we don't verify
10541 	 * policy wrongly.
10542 	 */
10543 	if ((ah_req & REQ_MASK) != 0 ||
10544 	    (esp_req & REQ_MASK) != 0 ||
10545 	    (se_req & REQ_MASK) != 0) {
10546 		connp->conn_in_enforce_policy = B_TRUE;
10547 		connp->conn_out_enforce_policy = B_TRUE;
10548 		connp->conn_flags |= IPCL_CHECK_POLICY;
10549 	}
10550 
10551 	mutex_exit(&connp->conn_lock);
10552 	return (error);
10553 #undef REQ_MASK
10554 
10555 	/*
10556 	 * Common memory-allocation-failure exit path.
10557 	 */
10558 enomem:
10559 	mutex_exit(&connp->conn_lock);
10560 	if (actp != NULL)
10561 		ipsec_actvec_free(actp, nact);
10562 	if (pin4 != NULL)
10563 		IPPOL_REFRELE(pin4, ipst->ips_netstack);
10564 	if (pout4 != NULL)
10565 		IPPOL_REFRELE(pout4, ipst->ips_netstack);
10566 	if (pin6 != NULL)
10567 		IPPOL_REFRELE(pin6, ipst->ips_netstack);
10568 	if (pout6 != NULL)
10569 		IPPOL_REFRELE(pout6, ipst->ips_netstack);
10570 	return (ENOMEM);
10571 }
10572 
10573 /*
10574  * Only for options that pass in an IP addr. Currently only V4 options
10575  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10576  * So this function assumes level is IPPROTO_IP
10577  */
10578 int
10579 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10580     mblk_t *first_mp)
10581 {
10582 	ipif_t *ipif = NULL;
10583 	int error;
10584 	ill_t *ill;
10585 	int zoneid;
10586 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10587 
10588 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10589 
10590 	if (addr != INADDR_ANY || checkonly) {
10591 		ASSERT(connp != NULL);
10592 		zoneid = IPCL_ZONEID(connp);
10593 		if (option == IP_NEXTHOP) {
10594 			ipif = ipif_lookup_onlink_addr(addr,
10595 			    connp->conn_zoneid, ipst);
10596 		} else {
10597 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10598 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10599 			    &error, ipst);
10600 		}
10601 		if (ipif == NULL) {
10602 			if (error == EINPROGRESS)
10603 				return (error);
10604 			else if ((option == IP_MULTICAST_IF) ||
10605 			    (option == IP_NEXTHOP))
10606 				return (EHOSTUNREACH);
10607 			else
10608 				return (EINVAL);
10609 		} else if (checkonly) {
10610 			if (option == IP_MULTICAST_IF) {
10611 				ill = ipif->ipif_ill;
10612 				/* not supported by the virtual network iface */
10613 				if (IS_VNI(ill)) {
10614 					ipif_refrele(ipif);
10615 					return (EINVAL);
10616 				}
10617 			}
10618 			ipif_refrele(ipif);
10619 			return (0);
10620 		}
10621 		ill = ipif->ipif_ill;
10622 		mutex_enter(&connp->conn_lock);
10623 		mutex_enter(&ill->ill_lock);
10624 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10625 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10626 			mutex_exit(&ill->ill_lock);
10627 			mutex_exit(&connp->conn_lock);
10628 			ipif_refrele(ipif);
10629 			return (option == IP_MULTICAST_IF ?
10630 			    EHOSTUNREACH : EINVAL);
10631 		}
10632 	} else {
10633 		mutex_enter(&connp->conn_lock);
10634 	}
10635 
10636 	/* None of the options below are supported on the VNI */
10637 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10638 		mutex_exit(&ill->ill_lock);
10639 		mutex_exit(&connp->conn_lock);
10640 		ipif_refrele(ipif);
10641 		return (EINVAL);
10642 	}
10643 
10644 	switch (option) {
10645 	case IP_DONTFAILOVER_IF:
10646 		/*
10647 		 * This option is used by in.mpathd to ensure
10648 		 * that IPMP probe packets only go out on the
10649 		 * test interfaces. in.mpathd sets this option
10650 		 * on the non-failover interfaces.
10651 		 * For backward compatibility, this option
10652 		 * implicitly sets IP_MULTICAST_IF, as used
10653 		 * be done in bind(), so that ip_wput gets
10654 		 * this ipif to send mcast packets.
10655 		 */
10656 		if (ipif != NULL) {
10657 			ASSERT(addr != INADDR_ANY);
10658 			connp->conn_nofailover_ill = ipif->ipif_ill;
10659 			connp->conn_multicast_ipif = ipif;
10660 		} else {
10661 			ASSERT(addr == INADDR_ANY);
10662 			connp->conn_nofailover_ill = NULL;
10663 			connp->conn_multicast_ipif = NULL;
10664 		}
10665 		break;
10666 
10667 	case IP_MULTICAST_IF:
10668 		connp->conn_multicast_ipif = ipif;
10669 		break;
10670 	case IP_NEXTHOP:
10671 		connp->conn_nexthop_v4 = addr;
10672 		connp->conn_nexthop_set = B_TRUE;
10673 		break;
10674 	}
10675 
10676 	if (ipif != NULL) {
10677 		mutex_exit(&ill->ill_lock);
10678 		mutex_exit(&connp->conn_lock);
10679 		ipif_refrele(ipif);
10680 		return (0);
10681 	}
10682 	mutex_exit(&connp->conn_lock);
10683 	/* We succeded in cleared the option */
10684 	return (0);
10685 }
10686 
10687 /*
10688  * For options that pass in an ifindex specifying the ill. V6 options always
10689  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10690  */
10691 int
10692 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10693     int level, int option, mblk_t *first_mp)
10694 {
10695 	ill_t *ill = NULL;
10696 	int error = 0;
10697 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10698 
10699 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10700 	if (ifindex != 0) {
10701 		ASSERT(connp != NULL);
10702 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10703 		    first_mp, ip_restart_optmgmt, &error, ipst);
10704 		if (ill != NULL) {
10705 			if (checkonly) {
10706 				/* not supported by the virtual network iface */
10707 				if (IS_VNI(ill)) {
10708 					ill_refrele(ill);
10709 					return (EINVAL);
10710 				}
10711 				ill_refrele(ill);
10712 				return (0);
10713 			}
10714 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
10715 			    0, NULL)) {
10716 				ill_refrele(ill);
10717 				ill = NULL;
10718 				mutex_enter(&connp->conn_lock);
10719 				goto setit;
10720 			}
10721 			mutex_enter(&connp->conn_lock);
10722 			mutex_enter(&ill->ill_lock);
10723 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10724 				mutex_exit(&ill->ill_lock);
10725 				mutex_exit(&connp->conn_lock);
10726 				ill_refrele(ill);
10727 				ill = NULL;
10728 				mutex_enter(&connp->conn_lock);
10729 			}
10730 			goto setit;
10731 		} else if (error == EINPROGRESS) {
10732 			return (error);
10733 		} else {
10734 			error = 0;
10735 		}
10736 	}
10737 	mutex_enter(&connp->conn_lock);
10738 setit:
10739 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10740 
10741 	/*
10742 	 * The options below assume that the ILL (if any) transmits and/or
10743 	 * receives traffic. Neither of which is true for the virtual network
10744 	 * interface, so fail setting these on a VNI.
10745 	 */
10746 	if (IS_VNI(ill)) {
10747 		ASSERT(ill != NULL);
10748 		mutex_exit(&ill->ill_lock);
10749 		mutex_exit(&connp->conn_lock);
10750 		ill_refrele(ill);
10751 		return (EINVAL);
10752 	}
10753 
10754 	if (level == IPPROTO_IP) {
10755 		switch (option) {
10756 		case IP_BOUND_IF:
10757 			connp->conn_incoming_ill = ill;
10758 			connp->conn_outgoing_ill = ill;
10759 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10760 			    0 : ifindex;
10761 			break;
10762 
10763 		case IP_XMIT_IF:
10764 			/*
10765 			 * Similar to IP_BOUND_IF, but this only
10766 			 * determines the outgoing interface for
10767 			 * unicast packets. Also no IRE_CACHE entry
10768 			 * is added for the destination of the
10769 			 * outgoing packets. This feature is needed
10770 			 * for mobile IP.
10771 			 */
10772 			connp->conn_xmit_if_ill = ill;
10773 			connp->conn_orig_xmit_ifindex = (ill == NULL) ?
10774 			    0 : ifindex;
10775 			break;
10776 
10777 		case IP_MULTICAST_IF:
10778 			/*
10779 			 * This option is an internal special. The socket
10780 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10781 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10782 			 * specifies an ifindex and we try first on V6 ill's.
10783 			 * If we don't find one, we they try using on v4 ill's
10784 			 * intenally and we come here.
10785 			 */
10786 			if (!checkonly && ill != NULL) {
10787 				ipif_t	*ipif;
10788 				ipif = ill->ill_ipif;
10789 
10790 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10791 					mutex_exit(&ill->ill_lock);
10792 					mutex_exit(&connp->conn_lock);
10793 					ill_refrele(ill);
10794 					ill = NULL;
10795 					mutex_enter(&connp->conn_lock);
10796 				} else {
10797 					connp->conn_multicast_ipif = ipif;
10798 				}
10799 			}
10800 			break;
10801 		}
10802 	} else {
10803 		switch (option) {
10804 		case IPV6_BOUND_IF:
10805 			connp->conn_incoming_ill = ill;
10806 			connp->conn_outgoing_ill = ill;
10807 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10808 			    0 : ifindex;
10809 			break;
10810 
10811 		case IPV6_BOUND_PIF:
10812 			/*
10813 			 * Limit all transmit to this ill.
10814 			 * Unlike IPV6_BOUND_IF, using this option
10815 			 * prevents load spreading and failover from
10816 			 * happening when the interface is part of the
10817 			 * group. That's why we don't need to remember
10818 			 * the ifindex in orig_bound_ifindex as in
10819 			 * IPV6_BOUND_IF.
10820 			 */
10821 			connp->conn_outgoing_pill = ill;
10822 			break;
10823 
10824 		case IPV6_DONTFAILOVER_IF:
10825 			/*
10826 			 * This option is used by in.mpathd to ensure
10827 			 * that IPMP probe packets only go out on the
10828 			 * test interfaces. in.mpathd sets this option
10829 			 * on the non-failover interfaces.
10830 			 */
10831 			connp->conn_nofailover_ill = ill;
10832 			/*
10833 			 * For backward compatibility, this option
10834 			 * implicitly sets ip_multicast_ill as used in
10835 			 * IP_MULTICAST_IF so that ip_wput gets
10836 			 * this ipif to send mcast packets.
10837 			 */
10838 			connp->conn_multicast_ill = ill;
10839 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
10840 			    0 : ifindex;
10841 			break;
10842 
10843 		case IPV6_MULTICAST_IF:
10844 			/*
10845 			 * Set conn_multicast_ill to be the IPv6 ill.
10846 			 * Set conn_multicast_ipif to be an IPv4 ipif
10847 			 * for ifindex to make IPv4 mapped addresses
10848 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10849 			 * Even if no IPv6 ill exists for the ifindex
10850 			 * we need to check for an IPv4 ifindex in order
10851 			 * for this to work with mapped addresses. In that
10852 			 * case only set conn_multicast_ipif.
10853 			 */
10854 			if (!checkonly) {
10855 				if (ifindex == 0) {
10856 					connp->conn_multicast_ill = NULL;
10857 					connp->conn_orig_multicast_ifindex = 0;
10858 					connp->conn_multicast_ipif = NULL;
10859 				} else if (ill != NULL) {
10860 					connp->conn_multicast_ill = ill;
10861 					connp->conn_orig_multicast_ifindex =
10862 					    ifindex;
10863 				}
10864 			}
10865 			break;
10866 		}
10867 	}
10868 
10869 	if (ill != NULL) {
10870 		mutex_exit(&ill->ill_lock);
10871 		mutex_exit(&connp->conn_lock);
10872 		ill_refrele(ill);
10873 		return (0);
10874 	}
10875 	mutex_exit(&connp->conn_lock);
10876 	/*
10877 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10878 	 * locate the ill and could not set the option (ifindex != 0)
10879 	 */
10880 	return (ifindex == 0 ? 0 : EINVAL);
10881 }
10882 
10883 /* This routine sets socket options. */
10884 /* ARGSUSED */
10885 int
10886 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10887     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10888     void *dummy, cred_t *cr, mblk_t *first_mp)
10889 {
10890 	int		*i1 = (int *)invalp;
10891 	conn_t		*connp = Q_TO_CONN(q);
10892 	int		error = 0;
10893 	boolean_t	checkonly;
10894 	ire_t		*ire;
10895 	boolean_t	found;
10896 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10897 
10898 	switch (optset_context) {
10899 
10900 	case SETFN_OPTCOM_CHECKONLY:
10901 		checkonly = B_TRUE;
10902 		/*
10903 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10904 		 * inlen != 0 implies value supplied and
10905 		 * 	we have to "pretend" to set it.
10906 		 * inlen == 0 implies that there is no
10907 		 * 	value part in T_CHECK request and just validation
10908 		 * done elsewhere should be enough, we just return here.
10909 		 */
10910 		if (inlen == 0) {
10911 			*outlenp = 0;
10912 			return (0);
10913 		}
10914 		break;
10915 	case SETFN_OPTCOM_NEGOTIATE:
10916 	case SETFN_UD_NEGOTIATE:
10917 	case SETFN_CONN_NEGOTIATE:
10918 		checkonly = B_FALSE;
10919 		break;
10920 	default:
10921 		/*
10922 		 * We should never get here
10923 		 */
10924 		*outlenp = 0;
10925 		return (EINVAL);
10926 	}
10927 
10928 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10929 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10930 
10931 	/*
10932 	 * For fixed length options, no sanity check
10933 	 * of passed in length is done. It is assumed *_optcom_req()
10934 	 * routines do the right thing.
10935 	 */
10936 
10937 	switch (level) {
10938 	case SOL_SOCKET:
10939 		/*
10940 		 * conn_lock protects the bitfields, and is used to
10941 		 * set the fields atomically.
10942 		 */
10943 		switch (name) {
10944 		case SO_BROADCAST:
10945 			if (!checkonly) {
10946 				/* TODO: use value someplace? */
10947 				mutex_enter(&connp->conn_lock);
10948 				connp->conn_broadcast = *i1 ? 1 : 0;
10949 				mutex_exit(&connp->conn_lock);
10950 			}
10951 			break;	/* goto sizeof (int) option return */
10952 		case SO_USELOOPBACK:
10953 			if (!checkonly) {
10954 				/* TODO: use value someplace? */
10955 				mutex_enter(&connp->conn_lock);
10956 				connp->conn_loopback = *i1 ? 1 : 0;
10957 				mutex_exit(&connp->conn_lock);
10958 			}
10959 			break;	/* goto sizeof (int) option return */
10960 		case SO_DONTROUTE:
10961 			if (!checkonly) {
10962 				mutex_enter(&connp->conn_lock);
10963 				connp->conn_dontroute = *i1 ? 1 : 0;
10964 				mutex_exit(&connp->conn_lock);
10965 			}
10966 			break;	/* goto sizeof (int) option return */
10967 		case SO_REUSEADDR:
10968 			if (!checkonly) {
10969 				mutex_enter(&connp->conn_lock);
10970 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10971 				mutex_exit(&connp->conn_lock);
10972 			}
10973 			break;	/* goto sizeof (int) option return */
10974 		case SO_PROTOTYPE:
10975 			if (!checkonly) {
10976 				mutex_enter(&connp->conn_lock);
10977 				connp->conn_proto = *i1;
10978 				mutex_exit(&connp->conn_lock);
10979 			}
10980 			break;	/* goto sizeof (int) option return */
10981 		case SO_ALLZONES:
10982 			if (!checkonly) {
10983 				mutex_enter(&connp->conn_lock);
10984 				if (IPCL_IS_BOUND(connp)) {
10985 					mutex_exit(&connp->conn_lock);
10986 					return (EINVAL);
10987 				}
10988 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10989 				mutex_exit(&connp->conn_lock);
10990 			}
10991 			break;	/* goto sizeof (int) option return */
10992 		case SO_ANON_MLP:
10993 			if (!checkonly) {
10994 				mutex_enter(&connp->conn_lock);
10995 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10996 				mutex_exit(&connp->conn_lock);
10997 			}
10998 			break;	/* goto sizeof (int) option return */
10999 		case SO_MAC_EXEMPT:
11000 			if (secpolicy_net_mac_aware(cr) != 0 ||
11001 			    IPCL_IS_BOUND(connp))
11002 				return (EACCES);
11003 			if (!checkonly) {
11004 				mutex_enter(&connp->conn_lock);
11005 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
11006 				mutex_exit(&connp->conn_lock);
11007 			}
11008 			break;	/* goto sizeof (int) option return */
11009 		default:
11010 			/*
11011 			 * "soft" error (negative)
11012 			 * option not handled at this level
11013 			 * Note: Do not modify *outlenp
11014 			 */
11015 			return (-EINVAL);
11016 		}
11017 		break;
11018 	case IPPROTO_IP:
11019 		switch (name) {
11020 		case IP_NEXTHOP:
11021 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
11022 				return (EPERM);
11023 			/* FALLTHRU */
11024 		case IP_MULTICAST_IF:
11025 		case IP_DONTFAILOVER_IF: {
11026 			ipaddr_t addr = *i1;
11027 
11028 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
11029 			    first_mp);
11030 			if (error != 0)
11031 				return (error);
11032 			break;	/* goto sizeof (int) option return */
11033 		}
11034 
11035 		case IP_MULTICAST_TTL:
11036 			/* Recorded in transport above IP */
11037 			*outvalp = *invalp;
11038 			*outlenp = sizeof (uchar_t);
11039 			return (0);
11040 		case IP_MULTICAST_LOOP:
11041 			if (!checkonly) {
11042 				mutex_enter(&connp->conn_lock);
11043 				connp->conn_multicast_loop = *invalp ? 1 : 0;
11044 				mutex_exit(&connp->conn_lock);
11045 			}
11046 			*outvalp = *invalp;
11047 			*outlenp = sizeof (uchar_t);
11048 			return (0);
11049 		case IP_ADD_MEMBERSHIP:
11050 		case MCAST_JOIN_GROUP:
11051 		case IP_DROP_MEMBERSHIP:
11052 		case MCAST_LEAVE_GROUP: {
11053 			struct ip_mreq *mreqp;
11054 			struct group_req *greqp;
11055 			ire_t *ire;
11056 			boolean_t done = B_FALSE;
11057 			ipaddr_t group, ifaddr;
11058 			struct sockaddr_in *sin;
11059 			uint32_t *ifindexp;
11060 			boolean_t mcast_opt = B_TRUE;
11061 			mcast_record_t fmode;
11062 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
11063 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
11064 
11065 			switch (name) {
11066 			case IP_ADD_MEMBERSHIP:
11067 				mcast_opt = B_FALSE;
11068 				/* FALLTHRU */
11069 			case MCAST_JOIN_GROUP:
11070 				fmode = MODE_IS_EXCLUDE;
11071 				optfn = ip_opt_add_group;
11072 				break;
11073 
11074 			case IP_DROP_MEMBERSHIP:
11075 				mcast_opt = B_FALSE;
11076 				/* FALLTHRU */
11077 			case MCAST_LEAVE_GROUP:
11078 				fmode = MODE_IS_INCLUDE;
11079 				optfn = ip_opt_delete_group;
11080 				break;
11081 			}
11082 
11083 			if (mcast_opt) {
11084 				greqp = (struct group_req *)i1;
11085 				sin = (struct sockaddr_in *)&greqp->gr_group;
11086 				if (sin->sin_family != AF_INET) {
11087 					*outlenp = 0;
11088 					return (ENOPROTOOPT);
11089 				}
11090 				group = (ipaddr_t)sin->sin_addr.s_addr;
11091 				ifaddr = INADDR_ANY;
11092 				ifindexp = &greqp->gr_interface;
11093 			} else {
11094 				mreqp = (struct ip_mreq *)i1;
11095 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
11096 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
11097 				ifindexp = NULL;
11098 			}
11099 
11100 			/*
11101 			 * In the multirouting case, we need to replicate
11102 			 * the request on all interfaces that will take part
11103 			 * in replication.  We do so because multirouting is
11104 			 * reflective, thus we will probably receive multi-
11105 			 * casts on those interfaces.
11106 			 * The ip_multirt_apply_membership() succeeds if the
11107 			 * operation succeeds on at least one interface.
11108 			 */
11109 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
11110 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11111 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11112 			if (ire != NULL) {
11113 				if (ire->ire_flags & RTF_MULTIRT) {
11114 					error = ip_multirt_apply_membership(
11115 					    optfn, ire, connp, checkonly, group,
11116 					    fmode, INADDR_ANY, first_mp);
11117 					done = B_TRUE;
11118 				}
11119 				ire_refrele(ire);
11120 			}
11121 			if (!done) {
11122 				error = optfn(connp, checkonly, group, ifaddr,
11123 				    ifindexp, fmode, INADDR_ANY, first_mp);
11124 			}
11125 			if (error) {
11126 				/*
11127 				 * EINPROGRESS is a soft error, needs retry
11128 				 * so don't make *outlenp zero.
11129 				 */
11130 				if (error != EINPROGRESS)
11131 					*outlenp = 0;
11132 				return (error);
11133 			}
11134 			/* OK return - copy input buffer into output buffer */
11135 			if (invalp != outvalp) {
11136 				/* don't trust bcopy for identical src/dst */
11137 				bcopy(invalp, outvalp, inlen);
11138 			}
11139 			*outlenp = inlen;
11140 			return (0);
11141 		}
11142 		case IP_BLOCK_SOURCE:
11143 		case IP_UNBLOCK_SOURCE:
11144 		case IP_ADD_SOURCE_MEMBERSHIP:
11145 		case IP_DROP_SOURCE_MEMBERSHIP:
11146 		case MCAST_BLOCK_SOURCE:
11147 		case MCAST_UNBLOCK_SOURCE:
11148 		case MCAST_JOIN_SOURCE_GROUP:
11149 		case MCAST_LEAVE_SOURCE_GROUP: {
11150 			struct ip_mreq_source *imreqp;
11151 			struct group_source_req *gsreqp;
11152 			in_addr_t grp, src, ifaddr = INADDR_ANY;
11153 			uint32_t ifindex = 0;
11154 			mcast_record_t fmode;
11155 			struct sockaddr_in *sin;
11156 			ire_t *ire;
11157 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
11158 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
11159 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
11160 
11161 			switch (name) {
11162 			case IP_BLOCK_SOURCE:
11163 				mcast_opt = B_FALSE;
11164 				/* FALLTHRU */
11165 			case MCAST_BLOCK_SOURCE:
11166 				fmode = MODE_IS_EXCLUDE;
11167 				optfn = ip_opt_add_group;
11168 				break;
11169 
11170 			case IP_UNBLOCK_SOURCE:
11171 				mcast_opt = B_FALSE;
11172 				/* FALLTHRU */
11173 			case MCAST_UNBLOCK_SOURCE:
11174 				fmode = MODE_IS_EXCLUDE;
11175 				optfn = ip_opt_delete_group;
11176 				break;
11177 
11178 			case IP_ADD_SOURCE_MEMBERSHIP:
11179 				mcast_opt = B_FALSE;
11180 				/* FALLTHRU */
11181 			case MCAST_JOIN_SOURCE_GROUP:
11182 				fmode = MODE_IS_INCLUDE;
11183 				optfn = ip_opt_add_group;
11184 				break;
11185 
11186 			case IP_DROP_SOURCE_MEMBERSHIP:
11187 				mcast_opt = B_FALSE;
11188 				/* FALLTHRU */
11189 			case MCAST_LEAVE_SOURCE_GROUP:
11190 				fmode = MODE_IS_INCLUDE;
11191 				optfn = ip_opt_delete_group;
11192 				break;
11193 			}
11194 
11195 			if (mcast_opt) {
11196 				gsreqp = (struct group_source_req *)i1;
11197 				if (gsreqp->gsr_group.ss_family != AF_INET) {
11198 					*outlenp = 0;
11199 					return (ENOPROTOOPT);
11200 				}
11201 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
11202 				grp = (ipaddr_t)sin->sin_addr.s_addr;
11203 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
11204 				src = (ipaddr_t)sin->sin_addr.s_addr;
11205 				ifindex = gsreqp->gsr_interface;
11206 			} else {
11207 				imreqp = (struct ip_mreq_source *)i1;
11208 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
11209 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
11210 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
11211 			}
11212 
11213 			/*
11214 			 * In the multirouting case, we need to replicate
11215 			 * the request as noted in the mcast cases above.
11216 			 */
11217 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
11218 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11219 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11220 			if (ire != NULL) {
11221 				if (ire->ire_flags & RTF_MULTIRT) {
11222 					error = ip_multirt_apply_membership(
11223 					    optfn, ire, connp, checkonly, grp,
11224 					    fmode, src, first_mp);
11225 					done = B_TRUE;
11226 				}
11227 				ire_refrele(ire);
11228 			}
11229 			if (!done) {
11230 				error = optfn(connp, checkonly, grp, ifaddr,
11231 				    &ifindex, fmode, src, first_mp);
11232 			}
11233 			if (error != 0) {
11234 				/*
11235 				 * EINPROGRESS is a soft error, needs retry
11236 				 * so don't make *outlenp zero.
11237 				 */
11238 				if (error != EINPROGRESS)
11239 					*outlenp = 0;
11240 				return (error);
11241 			}
11242 			/* OK return - copy input buffer into output buffer */
11243 			if (invalp != outvalp) {
11244 				bcopy(invalp, outvalp, inlen);
11245 			}
11246 			*outlenp = inlen;
11247 			return (0);
11248 		}
11249 		case IP_SEC_OPT:
11250 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11251 			if (error != 0) {
11252 				*outlenp = 0;
11253 				return (error);
11254 			}
11255 			break;
11256 		case IP_HDRINCL:
11257 		case IP_OPTIONS:
11258 		case T_IP_OPTIONS:
11259 		case IP_TOS:
11260 		case T_IP_TOS:
11261 		case IP_TTL:
11262 		case IP_RECVDSTADDR:
11263 		case IP_RECVOPTS:
11264 			/* OK return - copy input buffer into output buffer */
11265 			if (invalp != outvalp) {
11266 				/* don't trust bcopy for identical src/dst */
11267 				bcopy(invalp, outvalp, inlen);
11268 			}
11269 			*outlenp = inlen;
11270 			return (0);
11271 		case IP_RECVIF:
11272 			/* Retrieve the inbound interface index */
11273 			if (!checkonly) {
11274 				mutex_enter(&connp->conn_lock);
11275 				connp->conn_recvif = *i1 ? 1 : 0;
11276 				mutex_exit(&connp->conn_lock);
11277 			}
11278 			break;	/* goto sizeof (int) option return */
11279 		case IP_RECVPKTINFO:
11280 			if (!checkonly) {
11281 				mutex_enter(&connp->conn_lock);
11282 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11283 				mutex_exit(&connp->conn_lock);
11284 			}
11285 			break;	/* goto sizeof (int) option return */
11286 		case IP_RECVSLLA:
11287 			/* Retrieve the source link layer address */
11288 			if (!checkonly) {
11289 				mutex_enter(&connp->conn_lock);
11290 				connp->conn_recvslla = *i1 ? 1 : 0;
11291 				mutex_exit(&connp->conn_lock);
11292 			}
11293 			break;	/* goto sizeof (int) option return */
11294 		case MRT_INIT:
11295 		case MRT_DONE:
11296 		case MRT_ADD_VIF:
11297 		case MRT_DEL_VIF:
11298 		case MRT_ADD_MFC:
11299 		case MRT_DEL_MFC:
11300 		case MRT_ASSERT:
11301 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
11302 				*outlenp = 0;
11303 				return (error);
11304 			}
11305 			error = ip_mrouter_set((int)name, q, checkonly,
11306 			    (uchar_t *)invalp, inlen, first_mp);
11307 			if (error) {
11308 				*outlenp = 0;
11309 				return (error);
11310 			}
11311 			/* OK return - copy input buffer into output buffer */
11312 			if (invalp != outvalp) {
11313 				/* don't trust bcopy for identical src/dst */
11314 				bcopy(invalp, outvalp, inlen);
11315 			}
11316 			*outlenp = inlen;
11317 			return (0);
11318 		case IP_BOUND_IF:
11319 		case IP_XMIT_IF:
11320 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11321 			    level, name, first_mp);
11322 			if (error != 0)
11323 				return (error);
11324 			break; 		/* goto sizeof (int) option return */
11325 
11326 		case IP_UNSPEC_SRC:
11327 			/* Allow sending with a zero source address */
11328 			if (!checkonly) {
11329 				mutex_enter(&connp->conn_lock);
11330 				connp->conn_unspec_src = *i1 ? 1 : 0;
11331 				mutex_exit(&connp->conn_lock);
11332 			}
11333 			break;	/* goto sizeof (int) option return */
11334 		default:
11335 			/*
11336 			 * "soft" error (negative)
11337 			 * option not handled at this level
11338 			 * Note: Do not modify *outlenp
11339 			 */
11340 			return (-EINVAL);
11341 		}
11342 		break;
11343 	case IPPROTO_IPV6:
11344 		switch (name) {
11345 		case IPV6_BOUND_IF:
11346 		case IPV6_BOUND_PIF:
11347 		case IPV6_DONTFAILOVER_IF:
11348 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11349 			    level, name, first_mp);
11350 			if (error != 0)
11351 				return (error);
11352 			break; 		/* goto sizeof (int) option return */
11353 
11354 		case IPV6_MULTICAST_IF:
11355 			/*
11356 			 * The only possible errors are EINPROGRESS and
11357 			 * EINVAL. EINPROGRESS will be restarted and is not
11358 			 * a hard error. We call this option on both V4 and V6
11359 			 * If both return EINVAL, then this call returns
11360 			 * EINVAL. If at least one of them succeeds we
11361 			 * return success.
11362 			 */
11363 			found = B_FALSE;
11364 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11365 			    level, name, first_mp);
11366 			if (error == EINPROGRESS)
11367 				return (error);
11368 			if (error == 0)
11369 				found = B_TRUE;
11370 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11371 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11372 			if (error == 0)
11373 				found = B_TRUE;
11374 			if (!found)
11375 				return (error);
11376 			break; 		/* goto sizeof (int) option return */
11377 
11378 		case IPV6_MULTICAST_HOPS:
11379 			/* Recorded in transport above IP */
11380 			break;	/* goto sizeof (int) option return */
11381 		case IPV6_MULTICAST_LOOP:
11382 			if (!checkonly) {
11383 				mutex_enter(&connp->conn_lock);
11384 				connp->conn_multicast_loop = *i1;
11385 				mutex_exit(&connp->conn_lock);
11386 			}
11387 			break;	/* goto sizeof (int) option return */
11388 		case IPV6_JOIN_GROUP:
11389 		case MCAST_JOIN_GROUP:
11390 		case IPV6_LEAVE_GROUP:
11391 		case MCAST_LEAVE_GROUP: {
11392 			struct ipv6_mreq *ip_mreqp;
11393 			struct group_req *greqp;
11394 			ire_t *ire;
11395 			boolean_t done = B_FALSE;
11396 			in6_addr_t groupv6;
11397 			uint32_t ifindex;
11398 			boolean_t mcast_opt = B_TRUE;
11399 			mcast_record_t fmode;
11400 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11401 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11402 
11403 			switch (name) {
11404 			case IPV6_JOIN_GROUP:
11405 				mcast_opt = B_FALSE;
11406 				/* FALLTHRU */
11407 			case MCAST_JOIN_GROUP:
11408 				fmode = MODE_IS_EXCLUDE;
11409 				optfn = ip_opt_add_group_v6;
11410 				break;
11411 
11412 			case IPV6_LEAVE_GROUP:
11413 				mcast_opt = B_FALSE;
11414 				/* FALLTHRU */
11415 			case MCAST_LEAVE_GROUP:
11416 				fmode = MODE_IS_INCLUDE;
11417 				optfn = ip_opt_delete_group_v6;
11418 				break;
11419 			}
11420 
11421 			if (mcast_opt) {
11422 				struct sockaddr_in *sin;
11423 				struct sockaddr_in6 *sin6;
11424 				greqp = (struct group_req *)i1;
11425 				if (greqp->gr_group.ss_family == AF_INET) {
11426 					sin = (struct sockaddr_in *)
11427 					    &(greqp->gr_group);
11428 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11429 					    &groupv6);
11430 				} else {
11431 					sin6 = (struct sockaddr_in6 *)
11432 					    &(greqp->gr_group);
11433 					groupv6 = sin6->sin6_addr;
11434 				}
11435 				ifindex = greqp->gr_interface;
11436 			} else {
11437 				ip_mreqp = (struct ipv6_mreq *)i1;
11438 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11439 				ifindex = ip_mreqp->ipv6mr_interface;
11440 			}
11441 			/*
11442 			 * In the multirouting case, we need to replicate
11443 			 * the request on all interfaces that will take part
11444 			 * in replication.  We do so because multirouting is
11445 			 * reflective, thus we will probably receive multi-
11446 			 * casts on those interfaces.
11447 			 * The ip_multirt_apply_membership_v6() succeeds if
11448 			 * the operation succeeds on at least one interface.
11449 			 */
11450 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11451 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11452 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11453 			if (ire != NULL) {
11454 				if (ire->ire_flags & RTF_MULTIRT) {
11455 					error = ip_multirt_apply_membership_v6(
11456 					    optfn, ire, connp, checkonly,
11457 					    &groupv6, fmode, &ipv6_all_zeros,
11458 					    first_mp);
11459 					done = B_TRUE;
11460 				}
11461 				ire_refrele(ire);
11462 			}
11463 			if (!done) {
11464 				error = optfn(connp, checkonly, &groupv6,
11465 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11466 			}
11467 			if (error) {
11468 				/*
11469 				 * EINPROGRESS is a soft error, needs retry
11470 				 * so don't make *outlenp zero.
11471 				 */
11472 				if (error != EINPROGRESS)
11473 					*outlenp = 0;
11474 				return (error);
11475 			}
11476 			/* OK return - copy input buffer into output buffer */
11477 			if (invalp != outvalp) {
11478 				/* don't trust bcopy for identical src/dst */
11479 				bcopy(invalp, outvalp, inlen);
11480 			}
11481 			*outlenp = inlen;
11482 			return (0);
11483 		}
11484 		case MCAST_BLOCK_SOURCE:
11485 		case MCAST_UNBLOCK_SOURCE:
11486 		case MCAST_JOIN_SOURCE_GROUP:
11487 		case MCAST_LEAVE_SOURCE_GROUP: {
11488 			struct group_source_req *gsreqp;
11489 			in6_addr_t v6grp, v6src;
11490 			uint32_t ifindex;
11491 			mcast_record_t fmode;
11492 			ire_t *ire;
11493 			boolean_t done = B_FALSE;
11494 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11495 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11496 
11497 			switch (name) {
11498 			case MCAST_BLOCK_SOURCE:
11499 				fmode = MODE_IS_EXCLUDE;
11500 				optfn = ip_opt_add_group_v6;
11501 				break;
11502 			case MCAST_UNBLOCK_SOURCE:
11503 				fmode = MODE_IS_EXCLUDE;
11504 				optfn = ip_opt_delete_group_v6;
11505 				break;
11506 			case MCAST_JOIN_SOURCE_GROUP:
11507 				fmode = MODE_IS_INCLUDE;
11508 				optfn = ip_opt_add_group_v6;
11509 				break;
11510 			case MCAST_LEAVE_SOURCE_GROUP:
11511 				fmode = MODE_IS_INCLUDE;
11512 				optfn = ip_opt_delete_group_v6;
11513 				break;
11514 			}
11515 
11516 			gsreqp = (struct group_source_req *)i1;
11517 			ifindex = gsreqp->gsr_interface;
11518 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11519 				struct sockaddr_in *s;
11520 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11521 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11522 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11523 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11524 			} else {
11525 				struct sockaddr_in6 *s6;
11526 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11527 				v6grp = s6->sin6_addr;
11528 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11529 				v6src = s6->sin6_addr;
11530 			}
11531 
11532 			/*
11533 			 * In the multirouting case, we need to replicate
11534 			 * the request as noted in the mcast cases above.
11535 			 */
11536 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11537 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11538 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11539 			if (ire != NULL) {
11540 				if (ire->ire_flags & RTF_MULTIRT) {
11541 					error = ip_multirt_apply_membership_v6(
11542 					    optfn, ire, connp, checkonly,
11543 					    &v6grp, fmode, &v6src, first_mp);
11544 					done = B_TRUE;
11545 				}
11546 				ire_refrele(ire);
11547 			}
11548 			if (!done) {
11549 				error = optfn(connp, checkonly, &v6grp,
11550 				    ifindex, fmode, &v6src, first_mp);
11551 			}
11552 			if (error != 0) {
11553 				/*
11554 				 * EINPROGRESS is a soft error, needs retry
11555 				 * so don't make *outlenp zero.
11556 				 */
11557 				if (error != EINPROGRESS)
11558 					*outlenp = 0;
11559 				return (error);
11560 			}
11561 			/* OK return - copy input buffer into output buffer */
11562 			if (invalp != outvalp) {
11563 				bcopy(invalp, outvalp, inlen);
11564 			}
11565 			*outlenp = inlen;
11566 			return (0);
11567 		}
11568 		case IPV6_UNICAST_HOPS:
11569 			/* Recorded in transport above IP */
11570 			break;	/* goto sizeof (int) option return */
11571 		case IPV6_UNSPEC_SRC:
11572 			/* Allow sending with a zero source address */
11573 			if (!checkonly) {
11574 				mutex_enter(&connp->conn_lock);
11575 				connp->conn_unspec_src = *i1 ? 1 : 0;
11576 				mutex_exit(&connp->conn_lock);
11577 			}
11578 			break;	/* goto sizeof (int) option return */
11579 		case IPV6_RECVPKTINFO:
11580 			if (!checkonly) {
11581 				mutex_enter(&connp->conn_lock);
11582 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11583 				mutex_exit(&connp->conn_lock);
11584 			}
11585 			break;	/* goto sizeof (int) option return */
11586 		case IPV6_RECVTCLASS:
11587 			if (!checkonly) {
11588 				if (*i1 < 0 || *i1 > 1) {
11589 					return (EINVAL);
11590 				}
11591 				mutex_enter(&connp->conn_lock);
11592 				connp->conn_ipv6_recvtclass = *i1;
11593 				mutex_exit(&connp->conn_lock);
11594 			}
11595 			break;
11596 		case IPV6_RECVPATHMTU:
11597 			if (!checkonly) {
11598 				if (*i1 < 0 || *i1 > 1) {
11599 					return (EINVAL);
11600 				}
11601 				mutex_enter(&connp->conn_lock);
11602 				connp->conn_ipv6_recvpathmtu = *i1;
11603 				mutex_exit(&connp->conn_lock);
11604 			}
11605 			break;
11606 		case IPV6_RECVHOPLIMIT:
11607 			if (!checkonly) {
11608 				mutex_enter(&connp->conn_lock);
11609 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11610 				mutex_exit(&connp->conn_lock);
11611 			}
11612 			break;	/* goto sizeof (int) option return */
11613 		case IPV6_RECVHOPOPTS:
11614 			if (!checkonly) {
11615 				mutex_enter(&connp->conn_lock);
11616 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11617 				mutex_exit(&connp->conn_lock);
11618 			}
11619 			break;	/* goto sizeof (int) option return */
11620 		case IPV6_RECVDSTOPTS:
11621 			if (!checkonly) {
11622 				mutex_enter(&connp->conn_lock);
11623 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11624 				mutex_exit(&connp->conn_lock);
11625 			}
11626 			break;	/* goto sizeof (int) option return */
11627 		case IPV6_RECVRTHDR:
11628 			if (!checkonly) {
11629 				mutex_enter(&connp->conn_lock);
11630 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11631 				mutex_exit(&connp->conn_lock);
11632 			}
11633 			break;	/* goto sizeof (int) option return */
11634 		case IPV6_RECVRTHDRDSTOPTS:
11635 			if (!checkonly) {
11636 				mutex_enter(&connp->conn_lock);
11637 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11638 				mutex_exit(&connp->conn_lock);
11639 			}
11640 			break;	/* goto sizeof (int) option return */
11641 		case IPV6_PKTINFO:
11642 			if (inlen == 0)
11643 				return (-EINVAL);	/* clearing option */
11644 			error = ip6_set_pktinfo(cr, connp,
11645 			    (struct in6_pktinfo *)invalp, first_mp);
11646 			if (error != 0)
11647 				*outlenp = 0;
11648 			else
11649 				*outlenp = inlen;
11650 			return (error);
11651 		case IPV6_NEXTHOP: {
11652 			struct sockaddr_in6 *sin6;
11653 
11654 			/* Verify that the nexthop is reachable */
11655 			if (inlen == 0)
11656 				return (-EINVAL);	/* clearing option */
11657 
11658 			sin6 = (struct sockaddr_in6 *)invalp;
11659 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11660 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11661 			    NULL, MATCH_IRE_DEFAULT, ipst);
11662 
11663 			if (ire == NULL) {
11664 				*outlenp = 0;
11665 				return (EHOSTUNREACH);
11666 			}
11667 			ire_refrele(ire);
11668 			return (-EINVAL);
11669 		}
11670 		case IPV6_SEC_OPT:
11671 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11672 			if (error != 0) {
11673 				*outlenp = 0;
11674 				return (error);
11675 			}
11676 			break;
11677 		case IPV6_SRC_PREFERENCES: {
11678 			/*
11679 			 * This is implemented strictly in the ip module
11680 			 * (here and in tcp_opt_*() to accomodate tcp
11681 			 * sockets).  Modules above ip pass this option
11682 			 * down here since ip is the only one that needs to
11683 			 * be aware of source address preferences.
11684 			 *
11685 			 * This socket option only affects connected
11686 			 * sockets that haven't already bound to a specific
11687 			 * IPv6 address.  In other words, sockets that
11688 			 * don't call bind() with an address other than the
11689 			 * unspecified address and that call connect().
11690 			 * ip_bind_connected_v6() passes these preferences
11691 			 * to the ipif_select_source_v6() function.
11692 			 */
11693 			if (inlen != sizeof (uint32_t))
11694 				return (EINVAL);
11695 			error = ip6_set_src_preferences(connp,
11696 			    *(uint32_t *)invalp);
11697 			if (error != 0) {
11698 				*outlenp = 0;
11699 				return (error);
11700 			} else {
11701 				*outlenp = sizeof (uint32_t);
11702 			}
11703 			break;
11704 		}
11705 		case IPV6_V6ONLY:
11706 			if (*i1 < 0 || *i1 > 1) {
11707 				return (EINVAL);
11708 			}
11709 			mutex_enter(&connp->conn_lock);
11710 			connp->conn_ipv6_v6only = *i1;
11711 			mutex_exit(&connp->conn_lock);
11712 			break;
11713 		default:
11714 			return (-EINVAL);
11715 		}
11716 		break;
11717 	default:
11718 		/*
11719 		 * "soft" error (negative)
11720 		 * option not handled at this level
11721 		 * Note: Do not modify *outlenp
11722 		 */
11723 		return (-EINVAL);
11724 	}
11725 	/*
11726 	 * Common case of return from an option that is sizeof (int)
11727 	 */
11728 	*(int *)outvalp = *i1;
11729 	*outlenp = sizeof (int);
11730 	return (0);
11731 }
11732 
11733 /*
11734  * This routine gets default values of certain options whose default
11735  * values are maintained by protocol specific code
11736  */
11737 /* ARGSUSED */
11738 int
11739 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11740 {
11741 	int *i1 = (int *)ptr;
11742 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11743 
11744 	switch (level) {
11745 	case IPPROTO_IP:
11746 		switch (name) {
11747 		case IP_MULTICAST_TTL:
11748 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11749 			return (sizeof (uchar_t));
11750 		case IP_MULTICAST_LOOP:
11751 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11752 			return (sizeof (uchar_t));
11753 		default:
11754 			return (-1);
11755 		}
11756 	case IPPROTO_IPV6:
11757 		switch (name) {
11758 		case IPV6_UNICAST_HOPS:
11759 			*i1 = ipst->ips_ipv6_def_hops;
11760 			return (sizeof (int));
11761 		case IPV6_MULTICAST_HOPS:
11762 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11763 			return (sizeof (int));
11764 		case IPV6_MULTICAST_LOOP:
11765 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11766 			return (sizeof (int));
11767 		case IPV6_V6ONLY:
11768 			*i1 = 1;
11769 			return (sizeof (int));
11770 		default:
11771 			return (-1);
11772 		}
11773 	default:
11774 		return (-1);
11775 	}
11776 	/* NOTREACHED */
11777 }
11778 
11779 /*
11780  * Given a destination address and a pointer to where to put the information
11781  * this routine fills in the mtuinfo.
11782  */
11783 int
11784 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11785     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11786 {
11787 	ire_t *ire;
11788 	ip_stack_t	*ipst = ns->netstack_ip;
11789 
11790 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11791 		return (-1);
11792 
11793 	bzero(mtuinfo, sizeof (*mtuinfo));
11794 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11795 	mtuinfo->ip6m_addr.sin6_port = port;
11796 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11797 
11798 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11799 	if (ire != NULL) {
11800 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11801 		ire_refrele(ire);
11802 	} else {
11803 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11804 	}
11805 	return (sizeof (struct ip6_mtuinfo));
11806 }
11807 
11808 /*
11809  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11810  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11811  * isn't.  This doesn't matter as the error checking is done properly for the
11812  * other MRT options coming in through ip_opt_set.
11813  */
11814 int
11815 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11816 {
11817 	conn_t		*connp = Q_TO_CONN(q);
11818 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11819 
11820 	switch (level) {
11821 	case IPPROTO_IP:
11822 		switch (name) {
11823 		case MRT_VERSION:
11824 		case MRT_ASSERT:
11825 			(void) ip_mrouter_get(name, q, ptr);
11826 			return (sizeof (int));
11827 		case IP_SEC_OPT:
11828 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11829 		case IP_NEXTHOP:
11830 			if (connp->conn_nexthop_set) {
11831 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11832 				return (sizeof (ipaddr_t));
11833 			} else
11834 				return (0);
11835 		case IP_RECVPKTINFO:
11836 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11837 			return (sizeof (int));
11838 		default:
11839 			break;
11840 		}
11841 		break;
11842 	case IPPROTO_IPV6:
11843 		switch (name) {
11844 		case IPV6_SEC_OPT:
11845 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11846 		case IPV6_SRC_PREFERENCES: {
11847 			return (ip6_get_src_preferences(connp,
11848 			    (uint32_t *)ptr));
11849 		}
11850 		case IPV6_V6ONLY:
11851 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11852 			return (sizeof (int));
11853 		case IPV6_PATHMTU:
11854 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11855 			    (struct ip6_mtuinfo *)ptr, connp->conn_netstack));
11856 		default:
11857 			break;
11858 		}
11859 		break;
11860 	default:
11861 		break;
11862 	}
11863 	return (-1);
11864 }
11865 
11866 /* Named Dispatch routine to get a current value out of our parameter table. */
11867 /* ARGSUSED */
11868 static int
11869 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11870 {
11871 	ipparam_t *ippa = (ipparam_t *)cp;
11872 
11873 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11874 	return (0);
11875 }
11876 
11877 /* ARGSUSED */
11878 static int
11879 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11880 {
11881 
11882 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11883 	return (0);
11884 }
11885 
11886 /*
11887  * Set ip{,6}_forwarding values.  This means walking through all of the
11888  * ill's and toggling their forwarding values.
11889  */
11890 /* ARGSUSED */
11891 static int
11892 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11893 {
11894 	long new_value;
11895 	int *forwarding_value = (int *)cp;
11896 	ill_t *ill;
11897 	boolean_t isv6;
11898 	ill_walk_context_t ctx;
11899 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11900 
11901 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11902 
11903 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11904 	    new_value < 0 || new_value > 1) {
11905 		return (EINVAL);
11906 	}
11907 
11908 	*forwarding_value = new_value;
11909 
11910 	/*
11911 	 * Regardless of the current value of ip_forwarding, set all per-ill
11912 	 * values of ip_forwarding to the value being set.
11913 	 *
11914 	 * Bring all the ill's up to date with the new global value.
11915 	 */
11916 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11917 
11918 	if (isv6)
11919 		ill = ILL_START_WALK_V6(&ctx, ipst);
11920 	else
11921 		ill = ILL_START_WALK_V4(&ctx, ipst);
11922 
11923 	for (; ill != NULL; ill = ill_next(&ctx, ill))
11924 		(void) ill_forward_set(ill, new_value != 0);
11925 
11926 	rw_exit(&ipst->ips_ill_g_lock);
11927 	return (0);
11928 }
11929 
11930 /*
11931  * Walk through the param array specified registering each element with the
11932  * Named Dispatch handler. This is called only during init. So it is ok
11933  * not to acquire any locks
11934  */
11935 static boolean_t
11936 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11937     ipndp_t *ipnd, size_t ipnd_cnt)
11938 {
11939 	for (; ippa_cnt-- > 0; ippa++) {
11940 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11941 			if (!nd_load(ndp, ippa->ip_param_name,
11942 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11943 				nd_free(ndp);
11944 				return (B_FALSE);
11945 			}
11946 		}
11947 	}
11948 
11949 	for (; ipnd_cnt-- > 0; ipnd++) {
11950 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11951 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11952 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11953 			    ipnd->ip_ndp_data)) {
11954 				nd_free(ndp);
11955 				return (B_FALSE);
11956 			}
11957 		}
11958 	}
11959 
11960 	return (B_TRUE);
11961 }
11962 
11963 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11964 /* ARGSUSED */
11965 static int
11966 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11967 {
11968 	long		new_value;
11969 	ipparam_t	*ippa = (ipparam_t *)cp;
11970 
11971 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11972 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11973 		return (EINVAL);
11974 	}
11975 	ippa->ip_param_value = new_value;
11976 	return (0);
11977 }
11978 
11979 /*
11980  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11981  * When an ipf is passed here for the first time, if
11982  * we already have in-order fragments on the queue, we convert from the fast-
11983  * path reassembly scheme to the hard-case scheme.  From then on, additional
11984  * fragments are reassembled here.  We keep track of the start and end offsets
11985  * of each piece, and the number of holes in the chain.  When the hole count
11986  * goes to zero, we are done!
11987  *
11988  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11989  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11990  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11991  * after the call to ip_reassemble().
11992  */
11993 int
11994 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11995     size_t msg_len)
11996 {
11997 	uint_t	end;
11998 	mblk_t	*next_mp;
11999 	mblk_t	*mp1;
12000 	uint_t	offset;
12001 	boolean_t incr_dups = B_TRUE;
12002 	boolean_t offset_zero_seen = B_FALSE;
12003 	boolean_t pkt_boundary_checked = B_FALSE;
12004 
12005 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
12006 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
12007 
12008 	/* Add in byte count */
12009 	ipf->ipf_count += msg_len;
12010 	if (ipf->ipf_end) {
12011 		/*
12012 		 * We were part way through in-order reassembly, but now there
12013 		 * is a hole.  We walk through messages already queued, and
12014 		 * mark them for hard case reassembly.  We know that up till
12015 		 * now they were in order starting from offset zero.
12016 		 */
12017 		offset = 0;
12018 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12019 			IP_REASS_SET_START(mp1, offset);
12020 			if (offset == 0) {
12021 				ASSERT(ipf->ipf_nf_hdr_len != 0);
12022 				offset = -ipf->ipf_nf_hdr_len;
12023 			}
12024 			offset += mp1->b_wptr - mp1->b_rptr;
12025 			IP_REASS_SET_END(mp1, offset);
12026 		}
12027 		/* One hole at the end. */
12028 		ipf->ipf_hole_cnt = 1;
12029 		/* Brand it as a hard case, forever. */
12030 		ipf->ipf_end = 0;
12031 	}
12032 	/* Walk through all the new pieces. */
12033 	do {
12034 		end = start + (mp->b_wptr - mp->b_rptr);
12035 		/*
12036 		 * If start is 0, decrease 'end' only for the first mblk of
12037 		 * the fragment. Otherwise 'end' can get wrong value in the
12038 		 * second pass of the loop if first mblk is exactly the
12039 		 * size of ipf_nf_hdr_len.
12040 		 */
12041 		if (start == 0 && !offset_zero_seen) {
12042 			/* First segment */
12043 			ASSERT(ipf->ipf_nf_hdr_len != 0);
12044 			end -= ipf->ipf_nf_hdr_len;
12045 			offset_zero_seen = B_TRUE;
12046 		}
12047 		next_mp = mp->b_cont;
12048 		/*
12049 		 * We are checking to see if there is any interesing data
12050 		 * to process.  If there isn't and the mblk isn't the
12051 		 * one which carries the unfragmentable header then we
12052 		 * drop it.  It's possible to have just the unfragmentable
12053 		 * header come through without any data.  That needs to be
12054 		 * saved.
12055 		 *
12056 		 * If the assert at the top of this function holds then the
12057 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
12058 		 * is infrequently traveled enough that the test is left in
12059 		 * to protect against future code changes which break that
12060 		 * invariant.
12061 		 */
12062 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
12063 			/* Empty.  Blast it. */
12064 			IP_REASS_SET_START(mp, 0);
12065 			IP_REASS_SET_END(mp, 0);
12066 			/*
12067 			 * If the ipf points to the mblk we are about to free,
12068 			 * update ipf to point to the next mblk (or NULL
12069 			 * if none).
12070 			 */
12071 			if (ipf->ipf_mp->b_cont == mp)
12072 				ipf->ipf_mp->b_cont = next_mp;
12073 			freeb(mp);
12074 			continue;
12075 		}
12076 		mp->b_cont = NULL;
12077 		IP_REASS_SET_START(mp, start);
12078 		IP_REASS_SET_END(mp, end);
12079 		if (!ipf->ipf_tail_mp) {
12080 			ipf->ipf_tail_mp = mp;
12081 			ipf->ipf_mp->b_cont = mp;
12082 			if (start == 0 || !more) {
12083 				ipf->ipf_hole_cnt = 1;
12084 				/*
12085 				 * if the first fragment comes in more than one
12086 				 * mblk, this loop will be executed for each
12087 				 * mblk. Need to adjust hole count so exiting
12088 				 * this routine will leave hole count at 1.
12089 				 */
12090 				if (next_mp)
12091 					ipf->ipf_hole_cnt++;
12092 			} else
12093 				ipf->ipf_hole_cnt = 2;
12094 			continue;
12095 		} else if (ipf->ipf_last_frag_seen && !more &&
12096 		    !pkt_boundary_checked) {
12097 			/*
12098 			 * We check datagram boundary only if this fragment
12099 			 * claims to be the last fragment and we have seen a
12100 			 * last fragment in the past too. We do this only
12101 			 * once for a given fragment.
12102 			 *
12103 			 * start cannot be 0 here as fragments with start=0
12104 			 * and MF=0 gets handled as a complete packet. These
12105 			 * fragments should not reach here.
12106 			 */
12107 
12108 			if (start + msgdsize(mp) !=
12109 			    IP_REASS_END(ipf->ipf_tail_mp)) {
12110 				/*
12111 				 * We have two fragments both of which claim
12112 				 * to be the last fragment but gives conflicting
12113 				 * information about the whole datagram size.
12114 				 * Something fishy is going on. Drop the
12115 				 * fragment and free up the reassembly list.
12116 				 */
12117 				return (IP_REASS_FAILED);
12118 			}
12119 
12120 			/*
12121 			 * We shouldn't come to this code block again for this
12122 			 * particular fragment.
12123 			 */
12124 			pkt_boundary_checked = B_TRUE;
12125 		}
12126 
12127 		/* New stuff at or beyond tail? */
12128 		offset = IP_REASS_END(ipf->ipf_tail_mp);
12129 		if (start >= offset) {
12130 			if (ipf->ipf_last_frag_seen) {
12131 				/* current fragment is beyond last fragment */
12132 				return (IP_REASS_FAILED);
12133 			}
12134 			/* Link it on end. */
12135 			ipf->ipf_tail_mp->b_cont = mp;
12136 			ipf->ipf_tail_mp = mp;
12137 			if (more) {
12138 				if (start != offset)
12139 					ipf->ipf_hole_cnt++;
12140 			} else if (start == offset && next_mp == NULL)
12141 					ipf->ipf_hole_cnt--;
12142 			continue;
12143 		}
12144 		mp1 = ipf->ipf_mp->b_cont;
12145 		offset = IP_REASS_START(mp1);
12146 		/* New stuff at the front? */
12147 		if (start < offset) {
12148 			if (start == 0) {
12149 				if (end >= offset) {
12150 					/* Nailed the hole at the begining. */
12151 					ipf->ipf_hole_cnt--;
12152 				}
12153 			} else if (end < offset) {
12154 				/*
12155 				 * A hole, stuff, and a hole where there used
12156 				 * to be just a hole.
12157 				 */
12158 				ipf->ipf_hole_cnt++;
12159 			}
12160 			mp->b_cont = mp1;
12161 			/* Check for overlap. */
12162 			while (end > offset) {
12163 				if (end < IP_REASS_END(mp1)) {
12164 					mp->b_wptr -= end - offset;
12165 					IP_REASS_SET_END(mp, offset);
12166 					BUMP_MIB(ill->ill_ip_mib,
12167 					    ipIfStatsReasmPartDups);
12168 					break;
12169 				}
12170 				/* Did we cover another hole? */
12171 				if ((mp1->b_cont &&
12172 				    IP_REASS_END(mp1) !=
12173 				    IP_REASS_START(mp1->b_cont) &&
12174 				    end >= IP_REASS_START(mp1->b_cont)) ||
12175 				    (!ipf->ipf_last_frag_seen && !more)) {
12176 					ipf->ipf_hole_cnt--;
12177 				}
12178 				/* Clip out mp1. */
12179 				if ((mp->b_cont = mp1->b_cont) == NULL) {
12180 					/*
12181 					 * After clipping out mp1, this guy
12182 					 * is now hanging off the end.
12183 					 */
12184 					ipf->ipf_tail_mp = mp;
12185 				}
12186 				IP_REASS_SET_START(mp1, 0);
12187 				IP_REASS_SET_END(mp1, 0);
12188 				/* Subtract byte count */
12189 				ipf->ipf_count -= mp1->b_datap->db_lim -
12190 				    mp1->b_datap->db_base;
12191 				freeb(mp1);
12192 				BUMP_MIB(ill->ill_ip_mib,
12193 				    ipIfStatsReasmPartDups);
12194 				mp1 = mp->b_cont;
12195 				if (!mp1)
12196 					break;
12197 				offset = IP_REASS_START(mp1);
12198 			}
12199 			ipf->ipf_mp->b_cont = mp;
12200 			continue;
12201 		}
12202 		/*
12203 		 * The new piece starts somewhere between the start of the head
12204 		 * and before the end of the tail.
12205 		 */
12206 		for (; mp1; mp1 = mp1->b_cont) {
12207 			offset = IP_REASS_END(mp1);
12208 			if (start < offset) {
12209 				if (end <= offset) {
12210 					/* Nothing new. */
12211 					IP_REASS_SET_START(mp, 0);
12212 					IP_REASS_SET_END(mp, 0);
12213 					/* Subtract byte count */
12214 					ipf->ipf_count -= mp->b_datap->db_lim -
12215 					    mp->b_datap->db_base;
12216 					if (incr_dups) {
12217 						ipf->ipf_num_dups++;
12218 						incr_dups = B_FALSE;
12219 					}
12220 					freeb(mp);
12221 					BUMP_MIB(ill->ill_ip_mib,
12222 					    ipIfStatsReasmDuplicates);
12223 					break;
12224 				}
12225 				/*
12226 				 * Trim redundant stuff off beginning of new
12227 				 * piece.
12228 				 */
12229 				IP_REASS_SET_START(mp, offset);
12230 				mp->b_rptr += offset - start;
12231 				BUMP_MIB(ill->ill_ip_mib,
12232 				    ipIfStatsReasmPartDups);
12233 				start = offset;
12234 				if (!mp1->b_cont) {
12235 					/*
12236 					 * After trimming, this guy is now
12237 					 * hanging off the end.
12238 					 */
12239 					mp1->b_cont = mp;
12240 					ipf->ipf_tail_mp = mp;
12241 					if (!more) {
12242 						ipf->ipf_hole_cnt--;
12243 					}
12244 					break;
12245 				}
12246 			}
12247 			if (start >= IP_REASS_START(mp1->b_cont))
12248 				continue;
12249 			/* Fill a hole */
12250 			if (start > offset)
12251 				ipf->ipf_hole_cnt++;
12252 			mp->b_cont = mp1->b_cont;
12253 			mp1->b_cont = mp;
12254 			mp1 = mp->b_cont;
12255 			offset = IP_REASS_START(mp1);
12256 			if (end >= offset) {
12257 				ipf->ipf_hole_cnt--;
12258 				/* Check for overlap. */
12259 				while (end > offset) {
12260 					if (end < IP_REASS_END(mp1)) {
12261 						mp->b_wptr -= end - offset;
12262 						IP_REASS_SET_END(mp, offset);
12263 						/*
12264 						 * TODO we might bump
12265 						 * this up twice if there is
12266 						 * overlap at both ends.
12267 						 */
12268 						BUMP_MIB(ill->ill_ip_mib,
12269 						    ipIfStatsReasmPartDups);
12270 						break;
12271 					}
12272 					/* Did we cover another hole? */
12273 					if ((mp1->b_cont &&
12274 					    IP_REASS_END(mp1)
12275 					    != IP_REASS_START(mp1->b_cont) &&
12276 					    end >=
12277 					    IP_REASS_START(mp1->b_cont)) ||
12278 					    (!ipf->ipf_last_frag_seen &&
12279 					    !more)) {
12280 						ipf->ipf_hole_cnt--;
12281 					}
12282 					/* Clip out mp1. */
12283 					if ((mp->b_cont = mp1->b_cont) ==
12284 					    NULL) {
12285 						/*
12286 						 * After clipping out mp1,
12287 						 * this guy is now hanging
12288 						 * off the end.
12289 						 */
12290 						ipf->ipf_tail_mp = mp;
12291 					}
12292 					IP_REASS_SET_START(mp1, 0);
12293 					IP_REASS_SET_END(mp1, 0);
12294 					/* Subtract byte count */
12295 					ipf->ipf_count -=
12296 					    mp1->b_datap->db_lim -
12297 					    mp1->b_datap->db_base;
12298 					freeb(mp1);
12299 					BUMP_MIB(ill->ill_ip_mib,
12300 					    ipIfStatsReasmPartDups);
12301 					mp1 = mp->b_cont;
12302 					if (!mp1)
12303 						break;
12304 					offset = IP_REASS_START(mp1);
12305 				}
12306 			}
12307 			break;
12308 		}
12309 	} while (start = end, mp = next_mp);
12310 
12311 	/* Fragment just processed could be the last one. Remember this fact */
12312 	if (!more)
12313 		ipf->ipf_last_frag_seen = B_TRUE;
12314 
12315 	/* Still got holes? */
12316 	if (ipf->ipf_hole_cnt)
12317 		return (IP_REASS_PARTIAL);
12318 	/* Clean up overloaded fields to avoid upstream disasters. */
12319 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12320 		IP_REASS_SET_START(mp1, 0);
12321 		IP_REASS_SET_END(mp1, 0);
12322 	}
12323 	return (IP_REASS_COMPLETE);
12324 }
12325 
12326 /*
12327  * ipsec processing for the fast path, used for input UDP Packets
12328  */
12329 static boolean_t
12330 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
12331     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present)
12332 {
12333 	uint32_t	ill_index;
12334 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
12335 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
12336 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12337 
12338 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12339 	/* The ill_index of the incoming ILL */
12340 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
12341 
12342 	/* pass packet up to the transport */
12343 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
12344 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
12345 		    NULL, mctl_present);
12346 		if (*first_mpp == NULL) {
12347 			return (B_FALSE);
12348 		}
12349 	}
12350 
12351 	/* Initiate IPPF processing for fastpath UDP */
12352 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12353 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
12354 		if (*mpp == NULL) {
12355 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
12356 			    "deferred/dropped during IPPF processing\n"));
12357 			return (B_FALSE);
12358 		}
12359 	}
12360 	/*
12361 	 * We make the checks as below since we are in the fast path
12362 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12363 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12364 	 */
12365 	if (connp->conn_recvif || connp->conn_recvslla ||
12366 	    connp->conn_ip_recvpktinfo) {
12367 		if (connp->conn_recvif) {
12368 			in_flags = IPF_RECVIF;
12369 		}
12370 		/*
12371 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12372 		 * so the flag passed to ip_add_info is based on IP version
12373 		 * of connp.
12374 		 */
12375 		if (connp->conn_ip_recvpktinfo) {
12376 			if (connp->conn_af_isv6) {
12377 				/*
12378 				 * V6 only needs index
12379 				 */
12380 				in_flags |= IPF_RECVIF;
12381 			} else {
12382 				/*
12383 				 * V4 needs index + matching address.
12384 				 */
12385 				in_flags |= IPF_RECVADDR;
12386 			}
12387 		}
12388 		if (connp->conn_recvslla) {
12389 			in_flags |= IPF_RECVSLLA;
12390 		}
12391 		/*
12392 		 * since in_flags are being set ill will be
12393 		 * referenced in ip_add_info, so it better not
12394 		 * be NULL.
12395 		 */
12396 		/*
12397 		 * the actual data will be contained in b_cont
12398 		 * upon successful return of the following call.
12399 		 * If the call fails then the original mblk is
12400 		 * returned.
12401 		 */
12402 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12403 		    ipst);
12404 	}
12405 
12406 	return (B_TRUE);
12407 }
12408 
12409 /*
12410  * Fragmentation reassembly.  Each ILL has a hash table for
12411  * queuing packets undergoing reassembly for all IPIFs
12412  * associated with the ILL.  The hash is based on the packet
12413  * IP ident field.  The ILL frag hash table was allocated
12414  * as a timer block at the time the ILL was created.  Whenever
12415  * there is anything on the reassembly queue, the timer will
12416  * be running.  Returns B_TRUE if successful else B_FALSE;
12417  * frees mp on failure.
12418  */
12419 static boolean_t
12420 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
12421     uint32_t *cksum_val, uint16_t *cksum_flags)
12422 {
12423 	uint32_t	frag_offset_flags;
12424 	ill_t		*ill = (ill_t *)q->q_ptr;
12425 	mblk_t		*mp = *mpp;
12426 	mblk_t		*t_mp;
12427 	ipaddr_t	dst;
12428 	uint8_t		proto = ipha->ipha_protocol;
12429 	uint32_t	sum_val;
12430 	uint16_t	sum_flags;
12431 	ipf_t		*ipf;
12432 	ipf_t		**ipfp;
12433 	ipfb_t		*ipfb;
12434 	uint16_t	ident;
12435 	uint32_t	offset;
12436 	ipaddr_t	src;
12437 	uint_t		hdr_length;
12438 	uint32_t	end;
12439 	mblk_t		*mp1;
12440 	mblk_t		*tail_mp;
12441 	size_t		count;
12442 	size_t		msg_len;
12443 	uint8_t		ecn_info = 0;
12444 	uint32_t	packet_size;
12445 	boolean_t	pruned = B_FALSE;
12446 	ip_stack_t *ipst = ill->ill_ipst;
12447 
12448 	if (cksum_val != NULL)
12449 		*cksum_val = 0;
12450 	if (cksum_flags != NULL)
12451 		*cksum_flags = 0;
12452 
12453 	/*
12454 	 * Drop the fragmented as early as possible, if
12455 	 * we don't have resource(s) to re-assemble.
12456 	 */
12457 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12458 		freemsg(mp);
12459 		return (B_FALSE);
12460 	}
12461 
12462 	/* Check for fragmentation offset; return if there's none */
12463 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12464 	    (IPH_MF | IPH_OFFSET)) == 0)
12465 		return (B_TRUE);
12466 
12467 	/*
12468 	 * We utilize hardware computed checksum info only for UDP since
12469 	 * IP fragmentation is a normal occurence for the protocol.  In
12470 	 * addition, checksum offload support for IP fragments carrying
12471 	 * UDP payload is commonly implemented across network adapters.
12472 	 */
12473 	ASSERT(ill != NULL);
12474 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
12475 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12476 		mblk_t *mp1 = mp->b_cont;
12477 		int32_t len;
12478 
12479 		/* Record checksum information from the packet */
12480 		sum_val = (uint32_t)DB_CKSUM16(mp);
12481 		sum_flags = DB_CKSUMFLAGS(mp);
12482 
12483 		/* IP payload offset from beginning of mblk */
12484 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12485 
12486 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12487 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12488 		    offset >= DB_CKSUMSTART(mp) &&
12489 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12490 			uint32_t adj;
12491 			/*
12492 			 * Partial checksum has been calculated by hardware
12493 			 * and attached to the packet; in addition, any
12494 			 * prepended extraneous data is even byte aligned.
12495 			 * If any such data exists, we adjust the checksum;
12496 			 * this would also handle any postpended data.
12497 			 */
12498 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12499 			    mp, mp1, len, adj);
12500 
12501 			/* One's complement subtract extraneous checksum */
12502 			if (adj >= sum_val)
12503 				sum_val = ~(adj - sum_val) & 0xFFFF;
12504 			else
12505 				sum_val -= adj;
12506 		}
12507 	} else {
12508 		sum_val = 0;
12509 		sum_flags = 0;
12510 	}
12511 
12512 	/* Clear hardware checksumming flag */
12513 	DB_CKSUMFLAGS(mp) = 0;
12514 
12515 	ident = ipha->ipha_ident;
12516 	offset = (frag_offset_flags << 3) & 0xFFFF;
12517 	src = ipha->ipha_src;
12518 	dst = ipha->ipha_dst;
12519 	hdr_length = IPH_HDR_LENGTH(ipha);
12520 	end = ntohs(ipha->ipha_length) - hdr_length;
12521 
12522 	/* If end == 0 then we have a packet with no data, so just free it */
12523 	if (end == 0) {
12524 		freemsg(mp);
12525 		return (B_FALSE);
12526 	}
12527 
12528 	/* Record the ECN field info. */
12529 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12530 	if (offset != 0) {
12531 		/*
12532 		 * If this isn't the first piece, strip the header, and
12533 		 * add the offset to the end value.
12534 		 */
12535 		mp->b_rptr += hdr_length;
12536 		end += offset;
12537 	}
12538 
12539 	msg_len = MBLKSIZE(mp);
12540 	tail_mp = mp;
12541 	while (tail_mp->b_cont != NULL) {
12542 		tail_mp = tail_mp->b_cont;
12543 		msg_len += MBLKSIZE(tail_mp);
12544 	}
12545 
12546 	/* If the reassembly list for this ILL will get too big, prune it */
12547 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12548 	    ipst->ips_ip_reass_queue_bytes) {
12549 		ill_frag_prune(ill,
12550 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12551 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12552 		pruned = B_TRUE;
12553 	}
12554 
12555 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12556 	mutex_enter(&ipfb->ipfb_lock);
12557 
12558 	ipfp = &ipfb->ipfb_ipf;
12559 	/* Try to find an existing fragment queue for this packet. */
12560 	for (;;) {
12561 		ipf = ipfp[0];
12562 		if (ipf != NULL) {
12563 			/*
12564 			 * It has to match on ident and src/dst address.
12565 			 */
12566 			if (ipf->ipf_ident == ident &&
12567 			    ipf->ipf_src == src &&
12568 			    ipf->ipf_dst == dst &&
12569 			    ipf->ipf_protocol == proto) {
12570 				/*
12571 				 * If we have received too many
12572 				 * duplicate fragments for this packet
12573 				 * free it.
12574 				 */
12575 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12576 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12577 					freemsg(mp);
12578 					mutex_exit(&ipfb->ipfb_lock);
12579 					return (B_FALSE);
12580 				}
12581 				/* Found it. */
12582 				break;
12583 			}
12584 			ipfp = &ipf->ipf_hash_next;
12585 			continue;
12586 		}
12587 
12588 		/*
12589 		 * If we pruned the list, do we want to store this new
12590 		 * fragment?. We apply an optimization here based on the
12591 		 * fact that most fragments will be received in order.
12592 		 * So if the offset of this incoming fragment is zero,
12593 		 * it is the first fragment of a new packet. We will
12594 		 * keep it.  Otherwise drop the fragment, as we have
12595 		 * probably pruned the packet already (since the
12596 		 * packet cannot be found).
12597 		 */
12598 		if (pruned && offset != 0) {
12599 			mutex_exit(&ipfb->ipfb_lock);
12600 			freemsg(mp);
12601 			return (B_FALSE);
12602 		}
12603 
12604 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12605 			/*
12606 			 * Too many fragmented packets in this hash
12607 			 * bucket. Free the oldest.
12608 			 */
12609 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12610 		}
12611 
12612 		/* New guy.  Allocate a frag message. */
12613 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12614 		if (mp1 == NULL) {
12615 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12616 			freemsg(mp);
12617 reass_done:
12618 			mutex_exit(&ipfb->ipfb_lock);
12619 			return (B_FALSE);
12620 		}
12621 
12622 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12623 		mp1->b_cont = mp;
12624 
12625 		/* Initialize the fragment header. */
12626 		ipf = (ipf_t *)mp1->b_rptr;
12627 		ipf->ipf_mp = mp1;
12628 		ipf->ipf_ptphn = ipfp;
12629 		ipfp[0] = ipf;
12630 		ipf->ipf_hash_next = NULL;
12631 		ipf->ipf_ident = ident;
12632 		ipf->ipf_protocol = proto;
12633 		ipf->ipf_src = src;
12634 		ipf->ipf_dst = dst;
12635 		ipf->ipf_nf_hdr_len = 0;
12636 		/* Record reassembly start time. */
12637 		ipf->ipf_timestamp = gethrestime_sec();
12638 		/* Record ipf generation and account for frag header */
12639 		ipf->ipf_gen = ill->ill_ipf_gen++;
12640 		ipf->ipf_count = MBLKSIZE(mp1);
12641 		ipf->ipf_last_frag_seen = B_FALSE;
12642 		ipf->ipf_ecn = ecn_info;
12643 		ipf->ipf_num_dups = 0;
12644 		ipfb->ipfb_frag_pkts++;
12645 		ipf->ipf_checksum = 0;
12646 		ipf->ipf_checksum_flags = 0;
12647 
12648 		/* Store checksum value in fragment header */
12649 		if (sum_flags != 0) {
12650 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12651 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12652 			ipf->ipf_checksum = sum_val;
12653 			ipf->ipf_checksum_flags = sum_flags;
12654 		}
12655 
12656 		/*
12657 		 * We handle reassembly two ways.  In the easy case,
12658 		 * where all the fragments show up in order, we do
12659 		 * minimal bookkeeping, and just clip new pieces on
12660 		 * the end.  If we ever see a hole, then we go off
12661 		 * to ip_reassemble which has to mark the pieces and
12662 		 * keep track of the number of holes, etc.  Obviously,
12663 		 * the point of having both mechanisms is so we can
12664 		 * handle the easy case as efficiently as possible.
12665 		 */
12666 		if (offset == 0) {
12667 			/* Easy case, in-order reassembly so far. */
12668 			ipf->ipf_count += msg_len;
12669 			ipf->ipf_tail_mp = tail_mp;
12670 			/*
12671 			 * Keep track of next expected offset in
12672 			 * ipf_end.
12673 			 */
12674 			ipf->ipf_end = end;
12675 			ipf->ipf_nf_hdr_len = hdr_length;
12676 		} else {
12677 			/* Hard case, hole at the beginning. */
12678 			ipf->ipf_tail_mp = NULL;
12679 			/*
12680 			 * ipf_end == 0 means that we have given up
12681 			 * on easy reassembly.
12682 			 */
12683 			ipf->ipf_end = 0;
12684 
12685 			/* Forget checksum offload from now on */
12686 			ipf->ipf_checksum_flags = 0;
12687 
12688 			/*
12689 			 * ipf_hole_cnt is set by ip_reassemble.
12690 			 * ipf_count is updated by ip_reassemble.
12691 			 * No need to check for return value here
12692 			 * as we don't expect reassembly to complete
12693 			 * or fail for the first fragment itself.
12694 			 */
12695 			(void) ip_reassemble(mp, ipf,
12696 			    (frag_offset_flags & IPH_OFFSET) << 3,
12697 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12698 		}
12699 		/* Update per ipfb and ill byte counts */
12700 		ipfb->ipfb_count += ipf->ipf_count;
12701 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12702 		ill->ill_frag_count += ipf->ipf_count;
12703 		/* If the frag timer wasn't already going, start it. */
12704 		mutex_enter(&ill->ill_lock);
12705 		ill_frag_timer_start(ill);
12706 		mutex_exit(&ill->ill_lock);
12707 		goto reass_done;
12708 	}
12709 
12710 	/*
12711 	 * If the packet's flag has changed (it could be coming up
12712 	 * from an interface different than the previous, therefore
12713 	 * possibly different checksum capability), then forget about
12714 	 * any stored checksum states.  Otherwise add the value to
12715 	 * the existing one stored in the fragment header.
12716 	 */
12717 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12718 		sum_val += ipf->ipf_checksum;
12719 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12720 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12721 		ipf->ipf_checksum = sum_val;
12722 	} else if (ipf->ipf_checksum_flags != 0) {
12723 		/* Forget checksum offload from now on */
12724 		ipf->ipf_checksum_flags = 0;
12725 	}
12726 
12727 	/*
12728 	 * We have a new piece of a datagram which is already being
12729 	 * reassembled.  Update the ECN info if all IP fragments
12730 	 * are ECN capable.  If there is one which is not, clear
12731 	 * all the info.  If there is at least one which has CE
12732 	 * code point, IP needs to report that up to transport.
12733 	 */
12734 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12735 		if (ecn_info == IPH_ECN_CE)
12736 			ipf->ipf_ecn = IPH_ECN_CE;
12737 	} else {
12738 		ipf->ipf_ecn = IPH_ECN_NECT;
12739 	}
12740 	if (offset && ipf->ipf_end == offset) {
12741 		/* The new fragment fits at the end */
12742 		ipf->ipf_tail_mp->b_cont = mp;
12743 		/* Update the byte count */
12744 		ipf->ipf_count += msg_len;
12745 		/* Update per ipfb and ill byte counts */
12746 		ipfb->ipfb_count += msg_len;
12747 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12748 		ill->ill_frag_count += msg_len;
12749 		if (frag_offset_flags & IPH_MF) {
12750 			/* More to come. */
12751 			ipf->ipf_end = end;
12752 			ipf->ipf_tail_mp = tail_mp;
12753 			goto reass_done;
12754 		}
12755 	} else {
12756 		/* Go do the hard cases. */
12757 		int ret;
12758 
12759 		if (offset == 0)
12760 			ipf->ipf_nf_hdr_len = hdr_length;
12761 
12762 		/* Save current byte count */
12763 		count = ipf->ipf_count;
12764 		ret = ip_reassemble(mp, ipf,
12765 		    (frag_offset_flags & IPH_OFFSET) << 3,
12766 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12767 		/* Count of bytes added and subtracted (freeb()ed) */
12768 		count = ipf->ipf_count - count;
12769 		if (count) {
12770 			/* Update per ipfb and ill byte counts */
12771 			ipfb->ipfb_count += count;
12772 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12773 			ill->ill_frag_count += count;
12774 		}
12775 		if (ret == IP_REASS_PARTIAL) {
12776 			goto reass_done;
12777 		} else if (ret == IP_REASS_FAILED) {
12778 			/* Reassembly failed. Free up all resources */
12779 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12780 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12781 				IP_REASS_SET_START(t_mp, 0);
12782 				IP_REASS_SET_END(t_mp, 0);
12783 			}
12784 			freemsg(mp);
12785 			goto reass_done;
12786 		}
12787 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12788 	}
12789 	/*
12790 	 * We have completed reassembly.  Unhook the frag header from
12791 	 * the reassembly list.
12792 	 *
12793 	 * Before we free the frag header, record the ECN info
12794 	 * to report back to the transport.
12795 	 */
12796 	ecn_info = ipf->ipf_ecn;
12797 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12798 	ipfp = ipf->ipf_ptphn;
12799 
12800 	/* We need to supply these to caller */
12801 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12802 		sum_val = ipf->ipf_checksum;
12803 	else
12804 		sum_val = 0;
12805 
12806 	mp1 = ipf->ipf_mp;
12807 	count = ipf->ipf_count;
12808 	ipf = ipf->ipf_hash_next;
12809 	if (ipf != NULL)
12810 		ipf->ipf_ptphn = ipfp;
12811 	ipfp[0] = ipf;
12812 	ill->ill_frag_count -= count;
12813 	ASSERT(ipfb->ipfb_count >= count);
12814 	ipfb->ipfb_count -= count;
12815 	ipfb->ipfb_frag_pkts--;
12816 	mutex_exit(&ipfb->ipfb_lock);
12817 	/* Ditch the frag header. */
12818 	mp = mp1->b_cont;
12819 
12820 	freeb(mp1);
12821 
12822 	/* Restore original IP length in header. */
12823 	packet_size = (uint32_t)msgdsize(mp);
12824 	if (packet_size > IP_MAXPACKET) {
12825 		freemsg(mp);
12826 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12827 		return (B_FALSE);
12828 	}
12829 
12830 	if (DB_REF(mp) > 1) {
12831 		mblk_t *mp2 = copymsg(mp);
12832 
12833 		freemsg(mp);
12834 		if (mp2 == NULL) {
12835 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12836 			return (B_FALSE);
12837 		}
12838 		mp = mp2;
12839 	}
12840 	ipha = (ipha_t *)mp->b_rptr;
12841 
12842 	ipha->ipha_length = htons((uint16_t)packet_size);
12843 	/* We're now complete, zip the frag state */
12844 	ipha->ipha_fragment_offset_and_flags = 0;
12845 	/* Record the ECN info. */
12846 	ipha->ipha_type_of_service &= 0xFC;
12847 	ipha->ipha_type_of_service |= ecn_info;
12848 	*mpp = mp;
12849 
12850 	/* Reassembly is successful; return checksum information if needed */
12851 	if (cksum_val != NULL)
12852 		*cksum_val = sum_val;
12853 	if (cksum_flags != NULL)
12854 		*cksum_flags = sum_flags;
12855 
12856 	return (B_TRUE);
12857 }
12858 
12859 /*
12860  * Perform ip header check sum update local options.
12861  * return B_TRUE if all is well, else return B_FALSE and release
12862  * the mp. caller is responsible for decrementing ire ref cnt.
12863  */
12864 static boolean_t
12865 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12866     ip_stack_t *ipst)
12867 {
12868 	mblk_t		*first_mp;
12869 	boolean_t	mctl_present;
12870 	uint16_t	sum;
12871 
12872 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12873 	/*
12874 	 * Don't do the checksum if it has gone through AH/ESP
12875 	 * processing.
12876 	 */
12877 	if (!mctl_present) {
12878 		sum = ip_csum_hdr(ipha);
12879 		if (sum != 0) {
12880 			if (ill != NULL) {
12881 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12882 			} else {
12883 				BUMP_MIB(&ipst->ips_ip_mib,
12884 				    ipIfStatsInCksumErrs);
12885 			}
12886 			freemsg(first_mp);
12887 			return (B_FALSE);
12888 		}
12889 	}
12890 
12891 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12892 		if (mctl_present)
12893 			freeb(first_mp);
12894 		return (B_FALSE);
12895 	}
12896 
12897 	return (B_TRUE);
12898 }
12899 
12900 /*
12901  * All udp packet are delivered to the local host via this routine.
12902  */
12903 void
12904 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12905     ill_t *recv_ill)
12906 {
12907 	uint32_t	sum;
12908 	uint32_t	u1;
12909 	boolean_t	mctl_present;
12910 	conn_t		*connp;
12911 	mblk_t		*first_mp;
12912 	uint16_t	*up;
12913 	ill_t		*ill = (ill_t *)q->q_ptr;
12914 	uint16_t	reass_hck_flags = 0;
12915 	ip_stack_t	*ipst;
12916 
12917 	ASSERT(recv_ill != NULL);
12918 	ipst = recv_ill->ill_ipst;
12919 
12920 #define	rptr    ((uchar_t *)ipha)
12921 
12922 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12923 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12924 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12925 	ASSERT(ill != NULL);
12926 
12927 	/*
12928 	 * FAST PATH for udp packets
12929 	 */
12930 
12931 	/* u1 is # words of IP options */
12932 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12933 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12934 
12935 	/* IP options present */
12936 	if (u1 != 0)
12937 		goto ipoptions;
12938 
12939 	/* Check the IP header checksum.  */
12940 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12941 		/* Clear the IP header h/w cksum flag */
12942 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12943 	} else {
12944 #define	uph	((uint16_t *)ipha)
12945 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12946 		    uph[6] + uph[7] + uph[8] + uph[9];
12947 #undef	uph
12948 		/* finish doing IP checksum */
12949 		sum = (sum & 0xFFFF) + (sum >> 16);
12950 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12951 		/*
12952 		 * Don't verify header checksum if this packet is coming
12953 		 * back from AH/ESP as we already did it.
12954 		 */
12955 		if (!mctl_present && sum != 0 && sum != 0xFFFF) {
12956 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12957 			freemsg(first_mp);
12958 			return;
12959 		}
12960 	}
12961 
12962 	/*
12963 	 * Count for SNMP of inbound packets for ire.
12964 	 * if mctl is present this might be a secure packet and
12965 	 * has already been counted for in ip_proto_input().
12966 	 */
12967 	if (!mctl_present) {
12968 		UPDATE_IB_PKT_COUNT(ire);
12969 		ire->ire_last_used_time = lbolt;
12970 	}
12971 
12972 	/* packet part of fragmented IP packet? */
12973 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12974 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12975 		goto fragmented;
12976 	}
12977 
12978 	/* u1 = IP header length (20 bytes) */
12979 	u1 = IP_SIMPLE_HDR_LENGTH;
12980 
12981 	/* packet does not contain complete IP & UDP headers */
12982 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12983 		goto udppullup;
12984 
12985 	/* up points to UDP header */
12986 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12987 #define	iphs    ((uint16_t *)ipha)
12988 
12989 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12990 	if (up[3] != 0) {
12991 		mblk_t *mp1 = mp->b_cont;
12992 		boolean_t cksum_err;
12993 		uint16_t hck_flags = 0;
12994 
12995 		/* Pseudo-header checksum */
12996 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12997 		    iphs[9] + up[2];
12998 
12999 		/*
13000 		 * Revert to software checksum calculation if the interface
13001 		 * isn't capable of checksum offload or if IPsec is present.
13002 		 */
13003 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
13004 			hck_flags = DB_CKSUMFLAGS(mp);
13005 
13006 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13007 			IP_STAT(ipst, ip_in_sw_cksum);
13008 
13009 		IP_CKSUM_RECV(hck_flags, u1,
13010 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
13011 		    (int32_t)((uchar_t *)up - rptr),
13012 		    mp, mp1, cksum_err);
13013 
13014 		if (cksum_err) {
13015 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
13016 			if (hck_flags & HCK_FULLCKSUM)
13017 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
13018 			else if (hck_flags & HCK_PARTIALCKSUM)
13019 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
13020 			else
13021 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
13022 
13023 			freemsg(first_mp);
13024 			return;
13025 		}
13026 	}
13027 
13028 	/* Non-fragmented broadcast or multicast packet? */
13029 	if (ire->ire_type == IRE_BROADCAST)
13030 		goto udpslowpath;
13031 
13032 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
13033 	    ire->ire_zoneid, ipst)) != NULL) {
13034 		ASSERT(connp->conn_upq != NULL);
13035 		IP_STAT(ipst, ip_udp_fast_path);
13036 
13037 		if (CONN_UDP_FLOWCTLD(connp)) {
13038 			freemsg(mp);
13039 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
13040 		} else {
13041 			if (!mctl_present) {
13042 				BUMP_MIB(ill->ill_ip_mib,
13043 				    ipIfStatsHCInDelivers);
13044 			}
13045 			/*
13046 			 * mp and first_mp can change.
13047 			 */
13048 			if (ip_udp_check(q, connp, recv_ill,
13049 			    ipha, &mp, &first_mp, mctl_present)) {
13050 				/* Send it upstream */
13051 				CONN_UDP_RECV(connp, mp);
13052 			}
13053 		}
13054 		/*
13055 		 * freeb() cannot deal with null mblk being passed
13056 		 * in and first_mp can be set to null in the call
13057 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
13058 		 */
13059 		if (mctl_present && first_mp != NULL) {
13060 			freeb(first_mp);
13061 		}
13062 		CONN_DEC_REF(connp);
13063 		return;
13064 	}
13065 
13066 	/*
13067 	 * if we got here we know the packet is not fragmented and
13068 	 * has no options. The classifier could not find a conn_t and
13069 	 * most likely its an icmp packet so send it through slow path.
13070 	 */
13071 
13072 	goto udpslowpath;
13073 
13074 ipoptions:
13075 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
13076 		goto slow_done;
13077 	}
13078 
13079 	UPDATE_IB_PKT_COUNT(ire);
13080 	ire->ire_last_used_time = lbolt;
13081 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13082 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13083 fragmented:
13084 		/*
13085 		 * "sum" and "reass_hck_flags" are non-zero if the
13086 		 * reassembled packet has a valid hardware computed
13087 		 * checksum information associated with it.
13088 		 */
13089 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
13090 			goto slow_done;
13091 		/*
13092 		 * Make sure that first_mp points back to mp as
13093 		 * the mp we came in with could have changed in
13094 		 * ip_rput_fragment().
13095 		 */
13096 		ASSERT(!mctl_present);
13097 		ipha = (ipha_t *)mp->b_rptr;
13098 		first_mp = mp;
13099 	}
13100 
13101 	/* Now we have a complete datagram, destined for this machine. */
13102 	u1 = IPH_HDR_LENGTH(ipha);
13103 	/* Pull up the UDP header, if necessary. */
13104 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
13105 udppullup:
13106 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
13107 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13108 			freemsg(first_mp);
13109 			goto slow_done;
13110 		}
13111 		ipha = (ipha_t *)mp->b_rptr;
13112 	}
13113 
13114 	/*
13115 	 * Validate the checksum for the reassembled packet; for the
13116 	 * pullup case we calculate the payload checksum in software.
13117 	 */
13118 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
13119 	if (up[3] != 0) {
13120 		boolean_t cksum_err;
13121 
13122 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13123 			IP_STAT(ipst, ip_in_sw_cksum);
13124 
13125 		IP_CKSUM_RECV_REASS(reass_hck_flags,
13126 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
13127 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
13128 		    iphs[9] + up[2], sum, cksum_err);
13129 
13130 		if (cksum_err) {
13131 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
13132 
13133 			if (reass_hck_flags & HCK_FULLCKSUM)
13134 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
13135 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
13136 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
13137 			else
13138 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
13139 
13140 			freemsg(first_mp);
13141 			goto slow_done;
13142 		}
13143 	}
13144 udpslowpath:
13145 
13146 	/* Clear hardware checksum flag to be safe */
13147 	DB_CKSUMFLAGS(mp) = 0;
13148 
13149 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
13150 	    (ire->ire_type == IRE_BROADCAST),
13151 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
13152 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
13153 
13154 slow_done:
13155 	IP_STAT(ipst, ip_udp_slow_path);
13156 	return;
13157 
13158 #undef  iphs
13159 #undef  rptr
13160 }
13161 
13162 /* ARGSUSED */
13163 static mblk_t *
13164 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13165     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
13166     ill_rx_ring_t *ill_ring)
13167 {
13168 	conn_t		*connp;
13169 	uint32_t	sum;
13170 	uint32_t	u1;
13171 	uint16_t	*up;
13172 	int		offset;
13173 	ssize_t		len;
13174 	mblk_t		*mp1;
13175 	boolean_t	syn_present = B_FALSE;
13176 	tcph_t		*tcph;
13177 	uint_t		ip_hdr_len;
13178 	ill_t		*ill = (ill_t *)q->q_ptr;
13179 	zoneid_t	zoneid = ire->ire_zoneid;
13180 	boolean_t	cksum_err;
13181 	uint16_t	hck_flags = 0;
13182 	ip_stack_t	*ipst = recv_ill->ill_ipst;
13183 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
13184 
13185 #define	rptr	((uchar_t *)ipha)
13186 
13187 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
13188 	ASSERT(ill != NULL);
13189 
13190 	/*
13191 	 * FAST PATH for tcp packets
13192 	 */
13193 
13194 	/* u1 is # words of IP options */
13195 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13196 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13197 
13198 	/* IP options present */
13199 	if (u1) {
13200 		goto ipoptions;
13201 	} else {
13202 		/* Check the IP header checksum.  */
13203 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
13204 			/* Clear the IP header h/w cksum flag */
13205 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
13206 		} else {
13207 #define	uph	((uint16_t *)ipha)
13208 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13209 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13210 #undef	uph
13211 			/* finish doing IP checksum */
13212 			sum = (sum & 0xFFFF) + (sum >> 16);
13213 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13214 			/*
13215 			 * Don't verify header checksum if this packet
13216 			 * is coming back from AH/ESP as we already did it.
13217 			 */
13218 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
13219 				BUMP_MIB(ill->ill_ip_mib,
13220 				    ipIfStatsInCksumErrs);
13221 				goto error;
13222 			}
13223 		}
13224 	}
13225 
13226 	if (!mctl_present) {
13227 		UPDATE_IB_PKT_COUNT(ire);
13228 		ire->ire_last_used_time = lbolt;
13229 	}
13230 
13231 	/* packet part of fragmented IP packet? */
13232 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13233 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13234 		goto fragmented;
13235 	}
13236 
13237 	/* u1 = IP header length (20 bytes) */
13238 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
13239 
13240 	/* does packet contain IP+TCP headers? */
13241 	len = mp->b_wptr - rptr;
13242 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
13243 		IP_STAT(ipst, ip_tcppullup);
13244 		goto tcppullup;
13245 	}
13246 
13247 	/* TCP options present? */
13248 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
13249 
13250 	/*
13251 	 * If options need to be pulled up, then goto tcpoptions.
13252 	 * otherwise we are still in the fast path
13253 	 */
13254 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
13255 		IP_STAT(ipst, ip_tcpoptions);
13256 		goto tcpoptions;
13257 	}
13258 
13259 	/* multiple mblks of tcp data? */
13260 	if ((mp1 = mp->b_cont) != NULL) {
13261 		/* more then two? */
13262 		if (mp1->b_cont != NULL) {
13263 			IP_STAT(ipst, ip_multipkttcp);
13264 			goto multipkttcp;
13265 		}
13266 		len += mp1->b_wptr - mp1->b_rptr;
13267 	}
13268 
13269 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
13270 
13271 	/* part of pseudo checksum */
13272 
13273 	/* TCP datagram length */
13274 	u1 = len - IP_SIMPLE_HDR_LENGTH;
13275 
13276 #define	iphs    ((uint16_t *)ipha)
13277 
13278 #ifdef	_BIG_ENDIAN
13279 	u1 += IPPROTO_TCP;
13280 #else
13281 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13282 #endif
13283 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13284 
13285 	/*
13286 	 * Revert to software checksum calculation if the interface
13287 	 * isn't capable of checksum offload or if IPsec is present.
13288 	 */
13289 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
13290 		hck_flags = DB_CKSUMFLAGS(mp);
13291 
13292 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13293 		IP_STAT(ipst, ip_in_sw_cksum);
13294 
13295 	IP_CKSUM_RECV(hck_flags, u1,
13296 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
13297 	    (int32_t)((uchar_t *)up - rptr),
13298 	    mp, mp1, cksum_err);
13299 
13300 	if (cksum_err) {
13301 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13302 
13303 		if (hck_flags & HCK_FULLCKSUM)
13304 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
13305 		else if (hck_flags & HCK_PARTIALCKSUM)
13306 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
13307 		else
13308 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
13309 
13310 		goto error;
13311 	}
13312 
13313 try_again:
13314 
13315 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
13316 	    zoneid, ipst)) == NULL) {
13317 		/* Send the TH_RST */
13318 		goto no_conn;
13319 	}
13320 
13321 	/*
13322 	 * TCP FAST PATH for AF_INET socket.
13323 	 *
13324 	 * TCP fast path to avoid extra work. An AF_INET socket type
13325 	 * does not have facility to receive extra information via
13326 	 * ip_process or ip_add_info. Also, when the connection was
13327 	 * established, we made a check if this connection is impacted
13328 	 * by any global IPSec policy or per connection policy (a
13329 	 * policy that comes in effect later will not apply to this
13330 	 * connection). Since all this can be determined at the
13331 	 * connection establishment time, a quick check of flags
13332 	 * can avoid extra work.
13333 	 */
13334 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13335 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13336 		ASSERT(first_mp == mp);
13337 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13338 		SET_SQUEUE(mp, tcp_rput_data, connp);
13339 		return (mp);
13340 	}
13341 
13342 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
13343 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
13344 		if (IPCL_IS_TCP(connp)) {
13345 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13346 			DB_CKSUMSTART(mp) =
13347 			    (intptr_t)ip_squeue_get(ill_ring);
13348 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13349 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13350 				BUMP_MIB(ill->ill_ip_mib,
13351 				    ipIfStatsHCInDelivers);
13352 				SET_SQUEUE(mp, connp->conn_recv, connp);
13353 				return (mp);
13354 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13355 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13356 				BUMP_MIB(ill->ill_ip_mib,
13357 				    ipIfStatsHCInDelivers);
13358 				ip_squeue_enter_unbound++;
13359 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13360 				    connp);
13361 				return (mp);
13362 			}
13363 			syn_present = B_TRUE;
13364 		}
13365 
13366 	}
13367 
13368 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13369 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13370 
13371 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13372 		/* No need to send this packet to TCP */
13373 		if ((flags & TH_RST) || (flags & TH_URG)) {
13374 			CONN_DEC_REF(connp);
13375 			freemsg(first_mp);
13376 			return (NULL);
13377 		}
13378 		if (flags & TH_ACK) {
13379 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
13380 			    ipst->ips_netstack->netstack_tcp);
13381 			CONN_DEC_REF(connp);
13382 			return (NULL);
13383 		}
13384 
13385 		CONN_DEC_REF(connp);
13386 		freemsg(first_mp);
13387 		return (NULL);
13388 	}
13389 
13390 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13391 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13392 		    ipha, NULL, mctl_present);
13393 		if (first_mp == NULL) {
13394 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13395 			CONN_DEC_REF(connp);
13396 			return (NULL);
13397 		}
13398 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13399 			ASSERT(syn_present);
13400 			if (mctl_present) {
13401 				ASSERT(first_mp != mp);
13402 				first_mp->b_datap->db_struioflag |=
13403 				    STRUIO_POLICY;
13404 			} else {
13405 				ASSERT(first_mp == mp);
13406 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13407 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13408 			}
13409 		} else {
13410 			/*
13411 			 * Discard first_mp early since we're dealing with a
13412 			 * fully-connected conn_t and tcp doesn't do policy in
13413 			 * this case.
13414 			 */
13415 			if (mctl_present) {
13416 				freeb(first_mp);
13417 				mctl_present = B_FALSE;
13418 			}
13419 			first_mp = mp;
13420 		}
13421 	}
13422 
13423 	/* Initiate IPPF processing for fastpath */
13424 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13425 		uint32_t	ill_index;
13426 
13427 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13428 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13429 		if (mp == NULL) {
13430 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13431 			    "deferred/dropped during IPPF processing\n"));
13432 			CONN_DEC_REF(connp);
13433 			if (mctl_present)
13434 				freeb(first_mp);
13435 			return (NULL);
13436 		} else if (mctl_present) {
13437 			/*
13438 			 * ip_process might return a new mp.
13439 			 */
13440 			ASSERT(first_mp != mp);
13441 			first_mp->b_cont = mp;
13442 		} else {
13443 			first_mp = mp;
13444 		}
13445 
13446 	}
13447 
13448 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13449 		/*
13450 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13451 		 * make sure IPF_RECVIF is passed to ip_add_info.
13452 		 */
13453 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13454 		    IPCL_ZONEID(connp), ipst);
13455 		if (mp == NULL) {
13456 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13457 			CONN_DEC_REF(connp);
13458 			if (mctl_present)
13459 				freeb(first_mp);
13460 			return (NULL);
13461 		} else if (mctl_present) {
13462 			/*
13463 			 * ip_add_info might return a new mp.
13464 			 */
13465 			ASSERT(first_mp != mp);
13466 			first_mp->b_cont = mp;
13467 		} else {
13468 			first_mp = mp;
13469 		}
13470 	}
13471 
13472 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13473 	if (IPCL_IS_TCP(connp)) {
13474 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13475 		return (first_mp);
13476 	} else {
13477 		putnext(connp->conn_rq, first_mp);
13478 		CONN_DEC_REF(connp);
13479 		return (NULL);
13480 	}
13481 
13482 no_conn:
13483 	/* Initiate IPPf processing, if needed. */
13484 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13485 		uint32_t ill_index;
13486 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13487 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13488 		if (first_mp == NULL) {
13489 			return (NULL);
13490 		}
13491 	}
13492 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13493 
13494 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13495 	    ipst->ips_netstack->netstack_tcp);
13496 	return (NULL);
13497 ipoptions:
13498 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13499 		goto slow_done;
13500 	}
13501 
13502 	UPDATE_IB_PKT_COUNT(ire);
13503 	ire->ire_last_used_time = lbolt;
13504 
13505 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13506 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13507 fragmented:
13508 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
13509 			if (mctl_present)
13510 				freeb(first_mp);
13511 			goto slow_done;
13512 		}
13513 		/*
13514 		 * Make sure that first_mp points back to mp as
13515 		 * the mp we came in with could have changed in
13516 		 * ip_rput_fragment().
13517 		 */
13518 		ASSERT(!mctl_present);
13519 		ipha = (ipha_t *)mp->b_rptr;
13520 		first_mp = mp;
13521 	}
13522 
13523 	/* Now we have a complete datagram, destined for this machine. */
13524 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13525 
13526 	len = mp->b_wptr - mp->b_rptr;
13527 	/* Pull up a minimal TCP header, if necessary. */
13528 	if (len < (u1 + 20)) {
13529 tcppullup:
13530 		if (!pullupmsg(mp, u1 + 20)) {
13531 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13532 			goto error;
13533 		}
13534 		ipha = (ipha_t *)mp->b_rptr;
13535 		len = mp->b_wptr - mp->b_rptr;
13536 	}
13537 
13538 	/*
13539 	 * Extract the offset field from the TCP header.  As usual, we
13540 	 * try to help the compiler more than the reader.
13541 	 */
13542 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13543 	if (offset != 5) {
13544 tcpoptions:
13545 		if (offset < 5) {
13546 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13547 			goto error;
13548 		}
13549 		/*
13550 		 * There must be TCP options.
13551 		 * Make sure we can grab them.
13552 		 */
13553 		offset <<= 2;
13554 		offset += u1;
13555 		if (len < offset) {
13556 			if (!pullupmsg(mp, offset)) {
13557 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13558 				goto error;
13559 			}
13560 			ipha = (ipha_t *)mp->b_rptr;
13561 			len = mp->b_wptr - rptr;
13562 		}
13563 	}
13564 
13565 	/* Get the total packet length in len, including headers. */
13566 	if (mp->b_cont) {
13567 multipkttcp:
13568 		len = msgdsize(mp);
13569 	}
13570 
13571 	/*
13572 	 * Check the TCP checksum by pulling together the pseudo-
13573 	 * header checksum, and passing it to ip_csum to be added in
13574 	 * with the TCP datagram.
13575 	 *
13576 	 * Since we are not using the hwcksum if available we must
13577 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13578 	 * If either of these fails along the way the mblk is freed.
13579 	 * If this logic ever changes and mblk is reused to say send
13580 	 * ICMP's back, then this flag may need to be cleared in
13581 	 * other places as well.
13582 	 */
13583 	DB_CKSUMFLAGS(mp) = 0;
13584 
13585 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13586 
13587 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13588 #ifdef	_BIG_ENDIAN
13589 	u1 += IPPROTO_TCP;
13590 #else
13591 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13592 #endif
13593 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13594 	/*
13595 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13596 	 */
13597 	IP_STAT(ipst, ip_in_sw_cksum);
13598 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13599 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13600 		goto error;
13601 	}
13602 
13603 	IP_STAT(ipst, ip_tcp_slow_path);
13604 	goto try_again;
13605 #undef  iphs
13606 #undef  rptr
13607 
13608 error:
13609 	freemsg(first_mp);
13610 slow_done:
13611 	return (NULL);
13612 }
13613 
13614 /* ARGSUSED */
13615 static void
13616 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13617     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13618 {
13619 	conn_t		*connp;
13620 	uint32_t	sum;
13621 	uint32_t	u1;
13622 	ssize_t		len;
13623 	sctp_hdr_t	*sctph;
13624 	zoneid_t	zoneid = ire->ire_zoneid;
13625 	uint32_t	pktsum;
13626 	uint32_t	calcsum;
13627 	uint32_t	ports;
13628 	in6_addr_t	map_src, map_dst;
13629 	ill_t		*ill = (ill_t *)q->q_ptr;
13630 	ip_stack_t	*ipst;
13631 	sctp_stack_t	*sctps;
13632 
13633 	ASSERT(recv_ill != NULL);
13634 	ipst = recv_ill->ill_ipst;
13635 	sctps = ipst->ips_netstack->netstack_sctp;
13636 
13637 #define	rptr	((uchar_t *)ipha)
13638 
13639 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13640 	ASSERT(ill != NULL);
13641 
13642 	/* u1 is # words of IP options */
13643 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13644 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13645 
13646 	/* IP options present */
13647 	if (u1 > 0) {
13648 		goto ipoptions;
13649 	} else {
13650 		/* Check the IP header checksum.  */
13651 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
13652 #define	uph	((uint16_t *)ipha)
13653 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13654 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13655 #undef	uph
13656 			/* finish doing IP checksum */
13657 			sum = (sum & 0xFFFF) + (sum >> 16);
13658 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13659 			/*
13660 			 * Don't verify header checksum if this packet
13661 			 * is coming back from AH/ESP as we already did it.
13662 			 */
13663 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
13664 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13665 				goto error;
13666 			}
13667 		}
13668 		/*
13669 		 * Since there is no SCTP h/w cksum support yet, just
13670 		 * clear the flag.
13671 		 */
13672 		DB_CKSUMFLAGS(mp) = 0;
13673 	}
13674 
13675 	/*
13676 	 * Don't verify header checksum if this packet is coming
13677 	 * back from AH/ESP as we already did it.
13678 	 */
13679 	if (!mctl_present) {
13680 		UPDATE_IB_PKT_COUNT(ire);
13681 		ire->ire_last_used_time = lbolt;
13682 	}
13683 
13684 	/* packet part of fragmented IP packet? */
13685 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13686 	if (u1 & (IPH_MF | IPH_OFFSET))
13687 		goto fragmented;
13688 
13689 	/* u1 = IP header length (20 bytes) */
13690 	u1 = IP_SIMPLE_HDR_LENGTH;
13691 
13692 find_sctp_client:
13693 	/* Pullup if we don't have the sctp common header. */
13694 	len = MBLKL(mp);
13695 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13696 		if (mp->b_cont == NULL ||
13697 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13698 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13699 			goto error;
13700 		}
13701 		ipha = (ipha_t *)mp->b_rptr;
13702 		len = MBLKL(mp);
13703 	}
13704 
13705 	sctph = (sctp_hdr_t *)(rptr + u1);
13706 #ifdef	DEBUG
13707 	if (!skip_sctp_cksum) {
13708 #endif
13709 		pktsum = sctph->sh_chksum;
13710 		sctph->sh_chksum = 0;
13711 		calcsum = sctp_cksum(mp, u1);
13712 		if (calcsum != pktsum) {
13713 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
13714 			goto error;
13715 		}
13716 		sctph->sh_chksum = pktsum;
13717 #ifdef	DEBUG	/* skip_sctp_cksum */
13718 	}
13719 #endif
13720 	/* get the ports */
13721 	ports = *(uint32_t *)&sctph->sh_sport;
13722 
13723 	IRE_REFRELE(ire);
13724 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13725 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13726 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13727 	    sctps)) == NULL) {
13728 		/* Check for raw socket or OOTB handling */
13729 		goto no_conn;
13730 	}
13731 
13732 	/* Found a client; up it goes */
13733 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13734 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13735 	return;
13736 
13737 no_conn:
13738 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13739 	    ports, mctl_present, flags, B_TRUE, zoneid);
13740 	return;
13741 
13742 ipoptions:
13743 	DB_CKSUMFLAGS(mp) = 0;
13744 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13745 		goto slow_done;
13746 
13747 	UPDATE_IB_PKT_COUNT(ire);
13748 	ire->ire_last_used_time = lbolt;
13749 
13750 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13751 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13752 fragmented:
13753 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
13754 			goto slow_done;
13755 		/*
13756 		 * Make sure that first_mp points back to mp as
13757 		 * the mp we came in with could have changed in
13758 		 * ip_rput_fragment().
13759 		 */
13760 		ASSERT(!mctl_present);
13761 		ipha = (ipha_t *)mp->b_rptr;
13762 		first_mp = mp;
13763 	}
13764 
13765 	/* Now we have a complete datagram, destined for this machine. */
13766 	u1 = IPH_HDR_LENGTH(ipha);
13767 	goto find_sctp_client;
13768 #undef  iphs
13769 #undef  rptr
13770 
13771 error:
13772 	freemsg(first_mp);
13773 slow_done:
13774 	IRE_REFRELE(ire);
13775 }
13776 
13777 #define	VER_BITS	0xF0
13778 #define	VERSION_6	0x60
13779 
13780 static boolean_t
13781 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13782     ipaddr_t *dstp, ip_stack_t *ipst)
13783 {
13784 	uint_t	opt_len;
13785 	ipha_t *ipha;
13786 	ssize_t len;
13787 	uint_t	pkt_len;
13788 
13789 	ASSERT(ill != NULL);
13790 	IP_STAT(ipst, ip_ipoptions);
13791 	ipha = *iphapp;
13792 
13793 #define	rptr    ((uchar_t *)ipha)
13794 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13795 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13796 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13797 		freemsg(mp);
13798 		return (B_FALSE);
13799 	}
13800 
13801 	/* multiple mblk or too short */
13802 	pkt_len = ntohs(ipha->ipha_length);
13803 
13804 	/* Get the number of words of IP options in the IP header. */
13805 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13806 	if (opt_len) {
13807 		/* IP Options present!  Validate and process. */
13808 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13809 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13810 			goto done;
13811 		}
13812 		/*
13813 		 * Recompute complete header length and make sure we
13814 		 * have access to all of it.
13815 		 */
13816 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13817 		if (len > (mp->b_wptr - rptr)) {
13818 			if (len > pkt_len) {
13819 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13820 				goto done;
13821 			}
13822 			if (!pullupmsg(mp, len)) {
13823 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13824 				goto done;
13825 			}
13826 			ipha = (ipha_t *)mp->b_rptr;
13827 		}
13828 		/*
13829 		 * Go off to ip_rput_options which returns the next hop
13830 		 * destination address, which may have been affected
13831 		 * by source routing.
13832 		 */
13833 		IP_STAT(ipst, ip_opt);
13834 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13835 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13836 			return (B_FALSE);
13837 		}
13838 	}
13839 	*iphapp = ipha;
13840 	return (B_TRUE);
13841 done:
13842 	/* clear b_prev - used by ip_mroute_decap */
13843 	mp->b_prev = NULL;
13844 	freemsg(mp);
13845 	return (B_FALSE);
13846 #undef  rptr
13847 }
13848 
13849 /*
13850  * Deal with the fact that there is no ire for the destination.
13851  * The incoming ill (in_ill) is passed in to ip_newroute only
13852  * in the case of packets coming from mobile ip forward tunnel.
13853  * It must be null otherwise.
13854  */
13855 static ire_t *
13856 ip_rput_noire(queue_t *q, ill_t *in_ill, mblk_t *mp, int ll_multicast,
13857     ipaddr_t dst)
13858 {
13859 	ipha_t	*ipha;
13860 	ill_t	*ill;
13861 	ire_t	*ire;
13862 	boolean_t	check_multirt = B_FALSE;
13863 	ip_stack_t *ipst;
13864 
13865 	ipha = (ipha_t *)mp->b_rptr;
13866 	ill = (ill_t *)q->q_ptr;
13867 
13868 	ASSERT(ill != NULL);
13869 	ipst = ill->ill_ipst;
13870 
13871 	/*
13872 	 * No IRE for this destination, so it can't be for us.
13873 	 * Unless we are forwarding, drop the packet.
13874 	 * We have to let source routed packets through
13875 	 * since we don't yet know if they are 'ping -l'
13876 	 * packets i.e. if they will go out over the
13877 	 * same interface as they came in on.
13878 	 */
13879 	if (ll_multicast) {
13880 		freemsg(mp);
13881 		return (NULL);
13882 	}
13883 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13884 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13885 		freemsg(mp);
13886 		return (NULL);
13887 	}
13888 
13889 	/*
13890 	 * Mark this packet as having originated externally.
13891 	 *
13892 	 * For non-forwarding code path, ire_send later double
13893 	 * checks this interface to see if it is still exists
13894 	 * post-ARP resolution.
13895 	 *
13896 	 * Also, IPQOS uses this to differentiate between
13897 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13898 	 * QOS packet processing in ip_wput_attach_llhdr().
13899 	 * The QoS module can mark the b_band for a fastpath message
13900 	 * or the dl_priority field in a unitdata_req header for
13901 	 * CoS marking. This info can only be found in
13902 	 * ip_wput_attach_llhdr().
13903 	 */
13904 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13905 	/*
13906 	 * Clear the indication that this may have a hardware checksum
13907 	 * as we are not using it
13908 	 */
13909 	DB_CKSUMFLAGS(mp) = 0;
13910 
13911 	if (in_ill != NULL) {
13912 		/*
13913 		 * Now hand the packet to ip_newroute.
13914 		 */
13915 		ip_newroute(q, mp, dst, in_ill, NULL, GLOBAL_ZONEID, ipst);
13916 		return (NULL);
13917 	}
13918 	ire = ire_forward(dst, &check_multirt, NULL, NULL,
13919 	    MBLK_GETLABEL(mp), ipst);
13920 
13921 	if (ire == NULL && check_multirt) {
13922 		/* Let ip_newroute handle CGTP  */
13923 		ip_newroute(q, mp, dst, in_ill, NULL, GLOBAL_ZONEID, ipst);
13924 		return (NULL);
13925 	}
13926 
13927 	if (ire != NULL)
13928 		return (ire);
13929 
13930 	mp->b_prev = mp->b_next = 0;
13931 	/* send icmp unreachable */
13932 	q = WR(q);
13933 	/* Sent by forwarding path, and router is global zone */
13934 	if (ip_source_routed(ipha, ipst)) {
13935 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13936 		    GLOBAL_ZONEID, ipst);
13937 	} else {
13938 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13939 		    ipst);
13940 	}
13941 
13942 	return (NULL);
13943 
13944 }
13945 
13946 /*
13947  * check ip header length and align it.
13948  */
13949 static boolean_t
13950 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13951 {
13952 	ssize_t len;
13953 	ill_t *ill;
13954 	ipha_t	*ipha;
13955 
13956 	len = MBLKL(mp);
13957 
13958 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13959 		ill = (ill_t *)q->q_ptr;
13960 
13961 		if (!OK_32PTR(mp->b_rptr))
13962 			IP_STAT(ipst, ip_notaligned1);
13963 		else
13964 			IP_STAT(ipst, ip_notaligned2);
13965 		/* Guard against bogus device drivers */
13966 		if (len < 0) {
13967 			/* clear b_prev - used by ip_mroute_decap */
13968 			mp->b_prev = NULL;
13969 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13970 			freemsg(mp);
13971 			return (B_FALSE);
13972 		}
13973 
13974 		if (ip_rput_pullups++ == 0) {
13975 			ipha = (ipha_t *)mp->b_rptr;
13976 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13977 			    "ip_check_and_align_header: %s forced us to "
13978 			    " pullup pkt, hdr len %ld, hdr addr %p",
13979 			    ill->ill_name, len, ipha);
13980 		}
13981 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13982 			/* clear b_prev - used by ip_mroute_decap */
13983 			mp->b_prev = NULL;
13984 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13985 			freemsg(mp);
13986 			return (B_FALSE);
13987 		}
13988 	}
13989 	return (B_TRUE);
13990 }
13991 
13992 ire_t *
13993 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13994 {
13995 	ire_t		*new_ire;
13996 	ill_t		*ire_ill;
13997 	uint_t		ifindex;
13998 	ip_stack_t	*ipst = ill->ill_ipst;
13999 	boolean_t	strict_check = B_FALSE;
14000 
14001 	/*
14002 	 * This packet came in on an interface other than the one associated
14003 	 * with the first ire we found for the destination address. We do
14004 	 * another ire lookup here, using the ingress ill, to see if the
14005 	 * interface is in an interface group.
14006 	 * As long as the ills belong to the same group, we don't consider
14007 	 * them to be arriving on the wrong interface. Thus, if the switch
14008 	 * is doing inbound load spreading, we won't drop packets when the
14009 	 * ip*_strict_dst_multihoming switch is on. Note, the same holds true
14010 	 * for 'usesrc groups' where the destination address may belong to
14011 	 * another interface to allow multipathing to happen.
14012 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
14013 	 * where the local address may not be unique. In this case we were
14014 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
14015 	 * actually returned. The new lookup, which is more specific, should
14016 	 * only find the IRE_LOCAL associated with the ingress ill if one
14017 	 * exists.
14018 	 */
14019 
14020 	if (ire->ire_ipversion == IPV4_VERSION) {
14021 		if (ipst->ips_ip_strict_dst_multihoming)
14022 			strict_check = B_TRUE;
14023 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
14024 		    ill->ill_ipif, ALL_ZONES, NULL,
14025 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
14026 	} else {
14027 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
14028 		if (ipst->ips_ipv6_strict_dst_multihoming)
14029 			strict_check = B_TRUE;
14030 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
14031 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
14032 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
14033 	}
14034 	/*
14035 	 * If the same ire that was returned in ip_input() is found then this
14036 	 * is an indication that interface groups are in use. The packet
14037 	 * arrived on a different ill in the group than the one associated with
14038 	 * the destination address.  If a different ire was found then the same
14039 	 * IP address must be hosted on multiple ills. This is possible with
14040 	 * unnumbered point2point interfaces. We switch to use this new ire in
14041 	 * order to have accurate interface statistics.
14042 	 */
14043 	if (new_ire != NULL) {
14044 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
14045 			ire_refrele(ire);
14046 			ire = new_ire;
14047 		} else {
14048 			ire_refrele(new_ire);
14049 		}
14050 		return (ire);
14051 	} else if ((ire->ire_rfq == NULL) &&
14052 	    (ire->ire_ipversion == IPV4_VERSION)) {
14053 		/*
14054 		 * The best match could have been the original ire which
14055 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
14056 		 * the strict multihoming checks are irrelevant as we consider
14057 		 * local addresses hosted on lo0 to be interface agnostic. We
14058 		 * only expect a null ire_rfq on IREs which are associated with
14059 		 * lo0 hence we can return now.
14060 		 */
14061 		return (ire);
14062 	}
14063 
14064 	/*
14065 	 * Chase pointers once and store locally.
14066 	 */
14067 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
14068 	    (ill_t *)(ire->ire_rfq->q_ptr);
14069 	ifindex = ill->ill_usesrc_ifindex;
14070 
14071 	/*
14072 	 * Check if it's a legal address on the 'usesrc' interface.
14073 	 */
14074 	if ((ifindex != 0) && (ire_ill != NULL) &&
14075 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
14076 		return (ire);
14077 	}
14078 
14079 	/*
14080 	 * If the ip*_strict_dst_multihoming switch is on then we can
14081 	 * only accept this packet if the interface is marked as routing.
14082 	 */
14083 	if (!(strict_check))
14084 		return (ire);
14085 
14086 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
14087 	    ILLF_ROUTER) != 0) {
14088 		return (ire);
14089 	}
14090 
14091 	ire_refrele(ire);
14092 	return (NULL);
14093 }
14094 
14095 ire_t *
14096 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
14097 {
14098 	ipha_t	*ipha;
14099 	ipaddr_t ip_dst, ip_src;
14100 	ire_t	*src_ire = NULL;
14101 	ill_t	*stq_ill;
14102 	uint_t	hlen;
14103 	uint_t	pkt_len;
14104 	uint32_t sum;
14105 	queue_t	*dev_q;
14106 	boolean_t check_multirt = B_FALSE;
14107 	ip_stack_t *ipst = ill->ill_ipst;
14108 
14109 	ipha = (ipha_t *)mp->b_rptr;
14110 
14111 	/*
14112 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
14113 	 * The loopback address check for both src and dst has already
14114 	 * been checked in ip_input
14115 	 */
14116 	ip_dst = ntohl(dst);
14117 	ip_src = ntohl(ipha->ipha_src);
14118 
14119 	if (ip_dst == INADDR_ANY || IN_BADCLASS(ip_dst) ||
14120 	    IN_CLASSD(ip_src)) {
14121 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14122 		goto drop;
14123 	}
14124 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14125 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14126 
14127 	if (src_ire != NULL) {
14128 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14129 		goto drop;
14130 	}
14131 
14132 
14133 	/* No ire cache of nexthop. So first create one  */
14134 	if (ire == NULL) {
14135 		ire = ire_forward(dst, &check_multirt, NULL, NULL, NULL, ipst);
14136 		/*
14137 		 * We only come to ip_fast_forward if ip_cgtp_filter is
14138 		 * is not set. So upon return from ire_forward
14139 		 * check_multirt should remain as false.
14140 		 */
14141 		ASSERT(!check_multirt);
14142 		if (ire == NULL) {
14143 			/* An attempt was made to forward the packet */
14144 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14145 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14146 			mp->b_prev = mp->b_next = 0;
14147 			/* send icmp unreachable */
14148 			/* Sent by forwarding path, and router is global zone */
14149 			if (ip_source_routed(ipha, ipst)) {
14150 				icmp_unreachable(ill->ill_wq, mp,
14151 				    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID,
14152 				    ipst);
14153 			} else {
14154 				icmp_unreachable(ill->ill_wq, mp,
14155 				    ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
14156 				    ipst);
14157 			}
14158 			return (ire);
14159 		}
14160 	}
14161 
14162 	/*
14163 	 * Forwarding fastpath exception case:
14164 	 * If either of the follwoing case is true, we take
14165 	 * the slowpath
14166 	 *	o forwarding is not enabled
14167 	 *	o incoming and outgoing interface are the same, or the same
14168 	 *	  IPMP group
14169 	 *	o corresponding ire is in incomplete state
14170 	 *	o packet needs fragmentation
14171 	 *
14172 	 * The codeflow from here on is thus:
14173 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
14174 	 */
14175 	pkt_len = ntohs(ipha->ipha_length);
14176 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
14177 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
14178 	    !(ill->ill_flags & ILLF_ROUTER) ||
14179 	    (ill == stq_ill) ||
14180 	    (ill->ill_group != NULL && ill->ill_group == stq_ill->ill_group) ||
14181 	    (ire->ire_nce == NULL) ||
14182 	    (ire->ire_nce->nce_state != ND_REACHABLE) ||
14183 	    (pkt_len > ire->ire_max_frag) ||
14184 	    ipha->ipha_ttl <= 1) {
14185 		ip_rput_process_forward(ill->ill_rq, mp, ire,
14186 		    ipha, ill, B_FALSE);
14187 		return (ire);
14188 	}
14189 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14190 
14191 	DTRACE_PROBE4(ip4__forwarding__start,
14192 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
14193 
14194 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
14195 	    ipst->ips_ipv4firewall_forwarding,
14196 	    ill, stq_ill, ipha, mp, mp, ipst);
14197 
14198 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
14199 
14200 	if (mp == NULL)
14201 		goto drop;
14202 
14203 	mp->b_datap->db_struioun.cksum.flags = 0;
14204 	/* Adjust the checksum to reflect the ttl decrement. */
14205 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
14206 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
14207 	ipha->ipha_ttl--;
14208 
14209 	dev_q = ire->ire_stq->q_next;
14210 	if ((dev_q->q_next != NULL ||
14211 	    dev_q->q_first != NULL) && !canput(dev_q)) {
14212 		goto indiscard;
14213 	}
14214 
14215 	hlen = ire->ire_nce->nce_fp_mp != NULL ?
14216 	    MBLKL(ire->ire_nce->nce_fp_mp) : 0;
14217 
14218 	if (hlen != 0 || ire->ire_nce->nce_res_mp != NULL) {
14219 		mblk_t *mpip = mp;
14220 
14221 		mp = ip_wput_attach_llhdr(mpip, ire, 0, 0);
14222 		if (mp != NULL) {
14223 			DTRACE_PROBE4(ip4__physical__out__start,
14224 			    ill_t *, NULL, ill_t *, stq_ill,
14225 			    ipha_t *, ipha, mblk_t *, mp);
14226 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
14227 			    ipst->ips_ipv4firewall_physical_out,
14228 			    NULL, stq_ill, ipha, mp, mpip, ipst);
14229 			DTRACE_PROBE1(ip4__physical__out__end, mblk_t *,
14230 			    mp);
14231 			if (mp == NULL)
14232 				goto drop;
14233 
14234 			UPDATE_IB_PKT_COUNT(ire);
14235 			ire->ire_last_used_time = lbolt;
14236 			BUMP_MIB(stq_ill->ill_ip_mib,
14237 			    ipIfStatsHCOutForwDatagrams);
14238 			BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14239 			UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets,
14240 			    pkt_len);
14241 			putnext(ire->ire_stq, mp);
14242 			return (ire);
14243 		}
14244 	}
14245 
14246 indiscard:
14247 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14248 drop:
14249 	if (mp != NULL)
14250 		freemsg(mp);
14251 	if (src_ire != NULL)
14252 		ire_refrele(src_ire);
14253 	return (ire);
14254 
14255 }
14256 
14257 /*
14258  * This function is called in the forwarding slowpath, when
14259  * either the ire lacks the link-layer address, or the packet needs
14260  * further processing(eg. fragmentation), before transmission.
14261  */
14262 
14263 static void
14264 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14265     ill_t *ill, boolean_t ll_multicast)
14266 {
14267 	ill_group_t	*ill_group;
14268 	ill_group_t	*ire_group;
14269 	queue_t		*dev_q;
14270 	ire_t		*src_ire;
14271 	ip_stack_t	*ipst = ill->ill_ipst;
14272 
14273 	ASSERT(ire->ire_stq != NULL);
14274 
14275 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14276 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14277 
14278 	if (ll_multicast != 0) {
14279 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14280 		goto drop_pkt;
14281 	}
14282 
14283 	/*
14284 	 * check if ipha_src is a broadcast address. Note that this
14285 	 * check is redundant when we get here from ip_fast_forward()
14286 	 * which has already done this check. However, since we can
14287 	 * also get here from ip_rput_process_broadcast() or, for
14288 	 * for the slow path through ip_fast_forward(), we perform
14289 	 * the check again for code-reusability
14290 	 */
14291 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14292 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14293 	if (src_ire != NULL || ntohl(ipha->ipha_dst) == INADDR_ANY ||
14294 	    IN_BADCLASS(ntohl(ipha->ipha_dst))) {
14295 		if (src_ire != NULL)
14296 			ire_refrele(src_ire);
14297 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14298 		ip2dbg(("ip_rput_process_forward: Received packet with"
14299 		    " bad src/dst address on %s\n", ill->ill_name));
14300 		goto drop_pkt;
14301 	}
14302 
14303 	ill_group = ill->ill_group;
14304 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
14305 	/*
14306 	 * Check if we want to forward this one at this time.
14307 	 * We allow source routed packets on a host provided that
14308 	 * they go out the same interface or same interface group
14309 	 * as they came in on.
14310 	 *
14311 	 * XXX To be quicker, we may wish to not chase pointers to
14312 	 * get the ILLF_ROUTER flag and instead store the
14313 	 * forwarding policy in the ire.  An unfortunate
14314 	 * side-effect of that would be requiring an ire flush
14315 	 * whenever the ILLF_ROUTER flag changes.
14316 	 */
14317 	if (((ill->ill_flags &
14318 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
14319 	    ILLF_ROUTER) == 0) &&
14320 	    !(ip_source_routed(ipha, ipst) && (ire->ire_rfq == q ||
14321 	    (ill_group != NULL && ill_group == ire_group)))) {
14322 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14323 		if (ip_source_routed(ipha, ipst)) {
14324 			q = WR(q);
14325 			/*
14326 			 * Clear the indication that this may have
14327 			 * hardware checksum as we are not using it.
14328 			 */
14329 			DB_CKSUMFLAGS(mp) = 0;
14330 			/* Sent by forwarding path, and router is global zone */
14331 			icmp_unreachable(q, mp,
14332 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
14333 			return;
14334 		}
14335 		goto drop_pkt;
14336 	}
14337 
14338 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14339 
14340 	/* Packet is being forwarded. Turning off hwcksum flag. */
14341 	DB_CKSUMFLAGS(mp) = 0;
14342 	if (ipst->ips_ip_g_send_redirects) {
14343 		/*
14344 		 * Check whether the incoming interface and outgoing
14345 		 * interface is part of the same group. If so,
14346 		 * send redirects.
14347 		 *
14348 		 * Check the source address to see if it originated
14349 		 * on the same logical subnet it is going back out on.
14350 		 * If so, we should be able to send it a redirect.
14351 		 * Avoid sending a redirect if the destination
14352 		 * is directly connected (i.e., ipha_dst is the same
14353 		 * as ire_gateway_addr or the ire_addr of the
14354 		 * nexthop IRE_CACHE ), or if the packet was source
14355 		 * routed out this interface.
14356 		 */
14357 		ipaddr_t src, nhop;
14358 		mblk_t	*mp1;
14359 		ire_t	*nhop_ire = NULL;
14360 
14361 		/*
14362 		 * Check whether ire_rfq and q are from the same ill
14363 		 * or if they are not same, they at least belong
14364 		 * to the same group. If so, send redirects.
14365 		 */
14366 		if ((ire->ire_rfq == q ||
14367 		    (ill_group != NULL && ill_group == ire_group)) &&
14368 		    !ip_source_routed(ipha, ipst)) {
14369 
14370 			nhop = (ire->ire_gateway_addr != 0 ?
14371 			    ire->ire_gateway_addr : ire->ire_addr);
14372 
14373 			if (ipha->ipha_dst == nhop) {
14374 				/*
14375 				 * We avoid sending a redirect if the
14376 				 * destination is directly connected
14377 				 * because it is possible that multiple
14378 				 * IP subnets may have been configured on
14379 				 * the link, and the source may not
14380 				 * be on the same subnet as ip destination,
14381 				 * even though they are on the same
14382 				 * physical link.
14383 				 */
14384 				goto sendit;
14385 			}
14386 
14387 			src = ipha->ipha_src;
14388 
14389 			/*
14390 			 * We look up the interface ire for the nexthop,
14391 			 * to see if ipha_src is in the same subnet
14392 			 * as the nexthop.
14393 			 *
14394 			 * Note that, if, in the future, IRE_CACHE entries
14395 			 * are obsoleted,  this lookup will not be needed,
14396 			 * as the ire passed to this function will be the
14397 			 * same as the nhop_ire computed below.
14398 			 */
14399 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14400 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14401 			    0, NULL, MATCH_IRE_TYPE, ipst);
14402 
14403 			if (nhop_ire != NULL) {
14404 				if ((src & nhop_ire->ire_mask) ==
14405 				    (nhop & nhop_ire->ire_mask)) {
14406 					/*
14407 					 * The source is directly connected.
14408 					 * Just copy the ip header (which is
14409 					 * in the first mblk)
14410 					 */
14411 					mp1 = copyb(mp);
14412 					if (mp1 != NULL) {
14413 						icmp_send_redirect(WR(q), mp1,
14414 						    nhop, ipst);
14415 					}
14416 				}
14417 				ire_refrele(nhop_ire);
14418 			}
14419 		}
14420 	}
14421 sendit:
14422 	dev_q = ire->ire_stq->q_next;
14423 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
14424 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14425 		freemsg(mp);
14426 		return;
14427 	}
14428 
14429 	ip_rput_forward(ire, ipha, mp, ill);
14430 	return;
14431 
14432 drop_pkt:
14433 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14434 	freemsg(mp);
14435 }
14436 
14437 ire_t *
14438 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14439     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14440 {
14441 	queue_t		*q;
14442 	uint16_t	hcksumflags;
14443 	ip_stack_t	*ipst = ill->ill_ipst;
14444 
14445 	q = *qp;
14446 
14447 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14448 
14449 	/*
14450 	 * Clear the indication that this may have hardware
14451 	 * checksum as we are not using it for forwarding.
14452 	 */
14453 	hcksumflags = DB_CKSUMFLAGS(mp);
14454 	DB_CKSUMFLAGS(mp) = 0;
14455 
14456 	/*
14457 	 * Directed broadcast forwarding: if the packet came in over a
14458 	 * different interface then it is routed out over we can forward it.
14459 	 */
14460 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14461 		ire_refrele(ire);
14462 		freemsg(mp);
14463 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14464 		return (NULL);
14465 	}
14466 	/*
14467 	 * For multicast we have set dst to be INADDR_BROADCAST
14468 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
14469 	 * only for broadcast packets.
14470 	 */
14471 	if (!CLASSD(ipha->ipha_dst)) {
14472 		ire_t *new_ire;
14473 		ipif_t *ipif;
14474 		/*
14475 		 * For ill groups, as the switch duplicates broadcasts
14476 		 * across all the ports, we need to filter out and
14477 		 * send up only one copy. There is one copy for every
14478 		 * broadcast address on each ill. Thus, we look for a
14479 		 * specific IRE on this ill and look at IRE_MARK_NORECV
14480 		 * later to see whether this ill is eligible to receive
14481 		 * them or not. ill_nominate_bcast_rcv() nominates only
14482 		 * one set of IREs for receiving.
14483 		 */
14484 
14485 		ipif = ipif_get_next_ipif(NULL, ill);
14486 		if (ipif == NULL) {
14487 			ire_refrele(ire);
14488 			freemsg(mp);
14489 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14490 			return (NULL);
14491 		}
14492 		new_ire = ire_ctable_lookup(dst, 0, 0,
14493 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14494 		ipif_refrele(ipif);
14495 
14496 		if (new_ire != NULL) {
14497 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
14498 				ire_refrele(ire);
14499 				ire_refrele(new_ire);
14500 				freemsg(mp);
14501 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14502 				return (NULL);
14503 			}
14504 			/*
14505 			 * In the special case of multirouted broadcast
14506 			 * packets, we unconditionally need to "gateway"
14507 			 * them to the appropriate interface here.
14508 			 * In the normal case, this cannot happen, because
14509 			 * there is no broadcast IRE tagged with the
14510 			 * RTF_MULTIRT flag.
14511 			 */
14512 			if (new_ire->ire_flags & RTF_MULTIRT) {
14513 				ire_refrele(new_ire);
14514 				if (ire->ire_rfq != NULL) {
14515 					q = ire->ire_rfq;
14516 					*qp = q;
14517 				}
14518 			} else {
14519 				ire_refrele(ire);
14520 				ire = new_ire;
14521 			}
14522 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14523 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14524 				/*
14525 				 * Free the message if
14526 				 * ip_g_forward_directed_bcast is turned
14527 				 * off for non-local broadcast.
14528 				 */
14529 				ire_refrele(ire);
14530 				freemsg(mp);
14531 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14532 				return (NULL);
14533 			}
14534 		} else {
14535 			/*
14536 			 * This CGTP packet successfully passed the
14537 			 * CGTP filter, but the related CGTP
14538 			 * broadcast IRE has not been found,
14539 			 * meaning that the redundant ipif is
14540 			 * probably down. However, if we discarded
14541 			 * this packet, its duplicate would be
14542 			 * filtered out by the CGTP filter so none
14543 			 * of them would get through. So we keep
14544 			 * going with this one.
14545 			 */
14546 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14547 			if (ire->ire_rfq != NULL) {
14548 				q = ire->ire_rfq;
14549 				*qp = q;
14550 			}
14551 		}
14552 	}
14553 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14554 		/*
14555 		 * Verify that there are not more then one
14556 		 * IRE_BROADCAST with this broadcast address which
14557 		 * has ire_stq set.
14558 		 * TODO: simplify, loop over all IRE's
14559 		 */
14560 		ire_t	*ire1;
14561 		int	num_stq = 0;
14562 		mblk_t	*mp1;
14563 
14564 		/* Find the first one with ire_stq set */
14565 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14566 		for (ire1 = ire; ire1 &&
14567 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14568 		    ire1 = ire1->ire_next)
14569 			;
14570 		if (ire1) {
14571 			ire_refrele(ire);
14572 			ire = ire1;
14573 			IRE_REFHOLD(ire);
14574 		}
14575 
14576 		/* Check if there are additional ones with stq set */
14577 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14578 			if (ire->ire_addr != ire1->ire_addr)
14579 				break;
14580 			if (ire1->ire_stq) {
14581 				num_stq++;
14582 				break;
14583 			}
14584 		}
14585 		rw_exit(&ire->ire_bucket->irb_lock);
14586 		if (num_stq == 1 && ire->ire_stq != NULL) {
14587 			ip1dbg(("ip_rput_process_broadcast: directed "
14588 			    "broadcast to 0x%x\n",
14589 			    ntohl(ire->ire_addr)));
14590 			mp1 = copymsg(mp);
14591 			if (mp1) {
14592 				switch (ipha->ipha_protocol) {
14593 				case IPPROTO_UDP:
14594 					ip_udp_input(q, mp1, ipha, ire, ill);
14595 					break;
14596 				default:
14597 					ip_proto_input(q, mp1, ipha, ire, ill);
14598 					break;
14599 				}
14600 			}
14601 			/*
14602 			 * Adjust ttl to 2 (1+1 - the forward engine
14603 			 * will decrement it by one.
14604 			 */
14605 			if (ip_csum_hdr(ipha)) {
14606 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14607 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14608 				freemsg(mp);
14609 				ire_refrele(ire);
14610 				return (NULL);
14611 			}
14612 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14613 			ipha->ipha_hdr_checksum = 0;
14614 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14615 			ip_rput_process_forward(q, mp, ire, ipha,
14616 			    ill, ll_multicast);
14617 			ire_refrele(ire);
14618 			return (NULL);
14619 		}
14620 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14621 		    ntohl(ire->ire_addr)));
14622 	}
14623 
14624 
14625 	/* Restore any hardware checksum flags */
14626 	DB_CKSUMFLAGS(mp) = hcksumflags;
14627 	return (ire);
14628 }
14629 
14630 /* ARGSUSED */
14631 static boolean_t
14632 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14633     int *ll_multicast, ipaddr_t *dstp)
14634 {
14635 	ip_stack_t	*ipst = ill->ill_ipst;
14636 
14637 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14638 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14639 	    ntohs(ipha->ipha_length));
14640 
14641 	/*
14642 	 * Forward packets only if we have joined the allmulti
14643 	 * group on this interface.
14644 	 */
14645 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14646 		int retval;
14647 
14648 		/*
14649 		 * Clear the indication that this may have hardware
14650 		 * checksum as we are not using it.
14651 		 */
14652 		DB_CKSUMFLAGS(mp) = 0;
14653 		retval = ip_mforward(ill, ipha, mp);
14654 		/* ip_mforward updates mib variables if needed */
14655 		/* clear b_prev - used by ip_mroute_decap */
14656 		mp->b_prev = NULL;
14657 
14658 		switch (retval) {
14659 		case 0:
14660 			/*
14661 			 * pkt is okay and arrived on phyint.
14662 			 *
14663 			 * If we are running as a multicast router
14664 			 * we need to see all IGMP and/or PIM packets.
14665 			 */
14666 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14667 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14668 				goto done;
14669 			}
14670 			break;
14671 		case -1:
14672 			/* pkt is mal-formed, toss it */
14673 			goto drop_pkt;
14674 		case 1:
14675 			/* pkt is okay and arrived on a tunnel */
14676 			/*
14677 			 * If we are running a multicast router
14678 			 *  we need to see all igmp packets.
14679 			 */
14680 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14681 				*dstp = INADDR_BROADCAST;
14682 				*ll_multicast = 1;
14683 				return (B_FALSE);
14684 			}
14685 
14686 			goto drop_pkt;
14687 		}
14688 	}
14689 
14690 	ILM_WALKER_HOLD(ill);
14691 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14692 		/*
14693 		 * This might just be caused by the fact that
14694 		 * multiple IP Multicast addresses map to the same
14695 		 * link layer multicast - no need to increment counter!
14696 		 */
14697 		ILM_WALKER_RELE(ill);
14698 		freemsg(mp);
14699 		return (B_TRUE);
14700 	}
14701 	ILM_WALKER_RELE(ill);
14702 done:
14703 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14704 	/*
14705 	 * This assumes the we deliver to all streams for multicast
14706 	 * and broadcast packets.
14707 	 */
14708 	*dstp = INADDR_BROADCAST;
14709 	*ll_multicast = 1;
14710 	return (B_FALSE);
14711 drop_pkt:
14712 	ip2dbg(("ip_rput: drop pkt\n"));
14713 	freemsg(mp);
14714 	return (B_TRUE);
14715 }
14716 
14717 static boolean_t
14718 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14719     int *ll_multicast, mblk_t **mpp)
14720 {
14721 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14722 	boolean_t must_copy = B_FALSE;
14723 	struct iocblk   *iocp;
14724 	ipha_t		*ipha;
14725 	ip_stack_t	*ipst = ill->ill_ipst;
14726 
14727 #define	rptr    ((uchar_t *)ipha)
14728 
14729 	first_mp = *first_mpp;
14730 	mp = *mpp;
14731 
14732 	ASSERT(first_mp == mp);
14733 
14734 	/*
14735 	 * if db_ref > 1 then copymsg and free original. Packet may be
14736 	 * changed and do not want other entity who has a reference to this
14737 	 * message to trip over the changes. This is a blind change because
14738 	 * trying to catch all places that might change packet is too
14739 	 * difficult (since it may be a module above this one)
14740 	 *
14741 	 * This corresponds to the non-fast path case. We walk down the full
14742 	 * chain in this case, and check the db_ref count of all the dblks,
14743 	 * and do a copymsg if required. It is possible that the db_ref counts
14744 	 * of the data blocks in the mblk chain can be different.
14745 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14746 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14747 	 * 'snoop' is running.
14748 	 */
14749 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14750 		if (mp1->b_datap->db_ref > 1) {
14751 			must_copy = B_TRUE;
14752 			break;
14753 		}
14754 	}
14755 
14756 	if (must_copy) {
14757 		mp1 = copymsg(mp);
14758 		if (mp1 == NULL) {
14759 			for (mp1 = mp; mp1 != NULL;
14760 			    mp1 = mp1->b_cont) {
14761 				mp1->b_next = NULL;
14762 				mp1->b_prev = NULL;
14763 			}
14764 			freemsg(mp);
14765 			if (ill != NULL) {
14766 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14767 			} else {
14768 				BUMP_MIB(&ipst->ips_ip_mib,
14769 				    ipIfStatsInDiscards);
14770 			}
14771 			return (B_TRUE);
14772 		}
14773 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14774 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14775 			/* Copy b_prev - used by ip_mroute_decap */
14776 			to_mp->b_prev = from_mp->b_prev;
14777 			from_mp->b_prev = NULL;
14778 		}
14779 		*first_mpp = first_mp = mp1;
14780 		freemsg(mp);
14781 		mp = mp1;
14782 		*mpp = mp1;
14783 	}
14784 
14785 	ipha = (ipha_t *)mp->b_rptr;
14786 
14787 	/*
14788 	 * previous code has a case for M_DATA.
14789 	 * We want to check how that happens.
14790 	 */
14791 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14792 	switch (first_mp->b_datap->db_type) {
14793 	case M_PROTO:
14794 	case M_PCPROTO:
14795 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14796 		    DL_UNITDATA_IND) {
14797 			/* Go handle anything other than data elsewhere. */
14798 			ip_rput_dlpi(q, mp);
14799 			return (B_TRUE);
14800 		}
14801 		*ll_multicast = ((dl_unitdata_ind_t *)rptr)->dl_group_address;
14802 		/* Ditch the DLPI header. */
14803 		mp1 = mp->b_cont;
14804 		ASSERT(first_mp == mp);
14805 		*first_mpp = mp1;
14806 		freeb(mp);
14807 		*mpp = mp1;
14808 		return (B_FALSE);
14809 	case M_IOCACK:
14810 		ip1dbg(("got iocack "));
14811 		iocp = (struct iocblk *)mp->b_rptr;
14812 		switch (iocp->ioc_cmd) {
14813 		case DL_IOC_HDR_INFO:
14814 			ill = (ill_t *)q->q_ptr;
14815 			ill_fastpath_ack(ill, mp);
14816 			return (B_TRUE);
14817 		case SIOCSTUNPARAM:
14818 		case OSIOCSTUNPARAM:
14819 			/* Go through qwriter_ip */
14820 			break;
14821 		case SIOCGTUNPARAM:
14822 		case OSIOCGTUNPARAM:
14823 			ip_rput_other(NULL, q, mp, NULL);
14824 			return (B_TRUE);
14825 		default:
14826 			putnext(q, mp);
14827 			return (B_TRUE);
14828 		}
14829 		/* FALLTHRU */
14830 	case M_ERROR:
14831 	case M_HANGUP:
14832 		/*
14833 		 * Since this is on the ill stream we unconditionally
14834 		 * bump up the refcount
14835 		 */
14836 		ill_refhold(ill);
14837 		qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14838 		return (B_TRUE);
14839 	case M_CTL:
14840 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14841 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14842 		    IPHADA_M_CTL)) {
14843 			/*
14844 			 * It's an IPsec accelerated packet.
14845 			 * Make sure that the ill from which we received the
14846 			 * packet has enabled IPsec hardware acceleration.
14847 			 */
14848 			if (!(ill->ill_capabilities &
14849 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14850 				/* IPsec kstats: bean counter */
14851 				freemsg(mp);
14852 				return (B_TRUE);
14853 			}
14854 
14855 			/*
14856 			 * Make mp point to the mblk following the M_CTL,
14857 			 * then process according to type of mp.
14858 			 * After this processing, first_mp will point to
14859 			 * the data-attributes and mp to the pkt following
14860 			 * the M_CTL.
14861 			 */
14862 			mp = first_mp->b_cont;
14863 			if (mp == NULL) {
14864 				freemsg(first_mp);
14865 				return (B_TRUE);
14866 			}
14867 			/*
14868 			 * A Hardware Accelerated packet can only be M_DATA
14869 			 * ESP or AH packet.
14870 			 */
14871 			if (mp->b_datap->db_type != M_DATA) {
14872 				/* non-M_DATA IPsec accelerated packet */
14873 				IPSECHW_DEBUG(IPSECHW_PKT,
14874 				    ("non-M_DATA IPsec accelerated pkt\n"));
14875 				freemsg(first_mp);
14876 				return (B_TRUE);
14877 			}
14878 			ipha = (ipha_t *)mp->b_rptr;
14879 			if (ipha->ipha_protocol != IPPROTO_AH &&
14880 			    ipha->ipha_protocol != IPPROTO_ESP) {
14881 				IPSECHW_DEBUG(IPSECHW_PKT,
14882 				    ("non-M_DATA IPsec accelerated pkt\n"));
14883 				freemsg(first_mp);
14884 				return (B_TRUE);
14885 			}
14886 			*mpp = mp;
14887 			return (B_FALSE);
14888 		}
14889 		putnext(q, mp);
14890 		return (B_TRUE);
14891 	case M_IOCNAK:
14892 		ip1dbg(("got iocnak "));
14893 		iocp = (struct iocblk *)mp->b_rptr;
14894 		switch (iocp->ioc_cmd) {
14895 		case SIOCSTUNPARAM:
14896 		case OSIOCSTUNPARAM:
14897 			/*
14898 			 * Since this is on the ill stream we unconditionally
14899 			 * bump up the refcount
14900 			 */
14901 			ill_refhold(ill);
14902 			qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14903 			return (B_TRUE);
14904 		case DL_IOC_HDR_INFO:
14905 		case SIOCGTUNPARAM:
14906 		case OSIOCGTUNPARAM:
14907 			ip_rput_other(NULL, q, mp, NULL);
14908 			return (B_TRUE);
14909 		default:
14910 			break;
14911 		}
14912 		/* FALLTHRU */
14913 	default:
14914 		putnext(q, mp);
14915 		return (B_TRUE);
14916 	}
14917 }
14918 
14919 /* Read side put procedure.  Packets coming from the wire arrive here. */
14920 void
14921 ip_rput(queue_t *q, mblk_t *mp)
14922 {
14923 	ill_t		*ill = (ill_t *)q->q_ptr;
14924 	ip_stack_t	*ipst = ill->ill_ipst;
14925 	union DL_primitives *dl;
14926 
14927 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14928 
14929 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14930 		/*
14931 		 * If things are opening or closing, only accept high-priority
14932 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
14933 		 * created; on close, things hanging off the ill may have been
14934 		 * freed already.)
14935 		 */
14936 		dl = (union DL_primitives *)mp->b_rptr;
14937 		if (DB_TYPE(mp) != M_PCPROTO ||
14938 		    dl->dl_primitive == DL_UNITDATA_IND) {
14939 			/*
14940 			 * SIOC[GS]TUNPARAM ioctls can come here.
14941 			 */
14942 			inet_freemsg(mp);
14943 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14944 			    "ip_rput_end: q %p (%S)", q, "uninit");
14945 			return;
14946 		}
14947 	}
14948 
14949 	/*
14950 	 * if db_ref > 1 then copymsg and free original. Packet may be
14951 	 * changed and we do not want the other entity who has a reference to
14952 	 * this message to trip over the changes. This is a blind change because
14953 	 * trying to catch all places that might change the packet is too
14954 	 * difficult.
14955 	 *
14956 	 * This corresponds to the fast path case, where we have a chain of
14957 	 * M_DATA mblks.  We check the db_ref count of only the 1st data block
14958 	 * in the mblk chain. There doesn't seem to be a reason why a device
14959 	 * driver would send up data with varying db_ref counts in the mblk
14960 	 * chain. In any case the Fast path is a private interface, and our
14961 	 * drivers don't do such a thing. Given the above assumption, there is
14962 	 * no need to walk down the entire mblk chain (which could have a
14963 	 * potential performance problem)
14964 	 */
14965 	if (mp->b_datap->db_ref > 1) {
14966 		mblk_t  *mp1;
14967 		boolean_t adjusted = B_FALSE;
14968 		IP_STAT(ipst, ip_db_ref);
14969 
14970 		/*
14971 		 * The IP_RECVSLLA option depends on having the link layer
14972 		 * header. First check that:
14973 		 * a> the underlying device is of type ether, since this
14974 		 * option is currently supported only over ethernet.
14975 		 * b> there is enough room to copy over the link layer header.
14976 		 *
14977 		 * Once the checks are done, adjust rptr so that the link layer
14978 		 * header will be copied via copymsg. Note that, IFT_ETHER may
14979 		 * be returned by some non-ethernet drivers but in this case the
14980 		 * second check will fail.
14981 		 */
14982 		if (ill->ill_type == IFT_ETHER &&
14983 		    (mp->b_rptr - mp->b_datap->db_base) >=
14984 		    sizeof (struct ether_header)) {
14985 			mp->b_rptr -= sizeof (struct ether_header);
14986 			adjusted = B_TRUE;
14987 		}
14988 		mp1 = copymsg(mp);
14989 		if (mp1 == NULL) {
14990 			mp->b_next = NULL;
14991 			/* clear b_prev - used by ip_mroute_decap */
14992 			mp->b_prev = NULL;
14993 			freemsg(mp);
14994 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14995 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14996 			    "ip_rput_end: q %p (%S)", q, "copymsg");
14997 			return;
14998 		}
14999 		if (adjusted) {
15000 			/*
15001 			 * Copy is done. Restore the pointer in the _new_ mblk
15002 			 */
15003 			mp1->b_rptr += sizeof (struct ether_header);
15004 		}
15005 		/* Copy b_prev - used by ip_mroute_decap */
15006 		mp1->b_prev = mp->b_prev;
15007 		mp->b_prev = NULL;
15008 		freemsg(mp);
15009 		mp = mp1;
15010 	}
15011 
15012 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15013 	    "ip_rput_end: q %p (%S)", q, "end");
15014 
15015 	ip_input(ill, NULL, mp, NULL);
15016 }
15017 
15018 /*
15019  * Direct read side procedure capable of dealing with chains. GLDv3 based
15020  * drivers call this function directly with mblk chains while STREAMS
15021  * read side procedure ip_rput() calls this for single packet with ip_ring
15022  * set to NULL to process one packet at a time.
15023  *
15024  * The ill will always be valid if this function is called directly from
15025  * the driver.
15026  *
15027  * If ip_input() is called from GLDv3:
15028  *
15029  *   - This must be a non-VLAN IP stream.
15030  *   - 'mp' is either an untagged or a special priority-tagged packet.
15031  *   - Any VLAN tag that was in the MAC header has been stripped.
15032  *
15033  * If the IP header in packet is not 32-bit aligned, every message in the
15034  * chain will be aligned before further operations. This is required on SPARC
15035  * platform.
15036  */
15037 /* ARGSUSED */
15038 void
15039 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
15040     struct mac_header_info_s *mhip)
15041 {
15042 	ipaddr_t		dst = NULL;
15043 	ipaddr_t		prev_dst;
15044 	ire_t			*ire = NULL;
15045 	ipha_t			*ipha;
15046 	uint_t			pkt_len;
15047 	ssize_t			len;
15048 	uint_t			opt_len;
15049 	int			ll_multicast;
15050 	int			cgtp_flt_pkt;
15051 	queue_t			*q = ill->ill_rq;
15052 	squeue_t		*curr_sqp = NULL;
15053 	mblk_t 			*head = NULL;
15054 	mblk_t			*tail = NULL;
15055 	mblk_t			*first_mp;
15056 	mblk_t 			*mp;
15057 	mblk_t			*dmp;
15058 	int			cnt = 0;
15059 	ip_stack_t		*ipst = ill->ill_ipst;
15060 
15061 	ASSERT(mp_chain != NULL);
15062 	ASSERT(ill != NULL);
15063 
15064 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
15065 
15066 #define	rptr	((uchar_t *)ipha)
15067 
15068 	while (mp_chain != NULL) {
15069 		first_mp = mp = mp_chain;
15070 		mp_chain = mp_chain->b_next;
15071 		mp->b_next = NULL;
15072 		ll_multicast = 0;
15073 
15074 		/*
15075 		 * We do ire caching from one iteration to
15076 		 * another. In the event the packet chain contains
15077 		 * all packets from the same dst, this caching saves
15078 		 * an ire_cache_lookup for each of the succeeding
15079 		 * packets in a packet chain.
15080 		 */
15081 		prev_dst = dst;
15082 
15083 		/*
15084 		 * Check and align the IP header.
15085 		 */
15086 		if (DB_TYPE(mp) == M_DATA) {
15087 			dmp = mp;
15088 		} else if (DB_TYPE(mp) == M_PROTO &&
15089 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
15090 			dmp = mp->b_cont;
15091 		} else {
15092 			dmp = NULL;
15093 		}
15094 		if (dmp != NULL) {
15095 			/*
15096 			 * IP header ptr not aligned?
15097 			 * OR IP header not complete in first mblk
15098 			 */
15099 			if (!OK_32PTR(dmp->b_rptr) ||
15100 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
15101 				if (!ip_check_and_align_header(q, dmp, ipst))
15102 					continue;
15103 			}
15104 		}
15105 
15106 		/*
15107 		 * ip_input fast path
15108 		 */
15109 
15110 		/* mblk type is not M_DATA */
15111 		if (DB_TYPE(mp) != M_DATA) {
15112 			if (ip_rput_process_notdata(q, &first_mp, ill,
15113 			    &ll_multicast, &mp))
15114 				continue;
15115 		}
15116 
15117 		/* Make sure its an M_DATA and that its aligned */
15118 		ASSERT(DB_TYPE(mp) == M_DATA);
15119 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
15120 
15121 		ipha = (ipha_t *)mp->b_rptr;
15122 		len = mp->b_wptr - rptr;
15123 		pkt_len = ntohs(ipha->ipha_length);
15124 
15125 		/*
15126 		 * We must count all incoming packets, even if they end
15127 		 * up being dropped later on.
15128 		 */
15129 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15130 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15131 
15132 		/* multiple mblk or too short */
15133 		len -= pkt_len;
15134 		if (len != 0) {
15135 			/*
15136 			 * Make sure we have data length consistent
15137 			 * with the IP header.
15138 			 */
15139 			if (mp->b_cont == NULL) {
15140 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15141 					BUMP_MIB(ill->ill_ip_mib,
15142 					    ipIfStatsInHdrErrors);
15143 					ip2dbg(("ip_input: drop pkt\n"));
15144 					freemsg(mp);
15145 					continue;
15146 				}
15147 				mp->b_wptr = rptr + pkt_len;
15148 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
15149 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15150 					BUMP_MIB(ill->ill_ip_mib,
15151 					    ipIfStatsInHdrErrors);
15152 					ip2dbg(("ip_input: drop pkt\n"));
15153 					freemsg(mp);
15154 					continue;
15155 				}
15156 				(void) adjmsg(mp, -len);
15157 				IP_STAT(ipst, ip_multimblk3);
15158 			}
15159 		}
15160 
15161 		/* Obtain the dst of the current packet */
15162 		dst = ipha->ipha_dst;
15163 
15164 		if (IP_LOOPBACK_ADDR(dst) ||
15165 		    IP_LOOPBACK_ADDR(ipha->ipha_src)) {
15166 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
15167 			cmn_err(CE_CONT, "dst %X src %X\n",
15168 			    dst, ipha->ipha_src);
15169 			freemsg(mp);
15170 			continue;
15171 		}
15172 
15173 		/*
15174 		 * The event for packets being received from a 'physical'
15175 		 * interface is placed after validation of the source and/or
15176 		 * destination address as being local so that packets can be
15177 		 * redirected to loopback addresses using ipnat.
15178 		 */
15179 		DTRACE_PROBE4(ip4__physical__in__start,
15180 		    ill_t *, ill, ill_t *, NULL,
15181 		    ipha_t *, ipha, mblk_t *, first_mp);
15182 
15183 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15184 		    ipst->ips_ipv4firewall_physical_in,
15185 		    ill, NULL, ipha, first_mp, mp, ipst);
15186 
15187 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
15188 
15189 		if (first_mp == NULL) {
15190 			continue;
15191 		}
15192 		dst = ipha->ipha_dst;
15193 
15194 		/*
15195 		 * Attach any necessary label information to
15196 		 * this packet
15197 		 */
15198 		if (is_system_labeled() &&
15199 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
15200 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
15201 			freemsg(mp);
15202 			continue;
15203 		}
15204 
15205 		/*
15206 		 * Reuse the cached ire only if the ipha_dst of the previous
15207 		 * packet is the same as the current packet AND it is not
15208 		 * INADDR_ANY.
15209 		 */
15210 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15211 		    (ire != NULL)) {
15212 			ire_refrele(ire);
15213 			ire = NULL;
15214 		}
15215 		opt_len = ipha->ipha_version_and_hdr_length -
15216 		    IP_SIMPLE_HDR_VERSION;
15217 
15218 		/*
15219 		 * Check to see if we can take the fastpath.
15220 		 * That is possible if the following conditions are met
15221 		 *	o Tsol disabled
15222 		 *	o CGTP disabled
15223 		 *	o ipp_action_count is 0
15224 		 *	o Mobile IP not running
15225 		 *	o no options in the packet
15226 		 *	o not a RSVP packet
15227 		 * 	o not a multicast packet
15228 		 */
15229 		if (!is_system_labeled() &&
15230 		    !ip_cgtp_filter && ipp_action_count == 0 &&
15231 		    ill->ill_mrtun_refcnt == 0 && ill->ill_srcif_refcnt == 0 &&
15232 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
15233 		    !ll_multicast && !CLASSD(dst)) {
15234 			if (ire == NULL)
15235 				ire = ire_cache_lookup(dst, ALL_ZONES, NULL,
15236 				    ipst);
15237 
15238 			/* incoming packet is for forwarding */
15239 			if (ire == NULL || (ire->ire_type & IRE_CACHE)) {
15240 				ire = ip_fast_forward(ire, dst, ill, mp);
15241 				continue;
15242 			}
15243 			/* incoming packet is for local consumption */
15244 			if (ire->ire_type & IRE_LOCAL)
15245 				goto local;
15246 		}
15247 
15248 		/*
15249 		 * Disable ire caching for anything more complex
15250 		 * than the simple fast path case we checked for above.
15251 		 */
15252 		if (ire != NULL) {
15253 			ire_refrele(ire);
15254 			ire = NULL;
15255 		}
15256 
15257 		/* Full-blown slow path */
15258 		if (opt_len != 0) {
15259 			if (len != 0)
15260 				IP_STAT(ipst, ip_multimblk4);
15261 			else
15262 				IP_STAT(ipst, ip_ipoptions);
15263 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15264 			    &dst, ipst))
15265 				continue;
15266 		}
15267 
15268 		/*
15269 		 * Invoke the CGTP (multirouting) filtering module to process
15270 		 * the incoming packet. Packets identified as duplicates
15271 		 * must be discarded. Filtering is active only if the
15272 		 * the ip_cgtp_filter ndd variable is non-zero.
15273 		 *
15274 		 * Only applies to the shared stack since the filter_ops
15275 		 * do not carry an ip_stack_t or zoneid.
15276 		 */
15277 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15278 		if (ip_cgtp_filter && (ip_cgtp_filter_ops != NULL) &&
15279 		    ipst->ips_netstack->netstack_stackid == GLOBAL_NETSTACKID) {
15280 			cgtp_flt_pkt =
15281 			    ip_cgtp_filter_ops->cfo_filter(q, mp);
15282 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15283 				freemsg(first_mp);
15284 				continue;
15285 			}
15286 		}
15287 
15288 		/*
15289 		 * If rsvpd is running, let RSVP daemon handle its processing
15290 		 * and forwarding of RSVP multicast/unicast packets.
15291 		 * If rsvpd is not running but mrouted is running, RSVP
15292 		 * multicast packets are forwarded as multicast traffic
15293 		 * and RSVP unicast packets are forwarded by unicast router.
15294 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15295 		 * packets are not forwarded, but the unicast packets are
15296 		 * forwarded like unicast traffic.
15297 		 */
15298 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15299 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15300 		    NULL) {
15301 			/* RSVP packet and rsvpd running. Treat as ours */
15302 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15303 			/*
15304 			 * This assumes that we deliver to all streams for
15305 			 * multicast and broadcast packets.
15306 			 * We have to force ll_multicast to 1 to handle the
15307 			 * M_DATA messages passed in from ip_mroute_decap.
15308 			 */
15309 			dst = INADDR_BROADCAST;
15310 			ll_multicast = 1;
15311 		} else if (CLASSD(dst)) {
15312 			/* packet is multicast */
15313 			mp->b_next = NULL;
15314 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15315 			    &ll_multicast, &dst))
15316 				continue;
15317 		}
15318 
15319 
15320 		/*
15321 		 * Check if the packet is coming from the Mobile IP
15322 		 * forward tunnel interface
15323 		 */
15324 		if (ill->ill_srcif_refcnt > 0) {
15325 			ire = ire_srcif_table_lookup(dst, IRE_INTERFACE,
15326 			    NULL, ill, MATCH_IRE_TYPE);
15327 			if (ire != NULL && ire->ire_nce->nce_res_mp == NULL &&
15328 			    ire->ire_ipif->ipif_net_type == IRE_IF_RESOLVER) {
15329 
15330 				/* We need to resolve the link layer info */
15331 				ire_refrele(ire);
15332 				ire = NULL;
15333 				(void) ip_rput_noire(q, (ill_t *)q->q_ptr, mp,
15334 				    ll_multicast, dst);
15335 				continue;
15336 			}
15337 		}
15338 
15339 		if (ire == NULL) {
15340 			ire = ire_cache_lookup(dst, ALL_ZONES,
15341 			    MBLK_GETLABEL(mp), ipst);
15342 		}
15343 
15344 		/*
15345 		 * If mipagent is running and reverse tunnel is created as per
15346 		 * mobile node request, then any packet coming through the
15347 		 * incoming interface from the mobile-node, should be reverse
15348 		 * tunneled to it's home agent except those that are destined
15349 		 * to foreign agent only.
15350 		 * This needs source address based ire lookup. The routing
15351 		 * entries for source address based lookup are only created by
15352 		 * mipagent program only when a reverse tunnel is created.
15353 		 * Reference : RFC2002, RFC2344
15354 		 */
15355 		if (ill->ill_mrtun_refcnt > 0) {
15356 			ipaddr_t	srcaddr;
15357 			ire_t		*tmp_ire;
15358 
15359 			tmp_ire = ire;	/* Save, we might need it later */
15360 			if (ire == NULL || (ire->ire_type != IRE_LOCAL &&
15361 			    ire->ire_type != IRE_BROADCAST)) {
15362 				srcaddr = ipha->ipha_src;
15363 				ire = ire_mrtun_lookup(srcaddr, ill);
15364 				if (ire != NULL) {
15365 					/*
15366 					 * Should not be getting iphada packet
15367 					 * here. we should only get those for
15368 					 * IRE_LOCAL traffic, excluded above.
15369 					 * Fail-safe (drop packet) in the event
15370 					 * hardware is misbehaving.
15371 					 */
15372 					if (first_mp != mp) {
15373 						/* IPsec KSTATS: beancount me */
15374 						freemsg(first_mp);
15375 					} else {
15376 						/*
15377 						 * This packet must be forwarded
15378 						 * to Reverse Tunnel
15379 						 */
15380 						ip_mrtun_forward(ire, ill, mp);
15381 					}
15382 					ire_refrele(ire);
15383 					ire = NULL;
15384 					if (tmp_ire != NULL) {
15385 						ire_refrele(tmp_ire);
15386 						tmp_ire = NULL;
15387 					}
15388 					TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15389 					    "ip_input_end: q %p (%S)",
15390 					    q, "uninit");
15391 					continue;
15392 				}
15393 			}
15394 			/*
15395 			 * If this packet is from a non-mobilenode  or a
15396 			 * mobile-node which does not request reverse
15397 			 * tunnel service
15398 			 */
15399 			ire = tmp_ire;
15400 		}
15401 
15402 
15403 		/*
15404 		 * If we reach here that means the incoming packet satisfies
15405 		 * one of the following conditions:
15406 		 *   - packet is from a mobile node which does not request
15407 		 *	reverse tunnel
15408 		 *   - packet is from a non-mobile node, which is the most
15409 		 *	common case
15410 		 *   - packet is from a reverse tunnel enabled mobile node
15411 		 *	and destined to foreign agent only
15412 		 */
15413 
15414 		if (ire == NULL) {
15415 			/*
15416 			 * No IRE for this destination, so it can't be for us.
15417 			 * Unless we are forwarding, drop the packet.
15418 			 * We have to let source routed packets through
15419 			 * since we don't yet know if they are 'ping -l'
15420 			 * packets i.e. if they will go out over the
15421 			 * same interface as they came in on.
15422 			 */
15423 			ire = ip_rput_noire(q, NULL, mp, ll_multicast, dst);
15424 			if (ire == NULL)
15425 				continue;
15426 		}
15427 
15428 		/*
15429 		 * Broadcast IRE may indicate either broadcast or
15430 		 * multicast packet
15431 		 */
15432 		if (ire->ire_type == IRE_BROADCAST) {
15433 			/*
15434 			 * Skip broadcast checks if packet is UDP multicast;
15435 			 * we'd rather not enter ip_rput_process_broadcast()
15436 			 * unless the packet is broadcast for real, since
15437 			 * that routine is a no-op for multicast.
15438 			 */
15439 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15440 			    !CLASSD(ipha->ipha_dst)) {
15441 				ire = ip_rput_process_broadcast(&q, mp,
15442 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15443 				    ll_multicast);
15444 				if (ire == NULL)
15445 					continue;
15446 			}
15447 		} else if (ire->ire_stq != NULL) {
15448 			/* fowarding? */
15449 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15450 			    ll_multicast);
15451 			/* ip_rput_process_forward consumed the packet */
15452 			continue;
15453 		}
15454 
15455 local:
15456 		/*
15457 		 * If the queue in the ire is different to the ingress queue
15458 		 * then we need to check to see if we can accept the packet.
15459 		 * Note that for multicast packets and broadcast packets sent
15460 		 * to a broadcast address which is shared between multiple
15461 		 * interfaces we should not do this since we just got a random
15462 		 * broadcast ire.
15463 		 */
15464 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15465 			if ((ire = ip_check_multihome(&ipha->ipha_dst, ire,
15466 			    ill)) == NULL) {
15467 				/* Drop packet */
15468 				BUMP_MIB(ill->ill_ip_mib,
15469 				    ipIfStatsForwProhibits);
15470 				freemsg(mp);
15471 				continue;
15472 			}
15473 			if (ire->ire_rfq != NULL)
15474 				q = ire->ire_rfq;
15475 		}
15476 
15477 		switch (ipha->ipha_protocol) {
15478 		case IPPROTO_TCP:
15479 			ASSERT(first_mp == mp);
15480 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15481 			    mp, 0, q, ip_ring)) != NULL) {
15482 				if (curr_sqp == NULL) {
15483 					curr_sqp = GET_SQUEUE(mp);
15484 					ASSERT(cnt == 0);
15485 					cnt++;
15486 					head = tail = mp;
15487 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15488 					ASSERT(tail != NULL);
15489 					cnt++;
15490 					tail->b_next = mp;
15491 					tail = mp;
15492 				} else {
15493 					/*
15494 					 * A different squeue. Send the
15495 					 * chain for the previous squeue on
15496 					 * its way. This shouldn't happen
15497 					 * often unless interrupt binding
15498 					 * changes.
15499 					 */
15500 					IP_STAT(ipst, ip_input_multi_squeue);
15501 					squeue_enter_chain(curr_sqp, head,
15502 					    tail, cnt, SQTAG_IP_INPUT);
15503 					curr_sqp = GET_SQUEUE(mp);
15504 					head = mp;
15505 					tail = mp;
15506 					cnt = 1;
15507 				}
15508 			}
15509 			continue;
15510 		case IPPROTO_UDP:
15511 			ASSERT(first_mp == mp);
15512 			ip_udp_input(q, mp, ipha, ire, ill);
15513 			continue;
15514 		case IPPROTO_SCTP:
15515 			ASSERT(first_mp == mp);
15516 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15517 			    q, dst);
15518 			/* ire has been released by ip_sctp_input */
15519 			ire = NULL;
15520 			continue;
15521 		default:
15522 			ip_proto_input(q, first_mp, ipha, ire, ill);
15523 			continue;
15524 		}
15525 	}
15526 
15527 	if (ire != NULL)
15528 		ire_refrele(ire);
15529 
15530 	if (head != NULL)
15531 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
15532 
15533 	/*
15534 	 * This code is there just to make netperf/ttcp look good.
15535 	 *
15536 	 * Its possible that after being in polling mode (and having cleared
15537 	 * the backlog), squeues have turned the interrupt frequency higher
15538 	 * to improve latency at the expense of more CPU utilization (less
15539 	 * packets per interrupts or more number of interrupts). Workloads
15540 	 * like ttcp/netperf do manage to tickle polling once in a while
15541 	 * but for the remaining time, stay in higher interrupt mode since
15542 	 * their packet arrival rate is pretty uniform and this shows up
15543 	 * as higher CPU utilization. Since people care about CPU utilization
15544 	 * while running netperf/ttcp, turn the interrupt frequency back to
15545 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
15546 	 */
15547 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
15548 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
15549 			ip_ring->rr_poll_state &= ~ILL_POLLING;
15550 			ip_ring->rr_blank(ip_ring->rr_handle,
15551 			    ip_ring->rr_normal_blank_time,
15552 			    ip_ring->rr_normal_pkt_cnt);
15553 		}
15554 		}
15555 
15556 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15557 	    "ip_input_end: q %p (%S)", q, "end");
15558 #undef  rptr
15559 }
15560 
15561 static void
15562 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15563     t_uscalar_t err)
15564 {
15565 	if (dl_err == DL_SYSERR) {
15566 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15567 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15568 		    ill->ill_name, dlpi_prim_str(prim), err);
15569 		return;
15570 	}
15571 
15572 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15573 	    "%s: %s failed: %s\n", ill->ill_name, dlpi_prim_str(prim),
15574 	    dlpi_err_str(dl_err));
15575 }
15576 
15577 /*
15578  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15579  * than DL_UNITDATA_IND messages. If we need to process this message
15580  * exclusively, we call qwriter_ip, in which case we also need to call
15581  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15582  */
15583 void
15584 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15585 {
15586 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15587 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15588 	ill_t		*ill = (ill_t *)q->q_ptr;
15589 	boolean_t	pending;
15590 
15591 	ip1dbg(("ip_rput_dlpi"));
15592 	if (dloa->dl_primitive == DL_ERROR_ACK) {
15593 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
15594 		    "%s (0x%x), unix %u\n", ill->ill_name,
15595 		    dlpi_prim_str(dlea->dl_error_primitive),
15596 		    dlea->dl_error_primitive,
15597 		    dlpi_err_str(dlea->dl_errno),
15598 		    dlea->dl_errno,
15599 		    dlea->dl_unix_errno));
15600 	}
15601 
15602 	/*
15603 	 * If we received an ACK but didn't send a request for it, then it
15604 	 * can't be part of any pending operation; discard up-front.
15605 	 */
15606 	switch (dloa->dl_primitive) {
15607 	case DL_NOTIFY_IND:
15608 		pending = B_TRUE;
15609 		break;
15610 	case DL_ERROR_ACK:
15611 		pending = ill_dlpi_pending(ill, dlea->dl_error_primitive);
15612 		break;
15613 	case DL_OK_ACK:
15614 		pending = ill_dlpi_pending(ill, dloa->dl_correct_primitive);
15615 		break;
15616 	case DL_INFO_ACK:
15617 		pending = ill_dlpi_pending(ill, DL_INFO_REQ);
15618 		break;
15619 	case DL_BIND_ACK:
15620 		pending = ill_dlpi_pending(ill, DL_BIND_REQ);
15621 		break;
15622 	case DL_PHYS_ADDR_ACK:
15623 		pending = ill_dlpi_pending(ill, DL_PHYS_ADDR_REQ);
15624 		break;
15625 	case DL_NOTIFY_ACK:
15626 		pending = ill_dlpi_pending(ill, DL_NOTIFY_REQ);
15627 		break;
15628 	case DL_CONTROL_ACK:
15629 		pending = ill_dlpi_pending(ill, DL_CONTROL_REQ);
15630 		break;
15631 	case DL_CAPABILITY_ACK:
15632 		pending = ill_dlpi_pending(ill, DL_CAPABILITY_REQ);
15633 		break;
15634 	default:
15635 		/* Not a DLPI message we support or were expecting */
15636 		freemsg(mp);
15637 		return;
15638 	}
15639 
15640 	if (!pending) {
15641 		freemsg(mp);
15642 		return;
15643 	}
15644 
15645 	switch (dloa->dl_primitive) {
15646 	case DL_ERROR_ACK:
15647 		if (dlea->dl_error_primitive == DL_UNBIND_REQ) {
15648 			mutex_enter(&ill->ill_lock);
15649 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15650 			cv_signal(&ill->ill_cv);
15651 			mutex_exit(&ill->ill_lock);
15652 		}
15653 		break;
15654 
15655 	case DL_OK_ACK:
15656 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
15657 		    dlpi_prim_str((int)dloa->dl_correct_primitive)));
15658 		switch (dloa->dl_correct_primitive) {
15659 		case DL_UNBIND_REQ:
15660 			mutex_enter(&ill->ill_lock);
15661 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15662 			cv_signal(&ill->ill_cv);
15663 			mutex_exit(&ill->ill_lock);
15664 			break;
15665 
15666 		case DL_ENABMULTI_REQ:
15667 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15668 				ill->ill_dlpi_multicast_state = IDS_OK;
15669 			break;
15670 		}
15671 		break;
15672 	default:
15673 		break;
15674 	}
15675 
15676 	/*
15677 	 * We know the message is one we're waiting for (or DL_NOTIFY_IND),
15678 	 * and we need to become writer to continue to process it. If it's not
15679 	 * a DL_NOTIFY_IND, we assume we're in the middle of an exclusive
15680 	 * operation and pass CUR_OP.  If this isn't true, we'll end up doing
15681 	 * some work as part of the current exclusive operation that actually
15682 	 * is not part of it -- which is wrong, but better than the
15683 	 * alternative of deadlock (if NEW_OP is always used).  Someday, we
15684 	 * should track which DLPI requests have ACKs that we wait on
15685 	 * synchronously so we can know whether to use CUR_OP or NEW_OP.
15686 	 *
15687 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
15688 	 * Since this is on the ill stream we unconditionally bump up the
15689 	 * refcount without doing ILL_CAN_LOOKUP().
15690 	 */
15691 	ill_refhold(ill);
15692 	if (dloa->dl_primitive == DL_NOTIFY_IND)
15693 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
15694 	else
15695 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
15696 }
15697 
15698 /*
15699  * Handling of DLPI messages that require exclusive access to the ipsq.
15700  *
15701  * Need to do ill_pending_mp_release on ioctl completion, which could
15702  * happen here. (along with mi_copy_done)
15703  */
15704 /* ARGSUSED */
15705 static void
15706 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15707 {
15708 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15709 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15710 	int		err = 0;
15711 	ill_t		*ill;
15712 	ipif_t		*ipif = NULL;
15713 	mblk_t		*mp1 = NULL;
15714 	conn_t		*connp = NULL;
15715 	t_uscalar_t	paddrreq;
15716 	mblk_t		*mp_hw;
15717 	boolean_t	success;
15718 	boolean_t	ioctl_aborted = B_FALSE;
15719 	boolean_t	log = B_TRUE;
15720 	hook_nic_event_t	*info;
15721 	ip_stack_t		*ipst;
15722 
15723 	ip1dbg(("ip_rput_dlpi_writer .."));
15724 	ill = (ill_t *)q->q_ptr;
15725 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15726 
15727 	ASSERT(IAM_WRITER_ILL(ill));
15728 
15729 	ipst = ill->ill_ipst;
15730 
15731 	/*
15732 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
15733 	 * both are null or non-null. However we can assert that only
15734 	 * after grabbing the ipsq_lock. So we don't make any assertion
15735 	 * here and in other places in the code.
15736 	 */
15737 	ipif = ipsq->ipsq_pending_ipif;
15738 	/*
15739 	 * The current ioctl could have been aborted by the user and a new
15740 	 * ioctl to bring up another ill could have started. We could still
15741 	 * get a response from the driver later.
15742 	 */
15743 	if (ipif != NULL && ipif->ipif_ill != ill)
15744 		ioctl_aborted = B_TRUE;
15745 
15746 	switch (dloa->dl_primitive) {
15747 	case DL_ERROR_ACK:
15748 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
15749 		    dlpi_prim_str(dlea->dl_error_primitive)));
15750 
15751 		switch (dlea->dl_error_primitive) {
15752 		case DL_PROMISCON_REQ:
15753 		case DL_PROMISCOFF_REQ:
15754 		case DL_DISABMULTI_REQ:
15755 		case DL_UNBIND_REQ:
15756 		case DL_ATTACH_REQ:
15757 		case DL_INFO_REQ:
15758 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15759 			break;
15760 		case DL_NOTIFY_REQ:
15761 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15762 			log = B_FALSE;
15763 			break;
15764 		case DL_PHYS_ADDR_REQ:
15765 			/*
15766 			 * For IPv6 only, there are two additional
15767 			 * phys_addr_req's sent to the driver to get the
15768 			 * IPv6 token and lla. This allows IP to acquire
15769 			 * the hardware address format for a given interface
15770 			 * without having built in knowledge of the hardware
15771 			 * address. ill_phys_addr_pend keeps track of the last
15772 			 * DL_PAR sent so we know which response we are
15773 			 * dealing with. ill_dlpi_done will update
15774 			 * ill_phys_addr_pend when it sends the next req.
15775 			 * We don't complete the IOCTL until all three DL_PARs
15776 			 * have been attempted, so set *_len to 0 and break.
15777 			 */
15778 			paddrreq = ill->ill_phys_addr_pend;
15779 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15780 			if (paddrreq == DL_IPV6_TOKEN) {
15781 				ill->ill_token_length = 0;
15782 				log = B_FALSE;
15783 				break;
15784 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15785 				ill->ill_nd_lla_len = 0;
15786 				log = B_FALSE;
15787 				break;
15788 			}
15789 			/*
15790 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15791 			 * We presumably have an IOCTL hanging out waiting
15792 			 * for completion. Find it and complete the IOCTL
15793 			 * with the error noted.
15794 			 * However, ill_dl_phys was called on an ill queue
15795 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15796 			 * set. But the ioctl is known to be pending on ill_wq.
15797 			 */
15798 			if (!ill->ill_ifname_pending)
15799 				break;
15800 			ill->ill_ifname_pending = 0;
15801 			if (!ioctl_aborted)
15802 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15803 			if (mp1 != NULL) {
15804 				/*
15805 				 * This operation (SIOCSLIFNAME) must have
15806 				 * happened on the ill. Assert there is no conn
15807 				 */
15808 				ASSERT(connp == NULL);
15809 				q = ill->ill_wq;
15810 			}
15811 			break;
15812 		case DL_BIND_REQ:
15813 			ill_dlpi_done(ill, DL_BIND_REQ);
15814 			if (ill->ill_ifname_pending)
15815 				break;
15816 			/*
15817 			 * Something went wrong with the bind.  We presumably
15818 			 * have an IOCTL hanging out waiting for completion.
15819 			 * Find it, take down the interface that was coming
15820 			 * up, and complete the IOCTL with the error noted.
15821 			 */
15822 			if (!ioctl_aborted)
15823 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15824 			if (mp1 != NULL) {
15825 				/*
15826 				 * This operation (SIOCSLIFFLAGS) must have
15827 				 * happened from a conn.
15828 				 */
15829 				ASSERT(connp != NULL);
15830 				q = CONNP_TO_WQ(connp);
15831 				if (ill->ill_move_in_progress) {
15832 					ILL_CLEAR_MOVE(ill);
15833 				}
15834 				(void) ipif_down(ipif, NULL, NULL);
15835 				/* error is set below the switch */
15836 			}
15837 			break;
15838 		case DL_ENABMULTI_REQ:
15839 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
15840 
15841 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15842 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15843 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15844 				ipif_t *ipif;
15845 
15846 				printf("ip: joining multicasts failed (%d)"
15847 				    " on %s - will use link layer "
15848 				    "broadcasts for multicast\n",
15849 				    dlea->dl_errno, ill->ill_name);
15850 
15851 				/*
15852 				 * Set up the multicast mapping alone.
15853 				 * writer, so ok to access ill->ill_ipif
15854 				 * without any lock.
15855 				 */
15856 				ipif = ill->ill_ipif;
15857 				mutex_enter(&ill->ill_phyint->phyint_lock);
15858 				ill->ill_phyint->phyint_flags |=
15859 				    PHYI_MULTI_BCAST;
15860 				mutex_exit(&ill->ill_phyint->phyint_lock);
15861 
15862 				if (!ill->ill_isv6) {
15863 					(void) ipif_arp_setup_multicast(ipif,
15864 					    NULL);
15865 				} else {
15866 					(void) ipif_ndp_setup_multicast(ipif,
15867 					    NULL);
15868 				}
15869 			}
15870 			freemsg(mp);	/* Don't want to pass this up */
15871 			return;
15872 
15873 		case DL_CAPABILITY_REQ:
15874 		case DL_CONTROL_REQ:
15875 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15876 			ill->ill_dlpi_capab_state = IDS_FAILED;
15877 			freemsg(mp);
15878 			return;
15879 		}
15880 		/*
15881 		 * Note the error for IOCTL completion (mp1 is set when
15882 		 * ready to complete ioctl). If ill_ifname_pending_err is
15883 		 * set, an error occured during plumbing (ill_ifname_pending),
15884 		 * so we want to report that error.
15885 		 *
15886 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15887 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15888 		 * expected to get errack'd if the driver doesn't support
15889 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15890 		 * if these error conditions are encountered.
15891 		 */
15892 		if (mp1 != NULL) {
15893 			if (ill->ill_ifname_pending_err != 0)  {
15894 				err = ill->ill_ifname_pending_err;
15895 				ill->ill_ifname_pending_err = 0;
15896 			} else {
15897 				err = dlea->dl_unix_errno ?
15898 				    dlea->dl_unix_errno : ENXIO;
15899 			}
15900 		/*
15901 		 * If we're plumbing an interface and an error hasn't already
15902 		 * been saved, set ill_ifname_pending_err to the error passed
15903 		 * up. Ignore the error if log is B_FALSE (see comment above).
15904 		 */
15905 		} else if (log && ill->ill_ifname_pending &&
15906 		    ill->ill_ifname_pending_err == 0) {
15907 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15908 			    dlea->dl_unix_errno : ENXIO;
15909 		}
15910 
15911 		if (log)
15912 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15913 			    dlea->dl_errno, dlea->dl_unix_errno);
15914 		break;
15915 	case DL_CAPABILITY_ACK: {
15916 		boolean_t reneg_flag = B_FALSE;
15917 		/* Call a routine to handle this one. */
15918 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
15919 		/*
15920 		 * Check if the ACK is due to renegotiation case since we
15921 		 * will need to send a new CAPABILITY_REQ later.
15922 		 */
15923 		if (ill->ill_dlpi_capab_state == IDS_RENEG) {
15924 			/* This is the ack for a renogiation case */
15925 			reneg_flag = B_TRUE;
15926 			ill->ill_dlpi_capab_state = IDS_UNKNOWN;
15927 		}
15928 		ill_capability_ack(ill, mp);
15929 		if (reneg_flag)
15930 			ill_capability_probe(ill);
15931 		break;
15932 	}
15933 	case DL_CONTROL_ACK:
15934 		/* We treat all of these as "fire and forget" */
15935 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15936 		break;
15937 	case DL_INFO_ACK:
15938 		/* Call a routine to handle this one. */
15939 		ill_dlpi_done(ill, DL_INFO_REQ);
15940 		ip_ll_subnet_defaults(ill, mp);
15941 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15942 		return;
15943 	case DL_BIND_ACK:
15944 		/*
15945 		 * We should have an IOCTL waiting on this unless
15946 		 * sent by ill_dl_phys, in which case just return
15947 		 */
15948 		ill_dlpi_done(ill, DL_BIND_REQ);
15949 		if (ill->ill_ifname_pending)
15950 			break;
15951 
15952 		if (!ioctl_aborted)
15953 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15954 		if (mp1 == NULL)
15955 			break;
15956 		/*
15957 		 * Because mp1 was added by ill_dl_up(), and it always
15958 		 * passes a valid connp, connp must be valid here.
15959 		 */
15960 		ASSERT(connp != NULL);
15961 		q = CONNP_TO_WQ(connp);
15962 
15963 		/*
15964 		 * We are exclusive. So nothing can change even after
15965 		 * we get the pending mp. If need be we can put it back
15966 		 * and restart, as in calling ipif_arp_up()  below.
15967 		 */
15968 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15969 
15970 		mutex_enter(&ill->ill_lock);
15971 
15972 		ill->ill_dl_up = 1;
15973 
15974 		if ((info = ill->ill_nic_event_info) != NULL) {
15975 			ip2dbg(("ip_rput_dlpi_writer: unexpected nic event %d "
15976 			    "attached for %s\n", info->hne_event,
15977 			    ill->ill_name));
15978 			if (info->hne_data != NULL)
15979 				kmem_free(info->hne_data, info->hne_datalen);
15980 			kmem_free(info, sizeof (hook_nic_event_t));
15981 		}
15982 
15983 		info = kmem_alloc(sizeof (hook_nic_event_t), KM_NOSLEEP);
15984 		if (info != NULL) {
15985 			info->hne_nic = ill->ill_phyint->phyint_hook_ifindex;
15986 			info->hne_lif = 0;
15987 			info->hne_event = NE_UP;
15988 			info->hne_data = NULL;
15989 			info->hne_datalen = 0;
15990 			info->hne_family = ill->ill_isv6 ?
15991 			    ipst->ips_ipv6_net_data : ipst->ips_ipv4_net_data;
15992 		} else
15993 			ip2dbg(("ip_rput_dlpi_writer: could not attach UP nic "
15994 			    "event information for %s (ENOMEM)\n",
15995 			    ill->ill_name));
15996 
15997 		ill->ill_nic_event_info = info;
15998 
15999 		mutex_exit(&ill->ill_lock);
16000 
16001 		/*
16002 		 * Now bring up the resolver; when that is complete, we'll
16003 		 * create IREs.  Note that we intentionally mirror what
16004 		 * ipif_up() would have done, because we got here by way of
16005 		 * ill_dl_up(), which stopped ipif_up()'s processing.
16006 		 */
16007 		if (ill->ill_isv6) {
16008 			/*
16009 			 * v6 interfaces.
16010 			 * Unlike ARP which has to do another bind
16011 			 * and attach, once we get here we are
16012 			 * done with NDP. Except in the case of
16013 			 * ILLF_XRESOLV, in which case we send an
16014 			 * AR_INTERFACE_UP to the external resolver.
16015 			 * If all goes well, the ioctl will complete
16016 			 * in ip_rput(). If there's an error, we
16017 			 * complete it here.
16018 			 */
16019 			err = ipif_ndp_up(ipif, &ipif->ipif_v6lcl_addr);
16020 			if (err == 0) {
16021 				if (ill->ill_flags & ILLF_XRESOLV) {
16022 					mutex_enter(&connp->conn_lock);
16023 					mutex_enter(&ill->ill_lock);
16024 					success = ipsq_pending_mp_add(
16025 					    connp, ipif, q, mp1, 0);
16026 					mutex_exit(&ill->ill_lock);
16027 					mutex_exit(&connp->conn_lock);
16028 					if (success) {
16029 						err = ipif_resolver_up(ipif,
16030 						    Res_act_initial);
16031 						if (err == EINPROGRESS) {
16032 							freemsg(mp);
16033 							return;
16034 						}
16035 						ASSERT(err != 0);
16036 						mp1 = ipsq_pending_mp_get(ipsq,
16037 						    &connp);
16038 						ASSERT(mp1 != NULL);
16039 					} else {
16040 						/* conn has started closing */
16041 						err = EINTR;
16042 					}
16043 				} else { /* Non XRESOLV interface */
16044 					(void) ipif_resolver_up(ipif,
16045 					    Res_act_initial);
16046 					err = ipif_up_done_v6(ipif);
16047 				}
16048 			}
16049 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
16050 			/*
16051 			 * ARP and other v4 external resolvers.
16052 			 * Leave the pending mblk intact so that
16053 			 * the ioctl completes in ip_rput().
16054 			 */
16055 			mutex_enter(&connp->conn_lock);
16056 			mutex_enter(&ill->ill_lock);
16057 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
16058 			mutex_exit(&ill->ill_lock);
16059 			mutex_exit(&connp->conn_lock);
16060 			if (success) {
16061 				err = ipif_resolver_up(ipif, Res_act_initial);
16062 				if (err == EINPROGRESS) {
16063 					freemsg(mp);
16064 					return;
16065 				}
16066 				ASSERT(err != 0);
16067 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16068 			} else {
16069 				/* The conn has started closing */
16070 				err = EINTR;
16071 			}
16072 		} else {
16073 			/*
16074 			 * This one is complete. Reply to pending ioctl.
16075 			 */
16076 			(void) ipif_resolver_up(ipif, Res_act_initial);
16077 			err = ipif_up_done(ipif);
16078 		}
16079 
16080 		if ((err == 0) && (ill->ill_up_ipifs)) {
16081 			err = ill_up_ipifs(ill, q, mp1);
16082 			if (err == EINPROGRESS) {
16083 				freemsg(mp);
16084 				return;
16085 			}
16086 		}
16087 
16088 		if (ill->ill_up_ipifs) {
16089 			ill_group_cleanup(ill);
16090 		}
16091 
16092 		break;
16093 	case DL_NOTIFY_IND: {
16094 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
16095 		ire_t *ire;
16096 		boolean_t need_ire_walk_v4 = B_FALSE;
16097 		boolean_t need_ire_walk_v6 = B_FALSE;
16098 
16099 		switch (notify->dl_notification) {
16100 		case DL_NOTE_PHYS_ADDR:
16101 			err = ill_set_phys_addr(ill, mp);
16102 			break;
16103 
16104 		case DL_NOTE_FASTPATH_FLUSH:
16105 			ill_fastpath_flush(ill);
16106 			break;
16107 
16108 		case DL_NOTE_SDU_SIZE:
16109 			/*
16110 			 * Change the MTU size of the interface, of all
16111 			 * attached ipif's, and of all relevant ire's.  The
16112 			 * new value's a uint32_t at notify->dl_data.
16113 			 * Mtu change Vs. new ire creation - protocol below.
16114 			 *
16115 			 * a Mark the ipif as IPIF_CHANGING.
16116 			 * b Set the new mtu in the ipif.
16117 			 * c Change the ire_max_frag on all affected ires
16118 			 * d Unmark the IPIF_CHANGING
16119 			 *
16120 			 * To see how the protocol works, assume an interface
16121 			 * route is also being added simultaneously by
16122 			 * ip_rt_add and let 'ipif' be the ipif referenced by
16123 			 * the ire. If the ire is created before step a,
16124 			 * it will be cleaned up by step c. If the ire is
16125 			 * created after step d, it will see the new value of
16126 			 * ipif_mtu. Any attempt to create the ire between
16127 			 * steps a to d will fail because of the IPIF_CHANGING
16128 			 * flag. Note that ire_create() is passed a pointer to
16129 			 * the ipif_mtu, and not the value. During ire_add
16130 			 * under the bucket lock, the ire_max_frag of the
16131 			 * new ire being created is set from the ipif/ire from
16132 			 * which it is being derived.
16133 			 */
16134 			mutex_enter(&ill->ill_lock);
16135 			ill->ill_max_frag = (uint_t)notify->dl_data;
16136 
16137 			/*
16138 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
16139 			 * leave it alone
16140 			 */
16141 			if (ill->ill_mtu_userspecified) {
16142 				mutex_exit(&ill->ill_lock);
16143 				break;
16144 			}
16145 			ill->ill_max_mtu = ill->ill_max_frag;
16146 			if (ill->ill_isv6) {
16147 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
16148 					ill->ill_max_mtu = IPV6_MIN_MTU;
16149 			} else {
16150 				if (ill->ill_max_mtu < IP_MIN_MTU)
16151 					ill->ill_max_mtu = IP_MIN_MTU;
16152 			}
16153 			for (ipif = ill->ill_ipif; ipif != NULL;
16154 			    ipif = ipif->ipif_next) {
16155 				/*
16156 				 * Don't override the mtu if the user
16157 				 * has explicitly set it.
16158 				 */
16159 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
16160 					continue;
16161 				ipif->ipif_mtu = (uint_t)notify->dl_data;
16162 				if (ipif->ipif_isv6)
16163 					ire = ipif_to_ire_v6(ipif);
16164 				else
16165 					ire = ipif_to_ire(ipif);
16166 				if (ire != NULL) {
16167 					ire->ire_max_frag = ipif->ipif_mtu;
16168 					ire_refrele(ire);
16169 				}
16170 				if (ipif->ipif_flags & IPIF_UP) {
16171 					if (ill->ill_isv6)
16172 						need_ire_walk_v6 = B_TRUE;
16173 					else
16174 						need_ire_walk_v4 = B_TRUE;
16175 				}
16176 			}
16177 			mutex_exit(&ill->ill_lock);
16178 			if (need_ire_walk_v4)
16179 				ire_walk_v4(ill_mtu_change, (char *)ill,
16180 				    ALL_ZONES, ipst);
16181 			if (need_ire_walk_v6)
16182 				ire_walk_v6(ill_mtu_change, (char *)ill,
16183 				    ALL_ZONES, ipst);
16184 			break;
16185 		case DL_NOTE_LINK_UP:
16186 		case DL_NOTE_LINK_DOWN: {
16187 			/*
16188 			 * We are writer. ill / phyint / ipsq assocs stable.
16189 			 * The RUNNING flag reflects the state of the link.
16190 			 */
16191 			phyint_t *phyint = ill->ill_phyint;
16192 			uint64_t new_phyint_flags;
16193 			boolean_t changed = B_FALSE;
16194 			boolean_t went_up;
16195 
16196 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
16197 			mutex_enter(&phyint->phyint_lock);
16198 			new_phyint_flags = went_up ?
16199 			    phyint->phyint_flags | PHYI_RUNNING :
16200 			    phyint->phyint_flags & ~PHYI_RUNNING;
16201 			if (new_phyint_flags != phyint->phyint_flags) {
16202 				phyint->phyint_flags = new_phyint_flags;
16203 				changed = B_TRUE;
16204 			}
16205 			mutex_exit(&phyint->phyint_lock);
16206 			/*
16207 			 * ill_restart_dad handles the DAD restart and routing
16208 			 * socket notification logic.
16209 			 */
16210 			if (changed) {
16211 				ill_restart_dad(phyint->phyint_illv4, went_up);
16212 				ill_restart_dad(phyint->phyint_illv6, went_up);
16213 			}
16214 			break;
16215 		}
16216 		case DL_NOTE_PROMISC_ON_PHYS:
16217 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16218 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
16219 			mutex_enter(&ill->ill_lock);
16220 			ill->ill_promisc_on_phys = B_TRUE;
16221 			mutex_exit(&ill->ill_lock);
16222 			break;
16223 		case DL_NOTE_PROMISC_OFF_PHYS:
16224 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16225 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
16226 			mutex_enter(&ill->ill_lock);
16227 			ill->ill_promisc_on_phys = B_FALSE;
16228 			mutex_exit(&ill->ill_lock);
16229 			break;
16230 		case DL_NOTE_CAPAB_RENEG:
16231 			/*
16232 			 * Something changed on the driver side.
16233 			 * It wants us to renegotiate the capabilities
16234 			 * on this ill. The most likely cause is the
16235 			 * aggregation interface under us where a
16236 			 * port got added or went away.
16237 			 *
16238 			 * We reset the capabilities and set the
16239 			 * state to IDS_RENG so that when the ack
16240 			 * comes back, we can start the
16241 			 * renegotiation process.
16242 			 */
16243 			ill_capability_reset(ill);
16244 			ill->ill_dlpi_capab_state = IDS_RENEG;
16245 			break;
16246 		default:
16247 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
16248 			    "type 0x%x for DL_NOTIFY_IND\n",
16249 			    notify->dl_notification));
16250 			break;
16251 		}
16252 
16253 		/*
16254 		 * As this is an asynchronous operation, we
16255 		 * should not call ill_dlpi_done
16256 		 */
16257 		break;
16258 	}
16259 	case DL_NOTIFY_ACK: {
16260 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
16261 
16262 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
16263 			ill->ill_note_link = 1;
16264 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
16265 		break;
16266 	}
16267 	case DL_PHYS_ADDR_ACK: {
16268 		/*
16269 		 * As part of plumbing the interface via SIOCSLIFNAME,
16270 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
16271 		 * whose answers we receive here.  As each answer is received,
16272 		 * we call ill_dlpi_done() to dispatch the next request as
16273 		 * we're processing the current one.  Once all answers have
16274 		 * been received, we use ipsq_pending_mp_get() to dequeue the
16275 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
16276 		 * is invoked from an ill queue, conn_oper_pending_ill is not
16277 		 * available, but we know the ioctl is pending on ill_wq.)
16278 		 */
16279 		uint_t paddrlen, paddroff;
16280 
16281 		paddrreq = ill->ill_phys_addr_pend;
16282 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
16283 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
16284 
16285 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
16286 		if (paddrreq == DL_IPV6_TOKEN) {
16287 			/*
16288 			 * bcopy to low-order bits of ill_token
16289 			 *
16290 			 * XXX Temporary hack - currently, all known tokens
16291 			 * are 64 bits, so I'll cheat for the moment.
16292 			 */
16293 			bcopy(mp->b_rptr + paddroff,
16294 			    &ill->ill_token.s6_addr32[2], paddrlen);
16295 			ill->ill_token_length = paddrlen;
16296 			break;
16297 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16298 			ASSERT(ill->ill_nd_lla_mp == NULL);
16299 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
16300 			mp = NULL;
16301 			break;
16302 		}
16303 
16304 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
16305 		ASSERT(ill->ill_phys_addr_mp == NULL);
16306 		if (!ill->ill_ifname_pending)
16307 			break;
16308 		ill->ill_ifname_pending = 0;
16309 		if (!ioctl_aborted)
16310 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16311 		if (mp1 != NULL) {
16312 			ASSERT(connp == NULL);
16313 			q = ill->ill_wq;
16314 		}
16315 		/*
16316 		 * If any error acks received during the plumbing sequence,
16317 		 * ill_ifname_pending_err will be set. Break out and send up
16318 		 * the error to the pending ioctl.
16319 		 */
16320 		if (ill->ill_ifname_pending_err != 0) {
16321 			err = ill->ill_ifname_pending_err;
16322 			ill->ill_ifname_pending_err = 0;
16323 			break;
16324 		}
16325 
16326 		ill->ill_phys_addr_mp = mp;
16327 		ill->ill_phys_addr = mp->b_rptr + paddroff;
16328 		mp = NULL;
16329 
16330 		/*
16331 		 * If paddrlen is zero, the DLPI provider doesn't support
16332 		 * physical addresses.  The other two tests were historical
16333 		 * workarounds for bugs in our former PPP implementation, but
16334 		 * now other things have grown dependencies on them -- e.g.,
16335 		 * the tun module specifies a dl_addr_length of zero in its
16336 		 * DL_BIND_ACK, but then specifies an incorrect value in its
16337 		 * DL_PHYS_ADDR_ACK.  These bogus checks need to be removed,
16338 		 * but only after careful testing ensures that all dependent
16339 		 * broken DLPI providers have been fixed.
16340 		 */
16341 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0 ||
16342 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
16343 			ill->ill_phys_addr = NULL;
16344 		} else if (paddrlen != ill->ill_phys_addr_length) {
16345 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16346 			    paddrlen, ill->ill_phys_addr_length));
16347 			err = EINVAL;
16348 			break;
16349 		}
16350 
16351 		if (ill->ill_nd_lla_mp == NULL) {
16352 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16353 				err = ENOMEM;
16354 				break;
16355 			}
16356 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16357 		}
16358 
16359 		/*
16360 		 * Set the interface token.  If the zeroth interface address
16361 		 * is unspecified, then set it to the link local address.
16362 		 */
16363 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
16364 			(void) ill_setdefaulttoken(ill);
16365 
16366 		ASSERT(ill->ill_ipif->ipif_id == 0);
16367 		if (ipif != NULL &&
16368 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr)) {
16369 			(void) ipif_setlinklocal(ipif);
16370 		}
16371 		break;
16372 	}
16373 	case DL_OK_ACK:
16374 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16375 		    dlpi_prim_str((int)dloa->dl_correct_primitive),
16376 		    dloa->dl_correct_primitive));
16377 		switch (dloa->dl_correct_primitive) {
16378 		case DL_PROMISCON_REQ:
16379 		case DL_PROMISCOFF_REQ:
16380 		case DL_ENABMULTI_REQ:
16381 		case DL_DISABMULTI_REQ:
16382 		case DL_UNBIND_REQ:
16383 		case DL_ATTACH_REQ:
16384 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16385 			break;
16386 		}
16387 		break;
16388 	default:
16389 		break;
16390 	}
16391 
16392 	freemsg(mp);
16393 	if (mp1 != NULL) {
16394 		/*
16395 		 * The operation must complete without EINPROGRESS
16396 		 * since ipsq_pending_mp_get() has removed the mblk
16397 		 * from ipsq_pending_mp.  Otherwise, the operation
16398 		 * will be stuck forever in the ipsq.
16399 		 */
16400 		ASSERT(err != EINPROGRESS);
16401 
16402 		switch (ipsq->ipsq_current_ioctl) {
16403 		case 0:
16404 			ipsq_current_finish(ipsq);
16405 			break;
16406 
16407 		case SIOCLIFADDIF:
16408 		case SIOCSLIFNAME:
16409 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16410 			break;
16411 
16412 		default:
16413 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16414 			break;
16415 		}
16416 	}
16417 }
16418 
16419 /*
16420  * ip_rput_other is called by ip_rput to handle messages modifying the global
16421  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16422  */
16423 /* ARGSUSED */
16424 void
16425 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16426 {
16427 	ill_t		*ill;
16428 	struct iocblk	*iocp;
16429 	mblk_t		*mp1;
16430 	conn_t		*connp = NULL;
16431 
16432 	ip1dbg(("ip_rput_other "));
16433 	ill = (ill_t *)q->q_ptr;
16434 	/*
16435 	 * This routine is not a writer in the case of SIOCGTUNPARAM
16436 	 * in which case ipsq is NULL.
16437 	 */
16438 	if (ipsq != NULL) {
16439 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16440 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
16441 	}
16442 
16443 	switch (mp->b_datap->db_type) {
16444 	case M_ERROR:
16445 	case M_HANGUP:
16446 		/*
16447 		 * The device has a problem.  We force the ILL down.  It can
16448 		 * be brought up again manually using SIOCSIFFLAGS (via
16449 		 * ifconfig or equivalent).
16450 		 */
16451 		ASSERT(ipsq != NULL);
16452 		if (mp->b_rptr < mp->b_wptr)
16453 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16454 		if (ill->ill_error == 0)
16455 			ill->ill_error = ENXIO;
16456 		if (!ill_down_start(q, mp))
16457 			return;
16458 		ipif_all_down_tail(ipsq, q, mp, NULL);
16459 		break;
16460 	case M_IOCACK:
16461 		iocp = (struct iocblk *)mp->b_rptr;
16462 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16463 		switch (iocp->ioc_cmd) {
16464 		case SIOCSTUNPARAM:
16465 		case OSIOCSTUNPARAM:
16466 			ASSERT(ipsq != NULL);
16467 			/*
16468 			 * Finish socket ioctl passed through to tun.
16469 			 * We should have an IOCTL waiting on this.
16470 			 */
16471 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16472 			if (ill->ill_isv6) {
16473 				struct iftun_req *ta;
16474 
16475 				/*
16476 				 * if a source or destination is
16477 				 * being set, try and set the link
16478 				 * local address for the tunnel
16479 				 */
16480 				ta = (struct iftun_req *)mp->b_cont->
16481 				    b_cont->b_rptr;
16482 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16483 					ipif_set_tun_llink(ill, ta);
16484 				}
16485 
16486 			}
16487 			if (mp1 != NULL) {
16488 				/*
16489 				 * Now copy back the b_next/b_prev used by
16490 				 * mi code for the mi_copy* functions.
16491 				 * See ip_sioctl_tunparam() for the reason.
16492 				 * Also protect against missing b_cont.
16493 				 */
16494 				if (mp->b_cont != NULL) {
16495 					mp->b_cont->b_next =
16496 					    mp1->b_cont->b_next;
16497 					mp->b_cont->b_prev =
16498 					    mp1->b_cont->b_prev;
16499 				}
16500 				inet_freemsg(mp1);
16501 				ASSERT(connp != NULL);
16502 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16503 				    iocp->ioc_error, NO_COPYOUT, ipsq);
16504 			} else {
16505 				ASSERT(connp == NULL);
16506 				putnext(q, mp);
16507 			}
16508 			break;
16509 		case SIOCGTUNPARAM:
16510 		case OSIOCGTUNPARAM:
16511 			/*
16512 			 * This is really M_IOCDATA from the tunnel driver.
16513 			 * convert back and complete the ioctl.
16514 			 * We should have an IOCTL waiting on this.
16515 			 */
16516 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16517 			if (mp1) {
16518 				/*
16519 				 * Now copy back the b_next/b_prev used by
16520 				 * mi code for the mi_copy* functions.
16521 				 * See ip_sioctl_tunparam() for the reason.
16522 				 * Also protect against missing b_cont.
16523 				 */
16524 				if (mp->b_cont != NULL) {
16525 					mp->b_cont->b_next =
16526 					    mp1->b_cont->b_next;
16527 					mp->b_cont->b_prev =
16528 					    mp1->b_cont->b_prev;
16529 				}
16530 				inet_freemsg(mp1);
16531 				if (iocp->ioc_error == 0)
16532 					mp->b_datap->db_type = M_IOCDATA;
16533 				ASSERT(connp != NULL);
16534 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16535 				    iocp->ioc_error, COPYOUT, NULL);
16536 			} else {
16537 				ASSERT(connp == NULL);
16538 				putnext(q, mp);
16539 			}
16540 			break;
16541 		default:
16542 			break;
16543 		}
16544 		break;
16545 	case M_IOCNAK:
16546 		iocp = (struct iocblk *)mp->b_rptr;
16547 
16548 		switch (iocp->ioc_cmd) {
16549 		int mode;
16550 
16551 		case DL_IOC_HDR_INFO:
16552 			/*
16553 			 * If this was the first attempt turn of the
16554 			 * fastpath probing.
16555 			 */
16556 			mutex_enter(&ill->ill_lock);
16557 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16558 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16559 				mutex_exit(&ill->ill_lock);
16560 				ill_fastpath_nack(ill);
16561 				ip1dbg(("ip_rput: DLPI fastpath off on "
16562 				    "interface %s\n",
16563 				    ill->ill_name));
16564 			} else {
16565 				mutex_exit(&ill->ill_lock);
16566 			}
16567 			freemsg(mp);
16568 			break;
16569 		case SIOCSTUNPARAM:
16570 		case OSIOCSTUNPARAM:
16571 			ASSERT(ipsq != NULL);
16572 			/*
16573 			 * Finish socket ioctl passed through to tun
16574 			 * We should have an IOCTL waiting on this.
16575 			 */
16576 			/* FALLTHRU */
16577 		case SIOCGTUNPARAM:
16578 		case OSIOCGTUNPARAM:
16579 			/*
16580 			 * This is really M_IOCDATA from the tunnel driver.
16581 			 * convert back and complete the ioctl.
16582 			 * We should have an IOCTL waiting on this.
16583 			 */
16584 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16585 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16586 				mp1 = ill_pending_mp_get(ill, &connp,
16587 				    iocp->ioc_id);
16588 				mode = COPYOUT;
16589 				ipsq = NULL;
16590 			} else {
16591 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16592 				mode = NO_COPYOUT;
16593 			}
16594 			if (mp1 != NULL) {
16595 				/*
16596 				 * Now copy back the b_next/b_prev used by
16597 				 * mi code for the mi_copy* functions.
16598 				 * See ip_sioctl_tunparam() for the reason.
16599 				 * Also protect against missing b_cont.
16600 				 */
16601 				if (mp->b_cont != NULL) {
16602 					mp->b_cont->b_next =
16603 					    mp1->b_cont->b_next;
16604 					mp->b_cont->b_prev =
16605 					    mp1->b_cont->b_prev;
16606 				}
16607 				inet_freemsg(mp1);
16608 				if (iocp->ioc_error == 0)
16609 					iocp->ioc_error = EINVAL;
16610 				ASSERT(connp != NULL);
16611 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16612 				    iocp->ioc_error, mode, ipsq);
16613 			} else {
16614 				ASSERT(connp == NULL);
16615 				putnext(q, mp);
16616 			}
16617 			break;
16618 		default:
16619 			break;
16620 		}
16621 	default:
16622 		break;
16623 	}
16624 }
16625 
16626 /*
16627  * NOTE : This function does not ire_refrele the ire argument passed in.
16628  *
16629  * IPQoS notes
16630  * IP policy is invoked twice for a forwarded packet, once on the read side
16631  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16632  * enabled. An additional parameter, in_ill, has been added for this purpose.
16633  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16634  * because ip_mroute drops this information.
16635  *
16636  */
16637 void
16638 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16639 {
16640 	uint32_t	old_pkt_len;
16641 	uint32_t	pkt_len;
16642 	queue_t	*q;
16643 	uint32_t	sum;
16644 #define	rptr	((uchar_t *)ipha)
16645 	uint32_t	max_frag;
16646 	uint32_t	ill_index;
16647 	ill_t		*out_ill;
16648 	mib2_ipIfStatsEntry_t *mibptr;
16649 	ip_stack_t	*ipst = in_ill->ill_ipst;
16650 
16651 	/* Get the ill_index of the incoming ILL */
16652 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16653 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16654 
16655 	/* Initiate Read side IPPF processing */
16656 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16657 		ip_process(IPP_FWD_IN, &mp, ill_index);
16658 		if (mp == NULL) {
16659 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16660 			    "during IPPF processing\n"));
16661 			return;
16662 		}
16663 	}
16664 
16665 	/* Adjust the checksum to reflect the ttl decrement. */
16666 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16667 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16668 
16669 	if (ipha->ipha_ttl-- <= 1) {
16670 		if (ip_csum_hdr(ipha)) {
16671 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16672 			goto drop_pkt;
16673 		}
16674 		/*
16675 		 * Note: ire_stq this will be NULL for multicast
16676 		 * datagrams using the long path through arp (the IRE
16677 		 * is not an IRE_CACHE). This should not cause
16678 		 * problems since we don't generate ICMP errors for
16679 		 * multicast packets.
16680 		 */
16681 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16682 		q = ire->ire_stq;
16683 		if (q != NULL) {
16684 			/* Sent by forwarding path, and router is global zone */
16685 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16686 			    GLOBAL_ZONEID, ipst);
16687 		} else
16688 			freemsg(mp);
16689 		return;
16690 	}
16691 
16692 	/*
16693 	 * Don't forward if the interface is down
16694 	 */
16695 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16696 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16697 		ip2dbg(("ip_rput_forward:interface is down\n"));
16698 		goto drop_pkt;
16699 	}
16700 
16701 	/* Get the ill_index of the outgoing ILL */
16702 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
16703 
16704 	out_ill = ire->ire_ipif->ipif_ill;
16705 
16706 	DTRACE_PROBE4(ip4__forwarding__start,
16707 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16708 
16709 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16710 	    ipst->ips_ipv4firewall_forwarding,
16711 	    in_ill, out_ill, ipha, mp, mp, ipst);
16712 
16713 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16714 
16715 	if (mp == NULL)
16716 		return;
16717 	old_pkt_len = pkt_len = ntohs(ipha->ipha_length);
16718 
16719 	if (is_system_labeled()) {
16720 		mblk_t *mp1;
16721 
16722 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16723 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16724 			goto drop_pkt;
16725 		}
16726 		/* Size may have changed */
16727 		mp = mp1;
16728 		ipha = (ipha_t *)mp->b_rptr;
16729 		pkt_len = ntohs(ipha->ipha_length);
16730 	}
16731 
16732 	/* Check if there are options to update */
16733 	if (!IS_SIMPLE_IPH(ipha)) {
16734 		if (ip_csum_hdr(ipha)) {
16735 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16736 			goto drop_pkt;
16737 		}
16738 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16739 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16740 			return;
16741 		}
16742 
16743 		ipha->ipha_hdr_checksum = 0;
16744 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16745 	}
16746 	max_frag = ire->ire_max_frag;
16747 	if (pkt_len > max_frag) {
16748 		/*
16749 		 * It needs fragging on its way out.  We haven't
16750 		 * verified the header checksum yet.  Since we
16751 		 * are going to put a surely good checksum in the
16752 		 * outgoing header, we have to make sure that it
16753 		 * was good coming in.
16754 		 */
16755 		if (ip_csum_hdr(ipha)) {
16756 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16757 			goto drop_pkt;
16758 		}
16759 		/* Initiate Write side IPPF processing */
16760 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16761 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16762 			if (mp == NULL) {
16763 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16764 				    " during IPPF processing\n"));
16765 				return;
16766 			}
16767 		}
16768 		/*
16769 		 * Handle labeled packet resizing.
16770 		 *
16771 		 * If we have added a label, inform ip_wput_frag() of its
16772 		 * effect on the MTU for ICMP messages.
16773 		 */
16774 		if (pkt_len > old_pkt_len) {
16775 			uint32_t secopt_size;
16776 
16777 			secopt_size = pkt_len - old_pkt_len;
16778 			if (secopt_size < max_frag)
16779 				max_frag -= secopt_size;
16780 		}
16781 
16782 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID, ipst);
16783 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16784 		return;
16785 	}
16786 
16787 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16788 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16789 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16790 	    ipst->ips_ipv4firewall_physical_out,
16791 	    NULL, out_ill, ipha, mp, mp, ipst);
16792 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16793 	if (mp == NULL)
16794 		return;
16795 
16796 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16797 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16798 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE);
16799 	/* ip_xmit_v4 always consumes the packet */
16800 	return;
16801 
16802 drop_pkt:;
16803 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16804 	freemsg(mp);
16805 #undef	rptr
16806 }
16807 
16808 void
16809 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16810 {
16811 	ire_t	*ire;
16812 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
16813 
16814 	ASSERT(!ipif->ipif_isv6);
16815 	/*
16816 	 * Find an IRE which matches the destination and the outgoing
16817 	 * queue in the cache table. All we need is an IRE_CACHE which
16818 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
16819 	 * then it is enough to have some IRE_CACHE in the group.
16820 	 */
16821 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16822 		dst = ipif->ipif_pp_dst_addr;
16823 
16824 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
16825 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR, ipst);
16826 	if (ire == NULL) {
16827 		/*
16828 		 * Mark this packet to make it be delivered to
16829 		 * ip_rput_forward after the new ire has been
16830 		 * created.
16831 		 */
16832 		mp->b_prev = NULL;
16833 		mp->b_next = mp;
16834 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16835 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
16836 	} else {
16837 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16838 		IRE_REFRELE(ire);
16839 	}
16840 }
16841 
16842 /* Update any source route, record route or timestamp options */
16843 static int
16844 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
16845 {
16846 	ipoptp_t	opts;
16847 	uchar_t		*opt;
16848 	uint8_t		optval;
16849 	uint8_t		optlen;
16850 	ipaddr_t	dst;
16851 	uint32_t	ts;
16852 	ire_t		*dst_ire = NULL;
16853 	ire_t		*tmp_ire = NULL;
16854 	timestruc_t	now;
16855 
16856 	ip2dbg(("ip_rput_forward_options\n"));
16857 	dst = ipha->ipha_dst;
16858 	for (optval = ipoptp_first(&opts, ipha);
16859 	    optval != IPOPT_EOL;
16860 	    optval = ipoptp_next(&opts)) {
16861 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16862 		opt = opts.ipoptp_cur;
16863 		optlen = opts.ipoptp_len;
16864 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16865 		    optval, opts.ipoptp_len));
16866 		switch (optval) {
16867 			uint32_t off;
16868 		case IPOPT_SSRR:
16869 		case IPOPT_LSRR:
16870 			/* Check if adminstratively disabled */
16871 			if (!ipst->ips_ip_forward_src_routed) {
16872 				if (ire->ire_stq != NULL) {
16873 					/*
16874 					 * Sent by forwarding path, and router
16875 					 * is global zone
16876 					 */
16877 					icmp_unreachable(ire->ire_stq, mp,
16878 					    ICMP_SOURCE_ROUTE_FAILED,
16879 					    GLOBAL_ZONEID, ipst);
16880 				} else {
16881 					ip0dbg(("ip_rput_forward_options: "
16882 					    "unable to send unreach\n"));
16883 					freemsg(mp);
16884 				}
16885 				return (-1);
16886 			}
16887 
16888 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16889 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16890 			if (dst_ire == NULL) {
16891 				/*
16892 				 * Must be partial since ip_rput_options
16893 				 * checked for strict.
16894 				 */
16895 				break;
16896 			}
16897 			off = opt[IPOPT_OFFSET];
16898 			off--;
16899 		redo_srr:
16900 			if (optlen < IP_ADDR_LEN ||
16901 			    off > optlen - IP_ADDR_LEN) {
16902 				/* End of source route */
16903 				ip1dbg((
16904 				    "ip_rput_forward_options: end of SR\n"));
16905 				ire_refrele(dst_ire);
16906 				break;
16907 			}
16908 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16909 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16910 			    IP_ADDR_LEN);
16911 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16912 			    ntohl(dst)));
16913 
16914 			/*
16915 			 * Check if our address is present more than
16916 			 * once as consecutive hops in source route.
16917 			 */
16918 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16919 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16920 			if (tmp_ire != NULL) {
16921 				ire_refrele(tmp_ire);
16922 				off += IP_ADDR_LEN;
16923 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16924 				goto redo_srr;
16925 			}
16926 			ipha->ipha_dst = dst;
16927 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16928 			ire_refrele(dst_ire);
16929 			break;
16930 		case IPOPT_RR:
16931 			off = opt[IPOPT_OFFSET];
16932 			off--;
16933 			if (optlen < IP_ADDR_LEN ||
16934 			    off > optlen - IP_ADDR_LEN) {
16935 				/* No more room - ignore */
16936 				ip1dbg((
16937 				    "ip_rput_forward_options: end of RR\n"));
16938 				break;
16939 			}
16940 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16941 			    IP_ADDR_LEN);
16942 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16943 			break;
16944 		case IPOPT_TS:
16945 			/* Insert timestamp if there is room */
16946 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16947 			case IPOPT_TS_TSONLY:
16948 				off = IPOPT_TS_TIMELEN;
16949 				break;
16950 			case IPOPT_TS_PRESPEC:
16951 			case IPOPT_TS_PRESPEC_RFC791:
16952 				/* Verify that the address matched */
16953 				off = opt[IPOPT_OFFSET] - 1;
16954 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16955 				dst_ire = ire_ctable_lookup(dst, 0,
16956 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16957 				    MATCH_IRE_TYPE, ipst);
16958 				if (dst_ire == NULL) {
16959 					/* Not for us */
16960 					break;
16961 				}
16962 				ire_refrele(dst_ire);
16963 				/* FALLTHRU */
16964 			case IPOPT_TS_TSANDADDR:
16965 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16966 				break;
16967 			default:
16968 				/*
16969 				 * ip_*put_options should have already
16970 				 * dropped this packet.
16971 				 */
16972 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16973 				    "unknown IT - bug in ip_rput_options?\n");
16974 				return (0);	/* Keep "lint" happy */
16975 			}
16976 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16977 				/* Increase overflow counter */
16978 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16979 				opt[IPOPT_POS_OV_FLG] =
16980 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16981 				    (off << 4));
16982 				break;
16983 			}
16984 			off = opt[IPOPT_OFFSET] - 1;
16985 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16986 			case IPOPT_TS_PRESPEC:
16987 			case IPOPT_TS_PRESPEC_RFC791:
16988 			case IPOPT_TS_TSANDADDR:
16989 				bcopy(&ire->ire_src_addr,
16990 				    (char *)opt + off, IP_ADDR_LEN);
16991 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16992 				/* FALLTHRU */
16993 			case IPOPT_TS_TSONLY:
16994 				off = opt[IPOPT_OFFSET] - 1;
16995 				/* Compute # of milliseconds since midnight */
16996 				gethrestime(&now);
16997 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16998 				    now.tv_nsec / (NANOSEC / MILLISEC);
16999 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17000 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17001 				break;
17002 			}
17003 			break;
17004 		}
17005 	}
17006 	return (0);
17007 }
17008 
17009 /*
17010  * This is called after processing at least one of AH/ESP headers.
17011  *
17012  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
17013  * the actual, physical interface on which the packet was received,
17014  * but, when ip_strict_dst_multihoming is set to 1, could be the
17015  * interface which had the ipha_dst configured when the packet went
17016  * through ip_rput. The ill_index corresponding to the recv_ill
17017  * is saved in ipsec_in_rill_index
17018  *
17019  * NOTE2: The "ire" argument is only used in IPv4 cases.  This function
17020  * cannot assume "ire" points to valid data for any IPv6 cases.
17021  */
17022 void
17023 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
17024 {
17025 	mblk_t *mp;
17026 	ipaddr_t dst;
17027 	in6_addr_t *v6dstp;
17028 	ipha_t *ipha;
17029 	ip6_t *ip6h;
17030 	ipsec_in_t *ii;
17031 	boolean_t ill_need_rele = B_FALSE;
17032 	boolean_t rill_need_rele = B_FALSE;
17033 	boolean_t ire_need_rele = B_FALSE;
17034 	netstack_t	*ns;
17035 	ip_stack_t	*ipst;
17036 
17037 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
17038 	ASSERT(ii->ipsec_in_ill_index != 0);
17039 	ns = ii->ipsec_in_ns;
17040 	ASSERT(ii->ipsec_in_ns != NULL);
17041 	ipst = ns->netstack_ip;
17042 
17043 	mp = ipsec_mp->b_cont;
17044 	ASSERT(mp != NULL);
17045 
17046 
17047 	if (ill == NULL) {
17048 		ASSERT(recv_ill == NULL);
17049 		/*
17050 		 * We need to get the original queue on which ip_rput_local
17051 		 * or ip_rput_data_v6 was called.
17052 		 */
17053 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
17054 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
17055 		ill_need_rele = B_TRUE;
17056 
17057 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
17058 			recv_ill = ill_lookup_on_ifindex(
17059 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
17060 			    NULL, NULL, NULL, NULL, ipst);
17061 			rill_need_rele = B_TRUE;
17062 		} else {
17063 			recv_ill = ill;
17064 		}
17065 
17066 		if ((ill == NULL) || (recv_ill == NULL)) {
17067 			ip0dbg(("ip_fanout_proto_again: interface "
17068 			    "disappeared\n"));
17069 			if (ill != NULL)
17070 				ill_refrele(ill);
17071 			if (recv_ill != NULL)
17072 				ill_refrele(recv_ill);
17073 			freemsg(ipsec_mp);
17074 			return;
17075 		}
17076 	}
17077 
17078 	ASSERT(ill != NULL && recv_ill != NULL);
17079 
17080 	if (mp->b_datap->db_type == M_CTL) {
17081 		/*
17082 		 * AH/ESP is returning the ICMP message after
17083 		 * removing their headers. Fanout again till
17084 		 * it gets to the right protocol.
17085 		 */
17086 		if (ii->ipsec_in_v4) {
17087 			icmph_t *icmph;
17088 			int iph_hdr_length;
17089 			int hdr_length;
17090 
17091 			ipha = (ipha_t *)mp->b_rptr;
17092 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
17093 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
17094 			ipha = (ipha_t *)&icmph[1];
17095 			hdr_length = IPH_HDR_LENGTH(ipha);
17096 			/*
17097 			 * icmp_inbound_error_fanout may need to do pullupmsg.
17098 			 * Reset the type to M_DATA.
17099 			 */
17100 			mp->b_datap->db_type = M_DATA;
17101 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
17102 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
17103 			    B_FALSE, ill, ii->ipsec_in_zoneid);
17104 		} else {
17105 			icmp6_t *icmp6;
17106 			int hdr_length;
17107 
17108 			ip6h = (ip6_t *)mp->b_rptr;
17109 			/* Don't call hdr_length_v6() unless you have to. */
17110 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
17111 				hdr_length = ip_hdr_length_v6(mp, ip6h);
17112 			else
17113 				hdr_length = IPV6_HDR_LEN;
17114 
17115 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
17116 			/*
17117 			 * icmp_inbound_error_fanout_v6 may need to do
17118 			 * pullupmsg.  Reset the type to M_DATA.
17119 			 */
17120 			mp->b_datap->db_type = M_DATA;
17121 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
17122 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
17123 		}
17124 		if (ill_need_rele)
17125 			ill_refrele(ill);
17126 		if (rill_need_rele)
17127 			ill_refrele(recv_ill);
17128 		return;
17129 	}
17130 
17131 	if (ii->ipsec_in_v4) {
17132 		ipha = (ipha_t *)mp->b_rptr;
17133 		dst = ipha->ipha_dst;
17134 		if (CLASSD(dst)) {
17135 			/*
17136 			 * Multicast has to be delivered to all streams.
17137 			 */
17138 			dst = INADDR_BROADCAST;
17139 		}
17140 
17141 		if (ire == NULL) {
17142 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
17143 			    MBLK_GETLABEL(mp), ipst);
17144 			if (ire == NULL) {
17145 				if (ill_need_rele)
17146 					ill_refrele(ill);
17147 				if (rill_need_rele)
17148 					ill_refrele(recv_ill);
17149 				ip1dbg(("ip_fanout_proto_again: "
17150 				    "IRE not found"));
17151 				freemsg(ipsec_mp);
17152 				return;
17153 			}
17154 			ire_need_rele = B_TRUE;
17155 		}
17156 
17157 		switch (ipha->ipha_protocol) {
17158 			case IPPROTO_UDP:
17159 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
17160 				    recv_ill);
17161 				if (ire_need_rele)
17162 					ire_refrele(ire);
17163 				break;
17164 			case IPPROTO_TCP:
17165 				if (!ire_need_rele)
17166 					IRE_REFHOLD(ire);
17167 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
17168 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
17169 				IRE_REFRELE(ire);
17170 				if (mp != NULL)
17171 					squeue_enter_chain(GET_SQUEUE(mp), mp,
17172 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
17173 				break;
17174 			case IPPROTO_SCTP:
17175 				if (!ire_need_rele)
17176 					IRE_REFHOLD(ire);
17177 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
17178 				    ipsec_mp, 0, ill->ill_rq, dst);
17179 				break;
17180 			default:
17181 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
17182 				    recv_ill);
17183 				if (ire_need_rele)
17184 					ire_refrele(ire);
17185 				break;
17186 		}
17187 	} else {
17188 		uint32_t rput_flags = 0;
17189 
17190 		ip6h = (ip6_t *)mp->b_rptr;
17191 		v6dstp = &ip6h->ip6_dst;
17192 		/*
17193 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
17194 		 * address.
17195 		 *
17196 		 * Currently, we don't store that state in the IPSEC_IN
17197 		 * message, and we may need to.
17198 		 */
17199 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
17200 		    IP6_IN_LLMCAST : 0);
17201 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
17202 		    NULL, NULL);
17203 	}
17204 	if (ill_need_rele)
17205 		ill_refrele(ill);
17206 	if (rill_need_rele)
17207 		ill_refrele(recv_ill);
17208 }
17209 
17210 /*
17211  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
17212  * returns 'true' if there are still fragments left on the queue, in
17213  * which case we restart the timer.
17214  */
17215 void
17216 ill_frag_timer(void *arg)
17217 {
17218 	ill_t	*ill = (ill_t *)arg;
17219 	boolean_t frag_pending;
17220 	ip_stack_t	*ipst = ill->ill_ipst;
17221 
17222 	mutex_enter(&ill->ill_lock);
17223 	ASSERT(!ill->ill_fragtimer_executing);
17224 	if (ill->ill_state_flags & ILL_CONDEMNED) {
17225 		ill->ill_frag_timer_id = 0;
17226 		mutex_exit(&ill->ill_lock);
17227 		return;
17228 	}
17229 	ill->ill_fragtimer_executing = 1;
17230 	mutex_exit(&ill->ill_lock);
17231 
17232 	frag_pending = ill_frag_timeout(ill, ipst->ips_ip_g_frag_timeout);
17233 
17234 	/*
17235 	 * Restart the timer, if we have fragments pending or if someone
17236 	 * wanted us to be scheduled again.
17237 	 */
17238 	mutex_enter(&ill->ill_lock);
17239 	ill->ill_fragtimer_executing = 0;
17240 	ill->ill_frag_timer_id = 0;
17241 	if (frag_pending || ill->ill_fragtimer_needrestart)
17242 		ill_frag_timer_start(ill);
17243 	mutex_exit(&ill->ill_lock);
17244 }
17245 
17246 void
17247 ill_frag_timer_start(ill_t *ill)
17248 {
17249 	ip_stack_t	*ipst = ill->ill_ipst;
17250 
17251 	ASSERT(MUTEX_HELD(&ill->ill_lock));
17252 
17253 	/* If the ill is closing or opening don't proceed */
17254 	if (ill->ill_state_flags & ILL_CONDEMNED)
17255 		return;
17256 
17257 	if (ill->ill_fragtimer_executing) {
17258 		/*
17259 		 * ill_frag_timer is currently executing. Just record the
17260 		 * the fact that we want the timer to be restarted.
17261 		 * ill_frag_timer will post a timeout before it returns,
17262 		 * ensuring it will be called again.
17263 		 */
17264 		ill->ill_fragtimer_needrestart = 1;
17265 		return;
17266 	}
17267 
17268 	if (ill->ill_frag_timer_id == 0) {
17269 		/*
17270 		 * The timer is neither running nor is the timeout handler
17271 		 * executing. Post a timeout so that ill_frag_timer will be
17272 		 * called
17273 		 */
17274 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
17275 		    MSEC_TO_TICK(ipst->ips_ip_g_frag_timo_ms >> 1));
17276 		ill->ill_fragtimer_needrestart = 0;
17277 	}
17278 }
17279 
17280 /*
17281  * This routine is needed for loopback when forwarding multicasts.
17282  *
17283  * IPQoS Notes:
17284  * IPPF processing is done in fanout routines.
17285  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
17286  * processing for IPSec packets is done when it comes back in clear.
17287  * NOTE : The callers of this function need to do the ire_refrele for the
17288  *	  ire that is being passed in.
17289  */
17290 void
17291 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17292     ill_t *recv_ill)
17293 {
17294 	ill_t	*ill = (ill_t *)q->q_ptr;
17295 	uint32_t	sum;
17296 	uint32_t	u1;
17297 	uint32_t	u2;
17298 	int		hdr_length;
17299 	boolean_t	mctl_present;
17300 	mblk_t		*first_mp = mp;
17301 	mblk_t		*hada_mp = NULL;
17302 	ipha_t		*inner_ipha;
17303 	ip_stack_t	*ipst;
17304 
17305 	ASSERT(recv_ill != NULL);
17306 	ipst = recv_ill->ill_ipst;
17307 
17308 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17309 	    "ip_rput_locl_start: q %p", q);
17310 
17311 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17312 	ASSERT(ill != NULL);
17313 
17314 
17315 #define	rptr	((uchar_t *)ipha)
17316 #define	iphs	((uint16_t *)ipha)
17317 
17318 	/*
17319 	 * no UDP or TCP packet should come here anymore.
17320 	 */
17321 	ASSERT((ipha->ipha_protocol != IPPROTO_TCP) &&
17322 	    (ipha->ipha_protocol != IPPROTO_UDP));
17323 
17324 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17325 	if (mctl_present &&
17326 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17327 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17328 
17329 		/*
17330 		 * It's an IPsec accelerated packet.
17331 		 * Keep a pointer to the data attributes around until
17332 		 * we allocate the ipsec_info_t.
17333 		 */
17334 		IPSECHW_DEBUG(IPSECHW_PKT,
17335 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17336 		hada_mp = first_mp;
17337 		hada_mp->b_cont = NULL;
17338 		/*
17339 		 * Since it is accelerated, it comes directly from
17340 		 * the ill and the data attributes is followed by
17341 		 * the packet data.
17342 		 */
17343 		ASSERT(mp->b_datap->db_type != M_CTL);
17344 		first_mp = mp;
17345 		mctl_present = B_FALSE;
17346 	}
17347 
17348 	/*
17349 	 * IF M_CTL is not present, then ipsec_in_is_secure
17350 	 * should return B_TRUE. There is a case where loopback
17351 	 * packets has an M_CTL in the front with all the
17352 	 * IPSEC options set to IPSEC_PREF_NEVER - which means
17353 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17354 	 * packets never comes here, it is safe to ASSERT the
17355 	 * following.
17356 	 */
17357 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17358 
17359 
17360 	/* u1 is # words of IP options */
17361 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
17362 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17363 
17364 	if (u1) {
17365 		if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17366 			if (hada_mp != NULL)
17367 				freemsg(hada_mp);
17368 			return;
17369 		}
17370 	} else {
17371 		/* Check the IP header checksum.  */
17372 #define	uph	((uint16_t *)ipha)
17373 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
17374 		    uph[6] + uph[7] + uph[8] + uph[9];
17375 #undef  uph
17376 		/* finish doing IP checksum */
17377 		sum = (sum & 0xFFFF) + (sum >> 16);
17378 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
17379 		/*
17380 		 * Don't verify header checksum if this packet is coming
17381 		 * back from AH/ESP as we already did it.
17382 		 */
17383 		if (!mctl_present && (sum && sum != 0xFFFF)) {
17384 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17385 			goto drop_pkt;
17386 		}
17387 	}
17388 
17389 	/*
17390 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17391 	 * might be called more than once for secure packets, count only
17392 	 * the first time.
17393 	 */
17394 	if (!mctl_present) {
17395 		UPDATE_IB_PKT_COUNT(ire);
17396 		ire->ire_last_used_time = lbolt;
17397 	}
17398 
17399 	/* Check for fragmentation offset. */
17400 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17401 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17402 	if (u1) {
17403 		/*
17404 		 * We re-assemble fragments before we do the AH/ESP
17405 		 * processing. Thus, M_CTL should not be present
17406 		 * while we are re-assembling.
17407 		 */
17408 		ASSERT(!mctl_present);
17409 		ASSERT(first_mp == mp);
17410 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
17411 			return;
17412 		}
17413 		/*
17414 		 * Make sure that first_mp points back to mp as
17415 		 * the mp we came in with could have changed in
17416 		 * ip_rput_fragment().
17417 		 */
17418 		ipha = (ipha_t *)mp->b_rptr;
17419 		first_mp = mp;
17420 	}
17421 
17422 	/*
17423 	 * Clear hardware checksumming flag as it is currently only
17424 	 * used by TCP and UDP.
17425 	 */
17426 	DB_CKSUMFLAGS(mp) = 0;
17427 
17428 	/* Now we have a complete datagram, destined for this machine. */
17429 	u1 = IPH_HDR_LENGTH(ipha);
17430 	switch (ipha->ipha_protocol) {
17431 	case IPPROTO_ICMP: {
17432 		ire_t		*ire_zone;
17433 		ilm_t		*ilm;
17434 		mblk_t		*mp1;
17435 		zoneid_t	last_zoneid;
17436 
17437 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(recv_ill)) {
17438 			ASSERT(ire->ire_type == IRE_BROADCAST);
17439 			/*
17440 			 * In the multicast case, applications may have joined
17441 			 * the group from different zones, so we need to deliver
17442 			 * the packet to each of them. Loop through the
17443 			 * multicast memberships structures (ilm) on the receive
17444 			 * ill and send a copy of the packet up each matching
17445 			 * one. However, we don't do this for multicasts sent on
17446 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17447 			 * they must stay in the sender's zone.
17448 			 *
17449 			 * ilm_add_v6() ensures that ilms in the same zone are
17450 			 * contiguous in the ill_ilm list. We use this property
17451 			 * to avoid sending duplicates needed when two
17452 			 * applications in the same zone join the same group on
17453 			 * different logical interfaces: we ignore the ilm if
17454 			 * its zoneid is the same as the last matching one.
17455 			 * In addition, the sending of the packet for
17456 			 * ire_zoneid is delayed until all of the other ilms
17457 			 * have been exhausted.
17458 			 */
17459 			last_zoneid = -1;
17460 			ILM_WALKER_HOLD(recv_ill);
17461 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
17462 			    ilm = ilm->ilm_next) {
17463 				if ((ilm->ilm_flags & ILM_DELETED) ||
17464 				    ipha->ipha_dst != ilm->ilm_addr ||
17465 				    ilm->ilm_zoneid == last_zoneid ||
17466 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17467 				    ilm->ilm_zoneid == ALL_ZONES ||
17468 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17469 					continue;
17470 				mp1 = ip_copymsg(first_mp);
17471 				if (mp1 == NULL)
17472 					continue;
17473 				icmp_inbound(q, mp1, B_TRUE, ill,
17474 				    0, sum, mctl_present, B_TRUE,
17475 				    recv_ill, ilm->ilm_zoneid);
17476 				last_zoneid = ilm->ilm_zoneid;
17477 			}
17478 			ILM_WALKER_RELE(recv_ill);
17479 		} else if (ire->ire_type == IRE_BROADCAST) {
17480 			/*
17481 			 * In the broadcast case, there may be many zones
17482 			 * which need a copy of the packet delivered to them.
17483 			 * There is one IRE_BROADCAST per broadcast address
17484 			 * and per zone; we walk those using a helper function.
17485 			 * In addition, the sending of the packet for ire is
17486 			 * delayed until all of the other ires have been
17487 			 * processed.
17488 			 */
17489 			IRB_REFHOLD(ire->ire_bucket);
17490 			ire_zone = NULL;
17491 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17492 			    ire)) != NULL) {
17493 				mp1 = ip_copymsg(first_mp);
17494 				if (mp1 == NULL)
17495 					continue;
17496 
17497 				UPDATE_IB_PKT_COUNT(ire_zone);
17498 				ire_zone->ire_last_used_time = lbolt;
17499 				icmp_inbound(q, mp1, B_TRUE, ill,
17500 				    0, sum, mctl_present, B_TRUE,
17501 				    recv_ill, ire_zone->ire_zoneid);
17502 			}
17503 			IRB_REFRELE(ire->ire_bucket);
17504 		}
17505 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17506 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17507 		    ire->ire_zoneid);
17508 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17509 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17510 		return;
17511 	}
17512 	case IPPROTO_IGMP:
17513 		/*
17514 		 * If we are not willing to accept IGMP packets in clear,
17515 		 * then check with global policy.
17516 		 */
17517 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17518 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17519 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17520 			if (first_mp == NULL)
17521 				return;
17522 		}
17523 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17524 			freemsg(first_mp);
17525 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17526 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17527 			return;
17528 		}
17529 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17530 			/* Bad packet - discarded by igmp_input */
17531 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17532 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17533 			if (mctl_present)
17534 				freeb(first_mp);
17535 			return;
17536 		}
17537 		/*
17538 		 * igmp_input() may have returned the pulled up message.
17539 		 * So first_mp and ipha need to be reinitialized.
17540 		 */
17541 		ipha = (ipha_t *)mp->b_rptr;
17542 		if (mctl_present)
17543 			first_mp->b_cont = mp;
17544 		else
17545 			first_mp = mp;
17546 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17547 		    connf_head != NULL) {
17548 			/* No user-level listener for IGMP packets */
17549 			goto drop_pkt;
17550 		}
17551 		/* deliver to local raw users */
17552 		break;
17553 	case IPPROTO_PIM:
17554 		/*
17555 		 * If we are not willing to accept PIM packets in clear,
17556 		 * then check with global policy.
17557 		 */
17558 		if (ipst->ips_pim_accept_clear_messages == 0) {
17559 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17560 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17561 			if (first_mp == NULL)
17562 				return;
17563 		}
17564 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17565 			freemsg(first_mp);
17566 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17567 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17568 			return;
17569 		}
17570 		if (pim_input(q, mp, ill) != 0) {
17571 			/* Bad packet - discarded by pim_input */
17572 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17573 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17574 			if (mctl_present)
17575 				freeb(first_mp);
17576 			return;
17577 		}
17578 
17579 		/*
17580 		 * pim_input() may have pulled up the message so ipha needs to
17581 		 * be reinitialized.
17582 		 */
17583 		ipha = (ipha_t *)mp->b_rptr;
17584 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17585 		    connf_head != NULL) {
17586 			/* No user-level listener for PIM packets */
17587 			goto drop_pkt;
17588 		}
17589 		/* deliver to local raw users */
17590 		break;
17591 	case IPPROTO_ENCAP:
17592 		/*
17593 		 * Handle self-encapsulated packets (IP-in-IP where
17594 		 * the inner addresses == the outer addresses).
17595 		 */
17596 		hdr_length = IPH_HDR_LENGTH(ipha);
17597 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17598 		    mp->b_wptr) {
17599 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17600 			    sizeof (ipha_t) - mp->b_rptr)) {
17601 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17602 				freemsg(first_mp);
17603 				return;
17604 			}
17605 			ipha = (ipha_t *)mp->b_rptr;
17606 		}
17607 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17608 		/*
17609 		 * Check the sanity of the inner IP header.
17610 		 */
17611 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17612 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17613 			freemsg(first_mp);
17614 			return;
17615 		}
17616 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17617 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17618 			freemsg(first_mp);
17619 			return;
17620 		}
17621 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17622 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17623 			ipsec_in_t *ii;
17624 
17625 			/*
17626 			 * Self-encapsulated tunnel packet. Remove
17627 			 * the outer IP header and fanout again.
17628 			 * We also need to make sure that the inner
17629 			 * header is pulled up until options.
17630 			 */
17631 			mp->b_rptr = (uchar_t *)inner_ipha;
17632 			ipha = inner_ipha;
17633 			hdr_length = IPH_HDR_LENGTH(ipha);
17634 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17635 				if (!pullupmsg(mp, (uchar_t *)ipha +
17636 				    + hdr_length - mp->b_rptr)) {
17637 					freemsg(first_mp);
17638 					return;
17639 				}
17640 				ipha = (ipha_t *)mp->b_rptr;
17641 			}
17642 			if (!mctl_present) {
17643 				ASSERT(first_mp == mp);
17644 				/*
17645 				 * This means that somebody is sending
17646 				 * Self-encapsualted packets without AH/ESP.
17647 				 * If AH/ESP was present, we would have already
17648 				 * allocated the first_mp.
17649 				 */
17650 				first_mp = ipsec_in_alloc(B_TRUE,
17651 				    ipst->ips_netstack);
17652 				if (first_mp == NULL) {
17653 					ip1dbg(("ip_proto_input: IPSEC_IN "
17654 					    "allocation failure.\n"));
17655 					BUMP_MIB(ill->ill_ip_mib,
17656 					    ipIfStatsInDiscards);
17657 					freemsg(mp);
17658 					return;
17659 				}
17660 				first_mp->b_cont = mp;
17661 			}
17662 			/*
17663 			 * We generally store the ill_index if we need to
17664 			 * do IPSEC processing as we lose the ill queue when
17665 			 * we come back. But in this case, we never should
17666 			 * have to store the ill_index here as it should have
17667 			 * been stored previously when we processed the
17668 			 * AH/ESP header in this routine or for non-ipsec
17669 			 * cases, we still have the queue. But for some bad
17670 			 * packets from the wire, we can get to IPSEC after
17671 			 * this and we better store the index for that case.
17672 			 */
17673 			ill = (ill_t *)q->q_ptr;
17674 			ii = (ipsec_in_t *)first_mp->b_rptr;
17675 			ii->ipsec_in_ill_index =
17676 			    ill->ill_phyint->phyint_ifindex;
17677 			ii->ipsec_in_rill_index =
17678 			    recv_ill->ill_phyint->phyint_ifindex;
17679 			if (ii->ipsec_in_decaps) {
17680 				/*
17681 				 * This packet is self-encapsulated multiple
17682 				 * times. We don't want to recurse infinitely.
17683 				 * To keep it simple, drop the packet.
17684 				 */
17685 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17686 				freemsg(first_mp);
17687 				return;
17688 			}
17689 			ii->ipsec_in_decaps = B_TRUE;
17690 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17691 			    ire);
17692 			return;
17693 		}
17694 		break;
17695 	case IPPROTO_AH:
17696 	case IPPROTO_ESP: {
17697 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17698 
17699 		/*
17700 		 * Fast path for AH/ESP. If this is the first time
17701 		 * we are sending a datagram to AH/ESP, allocate
17702 		 * a IPSEC_IN message and prepend it. Otherwise,
17703 		 * just fanout.
17704 		 */
17705 
17706 		int ipsec_rc;
17707 		ipsec_in_t *ii;
17708 		netstack_t *ns = ipst->ips_netstack;
17709 
17710 		IP_STAT(ipst, ipsec_proto_ahesp);
17711 		if (!mctl_present) {
17712 			ASSERT(first_mp == mp);
17713 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17714 			if (first_mp == NULL) {
17715 				ip1dbg(("ip_proto_input: IPSEC_IN "
17716 				    "allocation failure.\n"));
17717 				freemsg(hada_mp); /* okay ifnull */
17718 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17719 				freemsg(mp);
17720 				return;
17721 			}
17722 			/*
17723 			 * Store the ill_index so that when we come back
17724 			 * from IPSEC we ride on the same queue.
17725 			 */
17726 			ill = (ill_t *)q->q_ptr;
17727 			ii = (ipsec_in_t *)first_mp->b_rptr;
17728 			ii->ipsec_in_ill_index =
17729 			    ill->ill_phyint->phyint_ifindex;
17730 			ii->ipsec_in_rill_index =
17731 			    recv_ill->ill_phyint->phyint_ifindex;
17732 			first_mp->b_cont = mp;
17733 			/*
17734 			 * Cache hardware acceleration info.
17735 			 */
17736 			if (hada_mp != NULL) {
17737 				IPSECHW_DEBUG(IPSECHW_PKT,
17738 				    ("ip_rput_local: caching data attr.\n"));
17739 				ii->ipsec_in_accelerated = B_TRUE;
17740 				ii->ipsec_in_da = hada_mp;
17741 				hada_mp = NULL;
17742 			}
17743 		} else {
17744 			ii = (ipsec_in_t *)first_mp->b_rptr;
17745 		}
17746 
17747 		if (!ipsec_loaded(ipss)) {
17748 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17749 			    ire->ire_zoneid, ipst);
17750 			return;
17751 		}
17752 
17753 		ns = ipst->ips_netstack;
17754 		/* select inbound SA and have IPsec process the pkt */
17755 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17756 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17757 			if (esph == NULL)
17758 				return;
17759 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17760 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17761 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17762 			    first_mp, esph);
17763 		} else {
17764 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
17765 			if (ah == NULL)
17766 				return;
17767 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17768 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17769 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17770 			    first_mp, ah);
17771 		}
17772 
17773 		switch (ipsec_rc) {
17774 		case IPSEC_STATUS_SUCCESS:
17775 			break;
17776 		case IPSEC_STATUS_FAILED:
17777 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17778 			/* FALLTHRU */
17779 		case IPSEC_STATUS_PENDING:
17780 			return;
17781 		}
17782 		/* we're done with IPsec processing, send it up */
17783 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17784 		return;
17785 	}
17786 	default:
17787 		break;
17788 	}
17789 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17790 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17791 		    ire->ire_zoneid));
17792 		goto drop_pkt;
17793 	}
17794 	/*
17795 	 * Handle protocols with which IP is less intimate.  There
17796 	 * can be more than one stream bound to a particular
17797 	 * protocol.  When this is the case, each one gets a copy
17798 	 * of any incoming packets.
17799 	 */
17800 	ip_fanout_proto(q, first_mp, ill, ipha,
17801 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17802 	    B_TRUE, recv_ill, ire->ire_zoneid);
17803 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17804 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17805 	return;
17806 
17807 drop_pkt:
17808 	freemsg(first_mp);
17809 	if (hada_mp != NULL)
17810 		freeb(hada_mp);
17811 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17812 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17813 #undef	rptr
17814 #undef  iphs
17815 
17816 }
17817 
17818 /*
17819  * Update any source route, record route or timestamp options.
17820  * Check that we are at end of strict source route.
17821  * The options have already been checked for sanity in ip_rput_options().
17822  */
17823 static boolean_t
17824 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17825     ip_stack_t *ipst)
17826 {
17827 	ipoptp_t	opts;
17828 	uchar_t		*opt;
17829 	uint8_t		optval;
17830 	uint8_t		optlen;
17831 	ipaddr_t	dst;
17832 	uint32_t	ts;
17833 	ire_t		*dst_ire;
17834 	timestruc_t	now;
17835 	zoneid_t	zoneid;
17836 	ill_t		*ill;
17837 
17838 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17839 
17840 	ip2dbg(("ip_rput_local_options\n"));
17841 
17842 	for (optval = ipoptp_first(&opts, ipha);
17843 	    optval != IPOPT_EOL;
17844 	    optval = ipoptp_next(&opts)) {
17845 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17846 		opt = opts.ipoptp_cur;
17847 		optlen = opts.ipoptp_len;
17848 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17849 		    optval, optlen));
17850 		switch (optval) {
17851 			uint32_t off;
17852 		case IPOPT_SSRR:
17853 		case IPOPT_LSRR:
17854 			off = opt[IPOPT_OFFSET];
17855 			off--;
17856 			if (optlen < IP_ADDR_LEN ||
17857 			    off > optlen - IP_ADDR_LEN) {
17858 				/* End of source route */
17859 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17860 				break;
17861 			}
17862 			/*
17863 			 * This will only happen if two consecutive entries
17864 			 * in the source route contains our address or if
17865 			 * it is a packet with a loose source route which
17866 			 * reaches us before consuming the whole source route
17867 			 */
17868 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17869 			if (optval == IPOPT_SSRR) {
17870 				goto bad_src_route;
17871 			}
17872 			/*
17873 			 * Hack: instead of dropping the packet truncate the
17874 			 * source route to what has been used by filling the
17875 			 * rest with IPOPT_NOP.
17876 			 */
17877 			opt[IPOPT_OLEN] = (uint8_t)off;
17878 			while (off < optlen) {
17879 				opt[off++] = IPOPT_NOP;
17880 			}
17881 			break;
17882 		case IPOPT_RR:
17883 			off = opt[IPOPT_OFFSET];
17884 			off--;
17885 			if (optlen < IP_ADDR_LEN ||
17886 			    off > optlen - IP_ADDR_LEN) {
17887 				/* No more room - ignore */
17888 				ip1dbg((
17889 				    "ip_rput_local_options: end of RR\n"));
17890 				break;
17891 			}
17892 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17893 			    IP_ADDR_LEN);
17894 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17895 			break;
17896 		case IPOPT_TS:
17897 			/* Insert timestamp if there is romm */
17898 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17899 			case IPOPT_TS_TSONLY:
17900 				off = IPOPT_TS_TIMELEN;
17901 				break;
17902 			case IPOPT_TS_PRESPEC:
17903 			case IPOPT_TS_PRESPEC_RFC791:
17904 				/* Verify that the address matched */
17905 				off = opt[IPOPT_OFFSET] - 1;
17906 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17907 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17908 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
17909 				    ipst);
17910 				if (dst_ire == NULL) {
17911 					/* Not for us */
17912 					break;
17913 				}
17914 				ire_refrele(dst_ire);
17915 				/* FALLTHRU */
17916 			case IPOPT_TS_TSANDADDR:
17917 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17918 				break;
17919 			default:
17920 				/*
17921 				 * ip_*put_options should have already
17922 				 * dropped this packet.
17923 				 */
17924 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17925 				    "unknown IT - bug in ip_rput_options?\n");
17926 				return (B_TRUE);	/* Keep "lint" happy */
17927 			}
17928 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17929 				/* Increase overflow counter */
17930 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17931 				opt[IPOPT_POS_OV_FLG] =
17932 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17933 				    (off << 4));
17934 				break;
17935 			}
17936 			off = opt[IPOPT_OFFSET] - 1;
17937 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17938 			case IPOPT_TS_PRESPEC:
17939 			case IPOPT_TS_PRESPEC_RFC791:
17940 			case IPOPT_TS_TSANDADDR:
17941 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17942 				    IP_ADDR_LEN);
17943 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17944 				/* FALLTHRU */
17945 			case IPOPT_TS_TSONLY:
17946 				off = opt[IPOPT_OFFSET] - 1;
17947 				/* Compute # of milliseconds since midnight */
17948 				gethrestime(&now);
17949 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17950 				    now.tv_nsec / (NANOSEC / MILLISEC);
17951 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17952 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17953 				break;
17954 			}
17955 			break;
17956 		}
17957 	}
17958 	return (B_TRUE);
17959 
17960 bad_src_route:
17961 	q = WR(q);
17962 	if (q->q_next != NULL)
17963 		ill = q->q_ptr;
17964 	else
17965 		ill = NULL;
17966 
17967 	/* make sure we clear any indication of a hardware checksum */
17968 	DB_CKSUMFLAGS(mp) = 0;
17969 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
17970 	if (zoneid == ALL_ZONES)
17971 		freemsg(mp);
17972 	else
17973 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17974 	return (B_FALSE);
17975 
17976 }
17977 
17978 /*
17979  * Process IP options in an inbound packet.  If an option affects the
17980  * effective destination address, return the next hop address via dstp.
17981  * Returns -1 if something fails in which case an ICMP error has been sent
17982  * and mp freed.
17983  */
17984 static int
17985 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
17986     ip_stack_t *ipst)
17987 {
17988 	ipoptp_t	opts;
17989 	uchar_t		*opt;
17990 	uint8_t		optval;
17991 	uint8_t		optlen;
17992 	ipaddr_t	dst;
17993 	intptr_t	code = 0;
17994 	ire_t		*ire = NULL;
17995 	zoneid_t	zoneid;
17996 	ill_t		*ill;
17997 
17998 	ip2dbg(("ip_rput_options\n"));
17999 	dst = ipha->ipha_dst;
18000 	for (optval = ipoptp_first(&opts, ipha);
18001 	    optval != IPOPT_EOL;
18002 	    optval = ipoptp_next(&opts)) {
18003 		opt = opts.ipoptp_cur;
18004 		optlen = opts.ipoptp_len;
18005 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
18006 		    optval, optlen));
18007 		/*
18008 		 * Note: we need to verify the checksum before we
18009 		 * modify anything thus this routine only extracts the next
18010 		 * hop dst from any source route.
18011 		 */
18012 		switch (optval) {
18013 			uint32_t off;
18014 		case IPOPT_SSRR:
18015 		case IPOPT_LSRR:
18016 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18017 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
18018 			if (ire == NULL) {
18019 				if (optval == IPOPT_SSRR) {
18020 					ip1dbg(("ip_rput_options: not next"
18021 					    " strict source route 0x%x\n",
18022 					    ntohl(dst)));
18023 					code = (char *)&ipha->ipha_dst -
18024 					    (char *)ipha;
18025 					goto param_prob; /* RouterReq's */
18026 				}
18027 				ip2dbg(("ip_rput_options: "
18028 				    "not next source route 0x%x\n",
18029 				    ntohl(dst)));
18030 				break;
18031 			}
18032 			ire_refrele(ire);
18033 
18034 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18035 				ip1dbg((
18036 				    "ip_rput_options: bad option offset\n"));
18037 				code = (char *)&opt[IPOPT_OLEN] -
18038 				    (char *)ipha;
18039 				goto param_prob;
18040 			}
18041 			off = opt[IPOPT_OFFSET];
18042 			off--;
18043 		redo_srr:
18044 			if (optlen < IP_ADDR_LEN ||
18045 			    off > optlen - IP_ADDR_LEN) {
18046 				/* End of source route */
18047 				ip1dbg(("ip_rput_options: end of SR\n"));
18048 				break;
18049 			}
18050 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
18051 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
18052 			    ntohl(dst)));
18053 
18054 			/*
18055 			 * Check if our address is present more than
18056 			 * once as consecutive hops in source route.
18057 			 * XXX verify per-interface ip_forwarding
18058 			 * for source route?
18059 			 */
18060 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18061 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
18062 
18063 			if (ire != NULL) {
18064 				ire_refrele(ire);
18065 				off += IP_ADDR_LEN;
18066 				goto redo_srr;
18067 			}
18068 
18069 			if (dst == htonl(INADDR_LOOPBACK)) {
18070 				ip1dbg(("ip_rput_options: loopback addr in "
18071 				    "source route!\n"));
18072 				goto bad_src_route;
18073 			}
18074 			/*
18075 			 * For strict: verify that dst is directly
18076 			 * reachable.
18077 			 */
18078 			if (optval == IPOPT_SSRR) {
18079 				ire = ire_ftable_lookup(dst, 0, 0,
18080 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
18081 				    MBLK_GETLABEL(mp),
18082 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
18083 				if (ire == NULL) {
18084 					ip1dbg(("ip_rput_options: SSRR not "
18085 					    "directly reachable: 0x%x\n",
18086 					    ntohl(dst)));
18087 					goto bad_src_route;
18088 				}
18089 				ire_refrele(ire);
18090 			}
18091 			/*
18092 			 * Defer update of the offset and the record route
18093 			 * until the packet is forwarded.
18094 			 */
18095 			break;
18096 		case IPOPT_RR:
18097 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18098 				ip1dbg((
18099 				    "ip_rput_options: bad option offset\n"));
18100 				code = (char *)&opt[IPOPT_OLEN] -
18101 				    (char *)ipha;
18102 				goto param_prob;
18103 			}
18104 			break;
18105 		case IPOPT_TS:
18106 			/*
18107 			 * Verify that length >= 5 and that there is either
18108 			 * room for another timestamp or that the overflow
18109 			 * counter is not maxed out.
18110 			 */
18111 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
18112 			if (optlen < IPOPT_MINLEN_IT) {
18113 				goto param_prob;
18114 			}
18115 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18116 				ip1dbg((
18117 				    "ip_rput_options: bad option offset\n"));
18118 				code = (char *)&opt[IPOPT_OFFSET] -
18119 				    (char *)ipha;
18120 				goto param_prob;
18121 			}
18122 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18123 			case IPOPT_TS_TSONLY:
18124 				off = IPOPT_TS_TIMELEN;
18125 				break;
18126 			case IPOPT_TS_TSANDADDR:
18127 			case IPOPT_TS_PRESPEC:
18128 			case IPOPT_TS_PRESPEC_RFC791:
18129 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18130 				break;
18131 			default:
18132 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
18133 				    (char *)ipha;
18134 				goto param_prob;
18135 			}
18136 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
18137 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
18138 				/*
18139 				 * No room and the overflow counter is 15
18140 				 * already.
18141 				 */
18142 				goto param_prob;
18143 			}
18144 			break;
18145 		}
18146 	}
18147 
18148 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
18149 		*dstp = dst;
18150 		return (0);
18151 	}
18152 
18153 	ip1dbg(("ip_rput_options: error processing IP options."));
18154 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
18155 
18156 param_prob:
18157 	q = WR(q);
18158 	if (q->q_next != NULL)
18159 		ill = q->q_ptr;
18160 	else
18161 		ill = NULL;
18162 
18163 	/* make sure we clear any indication of a hardware checksum */
18164 	DB_CKSUMFLAGS(mp) = 0;
18165 	/* Don't know whether this is for non-global or global/forwarding */
18166 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18167 	if (zoneid == ALL_ZONES)
18168 		freemsg(mp);
18169 	else
18170 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
18171 	return (-1);
18172 
18173 bad_src_route:
18174 	q = WR(q);
18175 	if (q->q_next != NULL)
18176 		ill = q->q_ptr;
18177 	else
18178 		ill = NULL;
18179 
18180 	/* make sure we clear any indication of a hardware checksum */
18181 	DB_CKSUMFLAGS(mp) = 0;
18182 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18183 	if (zoneid == ALL_ZONES)
18184 		freemsg(mp);
18185 	else
18186 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18187 	return (-1);
18188 }
18189 
18190 /*
18191  * IP & ICMP info in >=14 msg's ...
18192  *  - ip fixed part (mib2_ip_t)
18193  *  - icmp fixed part (mib2_icmp_t)
18194  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
18195  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
18196  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
18197  *  - ipRouteAttributeTable (ip 102)	labeled routes
18198  *  - ip multicast membership (ip_member_t)
18199  *  - ip multicast source filtering (ip_grpsrc_t)
18200  *  - igmp fixed part (struct igmpstat)
18201  *  - multicast routing stats (struct mrtstat)
18202  *  - multicast routing vifs (array of struct vifctl)
18203  *  - multicast routing routes (array of struct mfcctl)
18204  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
18205  *					One per ill plus one generic
18206  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
18207  *					One per ill plus one generic
18208  *  - ipv6RouteEntry			all IPv6 IREs
18209  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
18210  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
18211  *  - ipv6AddrEntry			all IPv6 ipifs
18212  *  - ipv6 multicast membership (ipv6_member_t)
18213  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
18214  *
18215  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
18216  *
18217  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
18218  * already filled in by the caller.
18219  * Return value of 0 indicates that no messages were sent and caller
18220  * should free mpctl.
18221  */
18222 int
18223 ip_snmp_get(queue_t *q, mblk_t *mpctl)
18224 {
18225 	ip_stack_t *ipst;
18226 	sctp_stack_t *sctps;
18227 
18228 
18229 	if (q->q_next != NULL) {
18230 		ipst = ILLQ_TO_IPST(q);
18231 	} else {
18232 		ipst = CONNQ_TO_IPST(q);
18233 	}
18234 	ASSERT(ipst != NULL);
18235 	sctps = ipst->ips_netstack->netstack_sctp;
18236 
18237 	if (mpctl == NULL || mpctl->b_cont == NULL) {
18238 		return (0);
18239 	}
18240 
18241 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
18242 	    ipst)) == NULL) {
18243 		return (1);
18244 	}
18245 
18246 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
18247 		return (1);
18248 	}
18249 
18250 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
18251 		return (1);
18252 	}
18253 
18254 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
18255 		return (1);
18256 	}
18257 
18258 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
18259 		return (1);
18260 	}
18261 
18262 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
18263 		return (1);
18264 	}
18265 
18266 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
18267 		return (1);
18268 	}
18269 
18270 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
18271 		return (1);
18272 	}
18273 
18274 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
18275 		return (1);
18276 	}
18277 
18278 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18279 		return (1);
18280 	}
18281 
18282 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18283 		return (1);
18284 	}
18285 
18286 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18287 		return (1);
18288 	}
18289 
18290 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18291 		return (1);
18292 	}
18293 
18294 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18295 		return (1);
18296 	}
18297 
18298 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, ipst)) == NULL) {
18299 		return (1);
18300 	}
18301 
18302 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, ipst);
18303 	if (mpctl == NULL) {
18304 		return (1);
18305 	}
18306 
18307 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18308 		return (1);
18309 	}
18310 	freemsg(mpctl);
18311 	return (1);
18312 }
18313 
18314 
18315 /* Get global (legacy) IPv4 statistics */
18316 static mblk_t *
18317 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18318     ip_stack_t *ipst)
18319 {
18320 	mib2_ip_t		old_ip_mib;
18321 	struct opthdr		*optp;
18322 	mblk_t			*mp2ctl;
18323 
18324 	/*
18325 	 * make a copy of the original message
18326 	 */
18327 	mp2ctl = copymsg(mpctl);
18328 
18329 	/* fixed length IP structure... */
18330 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18331 	optp->level = MIB2_IP;
18332 	optp->name = 0;
18333 	SET_MIB(old_ip_mib.ipForwarding,
18334 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18335 	SET_MIB(old_ip_mib.ipDefaultTTL,
18336 	    (uint32_t)ipst->ips_ip_def_ttl);
18337 	SET_MIB(old_ip_mib.ipReasmTimeout,
18338 	    ipst->ips_ip_g_frag_timeout);
18339 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18340 	    sizeof (mib2_ipAddrEntry_t));
18341 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18342 	    sizeof (mib2_ipRouteEntry_t));
18343 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18344 	    sizeof (mib2_ipNetToMediaEntry_t));
18345 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18346 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18347 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18348 	    sizeof (mib2_ipAttributeEntry_t));
18349 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18350 
18351 	/*
18352 	 * Grab the statistics from the new IP MIB
18353 	 */
18354 	SET_MIB(old_ip_mib.ipInReceives,
18355 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18356 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18357 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18358 	SET_MIB(old_ip_mib.ipForwDatagrams,
18359 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18360 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18361 	    ipmib->ipIfStatsInUnknownProtos);
18362 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18363 	SET_MIB(old_ip_mib.ipInDelivers,
18364 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18365 	SET_MIB(old_ip_mib.ipOutRequests,
18366 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18367 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18368 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18369 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18370 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18371 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18372 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18373 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18374 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18375 
18376 	/* ipRoutingDiscards is not being used */
18377 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18378 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18379 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18380 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18381 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18382 	    ipmib->ipIfStatsReasmDuplicates);
18383 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18384 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18385 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18386 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18387 	SET_MIB(old_ip_mib.rawipInOverflows,
18388 	    ipmib->rawipIfStatsInOverflows);
18389 
18390 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18391 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18392 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18393 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18394 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18395 	    ipmib->ipIfStatsOutSwitchIPVersion);
18396 
18397 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18398 	    (int)sizeof (old_ip_mib))) {
18399 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18400 		    (uint_t)sizeof (old_ip_mib)));
18401 	}
18402 
18403 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18404 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18405 	    (int)optp->level, (int)optp->name, (int)optp->len));
18406 	qreply(q, mpctl);
18407 	return (mp2ctl);
18408 }
18409 
18410 /* Per interface IPv4 statistics */
18411 static mblk_t *
18412 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18413 {
18414 	struct opthdr		*optp;
18415 	mblk_t			*mp2ctl;
18416 	ill_t			*ill;
18417 	ill_walk_context_t	ctx;
18418 	mblk_t			*mp_tail = NULL;
18419 	mib2_ipIfStatsEntry_t	global_ip_mib;
18420 
18421 	/*
18422 	 * Make a copy of the original message
18423 	 */
18424 	mp2ctl = copymsg(mpctl);
18425 
18426 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18427 	optp->level = MIB2_IP;
18428 	optp->name = MIB2_IP_TRAFFIC_STATS;
18429 	/* Include "unknown interface" ip_mib */
18430 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18431 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18432 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18433 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18434 	    (ipst->ips_ip_g_forward ? 1 : 2));
18435 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18436 	    (uint32_t)ipst->ips_ip_def_ttl);
18437 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18438 	    sizeof (mib2_ipIfStatsEntry_t));
18439 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18440 	    sizeof (mib2_ipAddrEntry_t));
18441 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18442 	    sizeof (mib2_ipRouteEntry_t));
18443 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18444 	    sizeof (mib2_ipNetToMediaEntry_t));
18445 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18446 	    sizeof (ip_member_t));
18447 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18448 	    sizeof (ip_grpsrc_t));
18449 
18450 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18451 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18452 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18453 		    "failed to allocate %u bytes\n",
18454 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18455 	}
18456 
18457 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18458 
18459 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18460 	ill = ILL_START_WALK_V4(&ctx, ipst);
18461 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18462 		ill->ill_ip_mib->ipIfStatsIfIndex =
18463 		    ill->ill_phyint->phyint_ifindex;
18464 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18465 		    (ipst->ips_ip_g_forward ? 1 : 2));
18466 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18467 		    (uint32_t)ipst->ips_ip_def_ttl);
18468 
18469 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18470 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18471 		    (char *)ill->ill_ip_mib,
18472 		    (int)sizeof (*ill->ill_ip_mib))) {
18473 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18474 			    "failed to allocate %u bytes\n",
18475 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18476 		}
18477 	}
18478 	rw_exit(&ipst->ips_ill_g_lock);
18479 
18480 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18481 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18482 	    "level %d, name %d, len %d\n",
18483 	    (int)optp->level, (int)optp->name, (int)optp->len));
18484 	qreply(q, mpctl);
18485 
18486 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18487 }
18488 
18489 /* Global IPv4 ICMP statistics */
18490 static mblk_t *
18491 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18492 {
18493 	struct opthdr		*optp;
18494 	mblk_t			*mp2ctl;
18495 
18496 	/*
18497 	 * Make a copy of the original message
18498 	 */
18499 	mp2ctl = copymsg(mpctl);
18500 
18501 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18502 	optp->level = MIB2_ICMP;
18503 	optp->name = 0;
18504 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18505 	    (int)sizeof (ipst->ips_icmp_mib))) {
18506 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18507 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18508 	}
18509 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18510 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18511 	    (int)optp->level, (int)optp->name, (int)optp->len));
18512 	qreply(q, mpctl);
18513 	return (mp2ctl);
18514 }
18515 
18516 /* Global IPv4 IGMP statistics */
18517 static mblk_t *
18518 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18519 {
18520 	struct opthdr		*optp;
18521 	mblk_t			*mp2ctl;
18522 
18523 	/*
18524 	 * make a copy of the original message
18525 	 */
18526 	mp2ctl = copymsg(mpctl);
18527 
18528 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18529 	optp->level = EXPER_IGMP;
18530 	optp->name = 0;
18531 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18532 	    (int)sizeof (ipst->ips_igmpstat))) {
18533 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18534 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18535 	}
18536 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18537 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18538 	    (int)optp->level, (int)optp->name, (int)optp->len));
18539 	qreply(q, mpctl);
18540 	return (mp2ctl);
18541 }
18542 
18543 /* Global IPv4 Multicast Routing statistics */
18544 static mblk_t *
18545 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18546 {
18547 	struct opthdr		*optp;
18548 	mblk_t			*mp2ctl;
18549 
18550 	/*
18551 	 * make a copy of the original message
18552 	 */
18553 	mp2ctl = copymsg(mpctl);
18554 
18555 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18556 	optp->level = EXPER_DVMRP;
18557 	optp->name = 0;
18558 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18559 		ip0dbg(("ip_mroute_stats: failed\n"));
18560 	}
18561 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18562 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18563 	    (int)optp->level, (int)optp->name, (int)optp->len));
18564 	qreply(q, mpctl);
18565 	return (mp2ctl);
18566 }
18567 
18568 /* IPv4 address information */
18569 static mblk_t *
18570 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18571 {
18572 	struct opthdr		*optp;
18573 	mblk_t			*mp2ctl;
18574 	mblk_t			*mp_tail = NULL;
18575 	ill_t			*ill;
18576 	ipif_t			*ipif;
18577 	uint_t			bitval;
18578 	mib2_ipAddrEntry_t	mae;
18579 	zoneid_t		zoneid;
18580 	ill_walk_context_t ctx;
18581 
18582 	/*
18583 	 * make a copy of the original message
18584 	 */
18585 	mp2ctl = copymsg(mpctl);
18586 
18587 	/* ipAddrEntryTable */
18588 
18589 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18590 	optp->level = MIB2_IP;
18591 	optp->name = MIB2_IP_ADDR;
18592 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18593 
18594 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18595 	ill = ILL_START_WALK_V4(&ctx, ipst);
18596 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18597 		for (ipif = ill->ill_ipif; ipif != NULL;
18598 		    ipif = ipif->ipif_next) {
18599 			if (ipif->ipif_zoneid != zoneid &&
18600 			    ipif->ipif_zoneid != ALL_ZONES)
18601 				continue;
18602 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18603 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18604 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18605 
18606 			(void) ipif_get_name(ipif,
18607 			    mae.ipAdEntIfIndex.o_bytes,
18608 			    OCTET_LENGTH);
18609 			mae.ipAdEntIfIndex.o_length =
18610 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18611 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18612 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18613 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18614 			mae.ipAdEntInfo.ae_subnet_len =
18615 			    ip_mask_to_plen(ipif->ipif_net_mask);
18616 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18617 			for (bitval = 1;
18618 			    bitval &&
18619 			    !(bitval & ipif->ipif_brd_addr);
18620 			    bitval <<= 1)
18621 				noop;
18622 			mae.ipAdEntBcastAddr = bitval;
18623 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18624 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18625 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18626 			mae.ipAdEntInfo.ae_broadcast_addr =
18627 			    ipif->ipif_brd_addr;
18628 			mae.ipAdEntInfo.ae_pp_dst_addr =
18629 			    ipif->ipif_pp_dst_addr;
18630 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18631 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18632 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18633 
18634 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18635 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18636 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18637 				    "allocate %u bytes\n",
18638 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18639 			}
18640 		}
18641 	}
18642 	rw_exit(&ipst->ips_ill_g_lock);
18643 
18644 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18645 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18646 	    (int)optp->level, (int)optp->name, (int)optp->len));
18647 	qreply(q, mpctl);
18648 	return (mp2ctl);
18649 }
18650 
18651 /* IPv6 address information */
18652 static mblk_t *
18653 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18654 {
18655 	struct opthdr		*optp;
18656 	mblk_t			*mp2ctl;
18657 	mblk_t			*mp_tail = NULL;
18658 	ill_t			*ill;
18659 	ipif_t			*ipif;
18660 	mib2_ipv6AddrEntry_t	mae6;
18661 	zoneid_t		zoneid;
18662 	ill_walk_context_t	ctx;
18663 
18664 	/*
18665 	 * make a copy of the original message
18666 	 */
18667 	mp2ctl = copymsg(mpctl);
18668 
18669 	/* ipv6AddrEntryTable */
18670 
18671 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18672 	optp->level = MIB2_IP6;
18673 	optp->name = MIB2_IP6_ADDR;
18674 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18675 
18676 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18677 	ill = ILL_START_WALK_V6(&ctx, ipst);
18678 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18679 		for (ipif = ill->ill_ipif; ipif != NULL;
18680 		    ipif = ipif->ipif_next) {
18681 			if (ipif->ipif_zoneid != zoneid &&
18682 			    ipif->ipif_zoneid != ALL_ZONES)
18683 				continue;
18684 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18685 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18686 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18687 
18688 			(void) ipif_get_name(ipif,
18689 			    mae6.ipv6AddrIfIndex.o_bytes,
18690 			    OCTET_LENGTH);
18691 			mae6.ipv6AddrIfIndex.o_length =
18692 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18693 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18694 			mae6.ipv6AddrPfxLength =
18695 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18696 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18697 			mae6.ipv6AddrInfo.ae_subnet_len =
18698 			    mae6.ipv6AddrPfxLength;
18699 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18700 
18701 			/* Type: stateless(1), stateful(2), unknown(3) */
18702 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18703 				mae6.ipv6AddrType = 1;
18704 			else
18705 				mae6.ipv6AddrType = 2;
18706 			/* Anycast: true(1), false(2) */
18707 			if (ipif->ipif_flags & IPIF_ANYCAST)
18708 				mae6.ipv6AddrAnycastFlag = 1;
18709 			else
18710 				mae6.ipv6AddrAnycastFlag = 2;
18711 
18712 			/*
18713 			 * Address status: preferred(1), deprecated(2),
18714 			 * invalid(3), inaccessible(4), unknown(5)
18715 			 */
18716 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18717 				mae6.ipv6AddrStatus = 3;
18718 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18719 				mae6.ipv6AddrStatus = 2;
18720 			else
18721 				mae6.ipv6AddrStatus = 1;
18722 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18723 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18724 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18725 			    ipif->ipif_v6pp_dst_addr;
18726 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18727 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18728 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18729 			mae6.ipv6AddrIdentifier = ill->ill_token;
18730 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18731 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18732 			mae6.ipv6AddrRetransmitTime =
18733 			    ill->ill_reachable_retrans_time;
18734 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18735 			    (char *)&mae6,
18736 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
18737 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18738 				    "allocate %u bytes\n",
18739 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18740 			}
18741 		}
18742 	}
18743 	rw_exit(&ipst->ips_ill_g_lock);
18744 
18745 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18746 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18747 	    (int)optp->level, (int)optp->name, (int)optp->len));
18748 	qreply(q, mpctl);
18749 	return (mp2ctl);
18750 }
18751 
18752 /* IPv4 multicast group membership. */
18753 static mblk_t *
18754 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18755 {
18756 	struct opthdr		*optp;
18757 	mblk_t			*mp2ctl;
18758 	ill_t			*ill;
18759 	ipif_t			*ipif;
18760 	ilm_t			*ilm;
18761 	ip_member_t		ipm;
18762 	mblk_t			*mp_tail = NULL;
18763 	ill_walk_context_t	ctx;
18764 	zoneid_t		zoneid;
18765 
18766 	/*
18767 	 * make a copy of the original message
18768 	 */
18769 	mp2ctl = copymsg(mpctl);
18770 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18771 
18772 	/* ipGroupMember table */
18773 	optp = (struct opthdr *)&mpctl->b_rptr[
18774 	    sizeof (struct T_optmgmt_ack)];
18775 	optp->level = MIB2_IP;
18776 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18777 
18778 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18779 	ill = ILL_START_WALK_V4(&ctx, ipst);
18780 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18781 		ILM_WALKER_HOLD(ill);
18782 		for (ipif = ill->ill_ipif; ipif != NULL;
18783 		    ipif = ipif->ipif_next) {
18784 			if (ipif->ipif_zoneid != zoneid &&
18785 			    ipif->ipif_zoneid != ALL_ZONES)
18786 				continue;	/* not this zone */
18787 			(void) ipif_get_name(ipif,
18788 			    ipm.ipGroupMemberIfIndex.o_bytes,
18789 			    OCTET_LENGTH);
18790 			ipm.ipGroupMemberIfIndex.o_length =
18791 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18792 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18793 				ASSERT(ilm->ilm_ipif != NULL);
18794 				ASSERT(ilm->ilm_ill == NULL);
18795 				if (ilm->ilm_ipif != ipif)
18796 					continue;
18797 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18798 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18799 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18800 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18801 				    (char *)&ipm, (int)sizeof (ipm))) {
18802 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18803 					    "failed to allocate %u bytes\n",
18804 					    (uint_t)sizeof (ipm)));
18805 				}
18806 			}
18807 		}
18808 		ILM_WALKER_RELE(ill);
18809 	}
18810 	rw_exit(&ipst->ips_ill_g_lock);
18811 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18812 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18813 	    (int)optp->level, (int)optp->name, (int)optp->len));
18814 	qreply(q, mpctl);
18815 	return (mp2ctl);
18816 }
18817 
18818 /* IPv6 multicast group membership. */
18819 static mblk_t *
18820 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18821 {
18822 	struct opthdr		*optp;
18823 	mblk_t			*mp2ctl;
18824 	ill_t			*ill;
18825 	ilm_t			*ilm;
18826 	ipv6_member_t		ipm6;
18827 	mblk_t			*mp_tail = NULL;
18828 	ill_walk_context_t	ctx;
18829 	zoneid_t		zoneid;
18830 
18831 	/*
18832 	 * make a copy of the original message
18833 	 */
18834 	mp2ctl = copymsg(mpctl);
18835 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18836 
18837 	/* ip6GroupMember table */
18838 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18839 	optp->level = MIB2_IP6;
18840 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18841 
18842 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18843 	ill = ILL_START_WALK_V6(&ctx, ipst);
18844 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18845 		ILM_WALKER_HOLD(ill);
18846 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18847 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18848 			ASSERT(ilm->ilm_ipif == NULL);
18849 			ASSERT(ilm->ilm_ill != NULL);
18850 			if (ilm->ilm_zoneid != zoneid)
18851 				continue;	/* not this zone */
18852 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18853 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18854 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18855 			if (!snmp_append_data2(mpctl->b_cont,
18856 			    &mp_tail,
18857 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18858 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18859 				    "failed to allocate %u bytes\n",
18860 				    (uint_t)sizeof (ipm6)));
18861 			}
18862 		}
18863 		ILM_WALKER_RELE(ill);
18864 	}
18865 	rw_exit(&ipst->ips_ill_g_lock);
18866 
18867 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18868 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18869 	    (int)optp->level, (int)optp->name, (int)optp->len));
18870 	qreply(q, mpctl);
18871 	return (mp2ctl);
18872 }
18873 
18874 /* IP multicast filtered sources */
18875 static mblk_t *
18876 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18877 {
18878 	struct opthdr		*optp;
18879 	mblk_t			*mp2ctl;
18880 	ill_t			*ill;
18881 	ipif_t			*ipif;
18882 	ilm_t			*ilm;
18883 	ip_grpsrc_t		ips;
18884 	mblk_t			*mp_tail = NULL;
18885 	ill_walk_context_t	ctx;
18886 	zoneid_t		zoneid;
18887 	int			i;
18888 	slist_t			*sl;
18889 
18890 	/*
18891 	 * make a copy of the original message
18892 	 */
18893 	mp2ctl = copymsg(mpctl);
18894 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18895 
18896 	/* ipGroupSource table */
18897 	optp = (struct opthdr *)&mpctl->b_rptr[
18898 	    sizeof (struct T_optmgmt_ack)];
18899 	optp->level = MIB2_IP;
18900 	optp->name = EXPER_IP_GROUP_SOURCES;
18901 
18902 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18903 	ill = ILL_START_WALK_V4(&ctx, ipst);
18904 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18905 		ILM_WALKER_HOLD(ill);
18906 		for (ipif = ill->ill_ipif; ipif != NULL;
18907 		    ipif = ipif->ipif_next) {
18908 			if (ipif->ipif_zoneid != zoneid)
18909 				continue;	/* not this zone */
18910 			(void) ipif_get_name(ipif,
18911 			    ips.ipGroupSourceIfIndex.o_bytes,
18912 			    OCTET_LENGTH);
18913 			ips.ipGroupSourceIfIndex.o_length =
18914 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18915 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18916 				ASSERT(ilm->ilm_ipif != NULL);
18917 				ASSERT(ilm->ilm_ill == NULL);
18918 				sl = ilm->ilm_filter;
18919 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18920 					continue;
18921 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18922 				for (i = 0; i < sl->sl_numsrc; i++) {
18923 					if (!IN6_IS_ADDR_V4MAPPED(
18924 					    &sl->sl_addr[i]))
18925 						continue;
18926 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18927 					    ips.ipGroupSourceAddress);
18928 					if (snmp_append_data2(mpctl->b_cont,
18929 					    &mp_tail, (char *)&ips,
18930 					    (int)sizeof (ips)) == 0) {
18931 						ip1dbg(("ip_snmp_get_mib2_"
18932 						    "ip_group_src: failed to "
18933 						    "allocate %u bytes\n",
18934 						    (uint_t)sizeof (ips)));
18935 					}
18936 				}
18937 			}
18938 		}
18939 		ILM_WALKER_RELE(ill);
18940 	}
18941 	rw_exit(&ipst->ips_ill_g_lock);
18942 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18943 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18944 	    (int)optp->level, (int)optp->name, (int)optp->len));
18945 	qreply(q, mpctl);
18946 	return (mp2ctl);
18947 }
18948 
18949 /* IPv6 multicast filtered sources. */
18950 static mblk_t *
18951 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18952 {
18953 	struct opthdr		*optp;
18954 	mblk_t			*mp2ctl;
18955 	ill_t			*ill;
18956 	ilm_t			*ilm;
18957 	ipv6_grpsrc_t		ips6;
18958 	mblk_t			*mp_tail = NULL;
18959 	ill_walk_context_t	ctx;
18960 	zoneid_t		zoneid;
18961 	int			i;
18962 	slist_t			*sl;
18963 
18964 	/*
18965 	 * make a copy of the original message
18966 	 */
18967 	mp2ctl = copymsg(mpctl);
18968 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18969 
18970 	/* ip6GroupMember table */
18971 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18972 	optp->level = MIB2_IP6;
18973 	optp->name = EXPER_IP6_GROUP_SOURCES;
18974 
18975 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18976 	ill = ILL_START_WALK_V6(&ctx, ipst);
18977 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18978 		ILM_WALKER_HOLD(ill);
18979 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18980 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18981 			ASSERT(ilm->ilm_ipif == NULL);
18982 			ASSERT(ilm->ilm_ill != NULL);
18983 			sl = ilm->ilm_filter;
18984 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
18985 				continue;
18986 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
18987 			for (i = 0; i < sl->sl_numsrc; i++) {
18988 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
18989 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18990 				    (char *)&ips6, (int)sizeof (ips6))) {
18991 					ip1dbg(("ip_snmp_get_mib2_ip6_"
18992 					    "group_src: failed to allocate "
18993 					    "%u bytes\n",
18994 					    (uint_t)sizeof (ips6)));
18995 				}
18996 			}
18997 		}
18998 		ILM_WALKER_RELE(ill);
18999 	}
19000 	rw_exit(&ipst->ips_ill_g_lock);
19001 
19002 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19003 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19004 	    (int)optp->level, (int)optp->name, (int)optp->len));
19005 	qreply(q, mpctl);
19006 	return (mp2ctl);
19007 }
19008 
19009 /* Multicast routing virtual interface table. */
19010 static mblk_t *
19011 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19012 {
19013 	struct opthdr		*optp;
19014 	mblk_t			*mp2ctl;
19015 
19016 	/*
19017 	 * make a copy of the original message
19018 	 */
19019 	mp2ctl = copymsg(mpctl);
19020 
19021 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19022 	optp->level = EXPER_DVMRP;
19023 	optp->name = EXPER_DVMRP_VIF;
19024 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
19025 		ip0dbg(("ip_mroute_vif: failed\n"));
19026 	}
19027 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19028 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
19029 	    (int)optp->level, (int)optp->name, (int)optp->len));
19030 	qreply(q, mpctl);
19031 	return (mp2ctl);
19032 }
19033 
19034 /* Multicast routing table. */
19035 static mblk_t *
19036 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19037 {
19038 	struct opthdr		*optp;
19039 	mblk_t			*mp2ctl;
19040 
19041 	/*
19042 	 * make a copy of the original message
19043 	 */
19044 	mp2ctl = copymsg(mpctl);
19045 
19046 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19047 	optp->level = EXPER_DVMRP;
19048 	optp->name = EXPER_DVMRP_MRT;
19049 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
19050 		ip0dbg(("ip_mroute_mrt: failed\n"));
19051 	}
19052 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19053 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
19054 	    (int)optp->level, (int)optp->name, (int)optp->len));
19055 	qreply(q, mpctl);
19056 	return (mp2ctl);
19057 }
19058 
19059 /*
19060  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
19061  * in one IRE walk.
19062  */
19063 static mblk_t *
19064 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19065 {
19066 	struct opthdr	*optp;
19067 	mblk_t		*mp2ctl;	/* Returned */
19068 	mblk_t		*mp3ctl;	/* nettomedia */
19069 	mblk_t		*mp4ctl;	/* routeattrs */
19070 	iproutedata_t	ird;
19071 	zoneid_t	zoneid;
19072 
19073 	/*
19074 	 * make copies of the original message
19075 	 *	- mp2ctl is returned unchanged to the caller for his use
19076 	 *	- mpctl is sent upstream as ipRouteEntryTable
19077 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
19078 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
19079 	 */
19080 	mp2ctl = copymsg(mpctl);
19081 	mp3ctl = copymsg(mpctl);
19082 	mp4ctl = copymsg(mpctl);
19083 	if (mp3ctl == NULL || mp4ctl == NULL) {
19084 		freemsg(mp4ctl);
19085 		freemsg(mp3ctl);
19086 		freemsg(mp2ctl);
19087 		freemsg(mpctl);
19088 		return (NULL);
19089 	}
19090 
19091 	bzero(&ird, sizeof (ird));
19092 
19093 	ird.ird_route.lp_head = mpctl->b_cont;
19094 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19095 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19096 
19097 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19098 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
19099 	if (zoneid == GLOBAL_ZONEID) {
19100 		/*
19101 		 * Those IREs are used by Mobile-IP; since mipagent(1M)
19102 		 * requires the sys_net_config or sys_ip_config privilege,
19103 		 * it can only run in the global zone or an exclusive-IP zone,
19104 		 * and both those have a conn_zoneid == GLOBAL_ZONEID.
19105 		 */
19106 		ire_walk_srcif_table_v4(ip_snmp_get2_v4, &ird, ipst);
19107 		ire_walk_ill_mrtun(0, 0, ip_snmp_get2_v4, &ird, NULL, ipst);
19108 	}
19109 
19110 	/* ipRouteEntryTable in mpctl */
19111 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19112 	optp->level = MIB2_IP;
19113 	optp->name = MIB2_IP_ROUTE;
19114 	optp->len = msgdsize(ird.ird_route.lp_head);
19115 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19116 	    (int)optp->level, (int)optp->name, (int)optp->len));
19117 	qreply(q, mpctl);
19118 
19119 	/* ipNetToMediaEntryTable in mp3ctl */
19120 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19121 	optp->level = MIB2_IP;
19122 	optp->name = MIB2_IP_MEDIA;
19123 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19124 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19125 	    (int)optp->level, (int)optp->name, (int)optp->len));
19126 	qreply(q, mp3ctl);
19127 
19128 	/* ipRouteAttributeTable in mp4ctl */
19129 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19130 	optp->level = MIB2_IP;
19131 	optp->name = EXPER_IP_RTATTR;
19132 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19133 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19134 	    (int)optp->level, (int)optp->name, (int)optp->len));
19135 	if (optp->len == 0)
19136 		freemsg(mp4ctl);
19137 	else
19138 		qreply(q, mp4ctl);
19139 
19140 	return (mp2ctl);
19141 }
19142 
19143 /*
19144  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
19145  * ipv6NetToMediaEntryTable in an NDP walk.
19146  */
19147 static mblk_t *
19148 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19149 {
19150 	struct opthdr	*optp;
19151 	mblk_t		*mp2ctl;	/* Returned */
19152 	mblk_t		*mp3ctl;	/* nettomedia */
19153 	mblk_t		*mp4ctl;	/* routeattrs */
19154 	iproutedata_t	ird;
19155 	zoneid_t	zoneid;
19156 
19157 	/*
19158 	 * make copies of the original message
19159 	 *	- mp2ctl is returned unchanged to the caller for his use
19160 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
19161 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
19162 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
19163 	 */
19164 	mp2ctl = copymsg(mpctl);
19165 	mp3ctl = copymsg(mpctl);
19166 	mp4ctl = copymsg(mpctl);
19167 	if (mp3ctl == NULL || mp4ctl == NULL) {
19168 		freemsg(mp4ctl);
19169 		freemsg(mp3ctl);
19170 		freemsg(mp2ctl);
19171 		freemsg(mpctl);
19172 		return (NULL);
19173 	}
19174 
19175 	bzero(&ird, sizeof (ird));
19176 
19177 	ird.ird_route.lp_head = mpctl->b_cont;
19178 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19179 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19180 
19181 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19182 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
19183 
19184 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19185 	optp->level = MIB2_IP6;
19186 	optp->name = MIB2_IP6_ROUTE;
19187 	optp->len = msgdsize(ird.ird_route.lp_head);
19188 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19189 	    (int)optp->level, (int)optp->name, (int)optp->len));
19190 	qreply(q, mpctl);
19191 
19192 	/* ipv6NetToMediaEntryTable in mp3ctl */
19193 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
19194 
19195 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19196 	optp->level = MIB2_IP6;
19197 	optp->name = MIB2_IP6_MEDIA;
19198 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19199 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19200 	    (int)optp->level, (int)optp->name, (int)optp->len));
19201 	qreply(q, mp3ctl);
19202 
19203 	/* ipv6RouteAttributeTable in mp4ctl */
19204 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19205 	optp->level = MIB2_IP6;
19206 	optp->name = EXPER_IP_RTATTR;
19207 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19208 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19209 	    (int)optp->level, (int)optp->name, (int)optp->len));
19210 	if (optp->len == 0)
19211 		freemsg(mp4ctl);
19212 	else
19213 		qreply(q, mp4ctl);
19214 
19215 	return (mp2ctl);
19216 }
19217 
19218 /*
19219  * IPv6 mib: One per ill
19220  */
19221 static mblk_t *
19222 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19223 {
19224 	struct opthdr		*optp;
19225 	mblk_t			*mp2ctl;
19226 	ill_t			*ill;
19227 	ill_walk_context_t	ctx;
19228 	mblk_t			*mp_tail = NULL;
19229 
19230 	/*
19231 	 * Make a copy of the original message
19232 	 */
19233 	mp2ctl = copymsg(mpctl);
19234 
19235 	/* fixed length IPv6 structure ... */
19236 
19237 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19238 	optp->level = MIB2_IP6;
19239 	optp->name = 0;
19240 	/* Include "unknown interface" ip6_mib */
19241 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
19242 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
19243 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
19244 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
19245 	    ipst->ips_ipv6_forward ? 1 : 2);
19246 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
19247 	    ipst->ips_ipv6_def_hops);
19248 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
19249 	    sizeof (mib2_ipIfStatsEntry_t));
19250 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
19251 	    sizeof (mib2_ipv6AddrEntry_t));
19252 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
19253 	    sizeof (mib2_ipv6RouteEntry_t));
19254 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
19255 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19256 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
19257 	    sizeof (ipv6_member_t));
19258 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
19259 	    sizeof (ipv6_grpsrc_t));
19260 
19261 	/*
19262 	 * Synchronize 64- and 32-bit counters
19263 	 */
19264 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
19265 	    ipIfStatsHCInReceives);
19266 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
19267 	    ipIfStatsHCInDelivers);
19268 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
19269 	    ipIfStatsHCOutRequests);
19270 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
19271 	    ipIfStatsHCOutForwDatagrams);
19272 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
19273 	    ipIfStatsHCOutMcastPkts);
19274 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19275 	    ipIfStatsHCInMcastPkts);
19276 
19277 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19278 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19279 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19280 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19281 	}
19282 
19283 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19284 	ill = ILL_START_WALK_V6(&ctx, ipst);
19285 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19286 		ill->ill_ip_mib->ipIfStatsIfIndex =
19287 		    ill->ill_phyint->phyint_ifindex;
19288 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19289 		    ipst->ips_ipv6_forward ? 1 : 2);
19290 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19291 		    ill->ill_max_hops);
19292 
19293 		/*
19294 		 * Synchronize 64- and 32-bit counters
19295 		 */
19296 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19297 		    ipIfStatsHCInReceives);
19298 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19299 		    ipIfStatsHCInDelivers);
19300 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19301 		    ipIfStatsHCOutRequests);
19302 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19303 		    ipIfStatsHCOutForwDatagrams);
19304 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19305 		    ipIfStatsHCOutMcastPkts);
19306 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19307 		    ipIfStatsHCInMcastPkts);
19308 
19309 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19310 		    (char *)ill->ill_ip_mib,
19311 		    (int)sizeof (*ill->ill_ip_mib))) {
19312 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19313 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
19314 		}
19315 	}
19316 	rw_exit(&ipst->ips_ill_g_lock);
19317 
19318 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19319 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19320 	    (int)optp->level, (int)optp->name, (int)optp->len));
19321 	qreply(q, mpctl);
19322 	return (mp2ctl);
19323 }
19324 
19325 /*
19326  * ICMPv6 mib: One per ill
19327  */
19328 static mblk_t *
19329 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19330 {
19331 	struct opthdr		*optp;
19332 	mblk_t			*mp2ctl;
19333 	ill_t			*ill;
19334 	ill_walk_context_t	ctx;
19335 	mblk_t			*mp_tail = NULL;
19336 	/*
19337 	 * Make a copy of the original message
19338 	 */
19339 	mp2ctl = copymsg(mpctl);
19340 
19341 	/* fixed length ICMPv6 structure ... */
19342 
19343 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19344 	optp->level = MIB2_ICMP6;
19345 	optp->name = 0;
19346 	/* Include "unknown interface" icmp6_mib */
19347 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19348 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19349 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19350 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19351 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19352 	    (char *)&ipst->ips_icmp6_mib,
19353 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19354 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19355 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19356 	}
19357 
19358 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19359 	ill = ILL_START_WALK_V6(&ctx, ipst);
19360 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19361 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19362 		    ill->ill_phyint->phyint_ifindex;
19363 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19364 		    (char *)ill->ill_icmp6_mib,
19365 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19366 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19367 			    "%u bytes\n",
19368 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19369 		}
19370 	}
19371 	rw_exit(&ipst->ips_ill_g_lock);
19372 
19373 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19374 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19375 	    (int)optp->level, (int)optp->name, (int)optp->len));
19376 	qreply(q, mpctl);
19377 	return (mp2ctl);
19378 }
19379 
19380 /*
19381  * ire_walk routine to create both ipRouteEntryTable and
19382  * ipRouteAttributeTable in one IRE walk
19383  */
19384 static void
19385 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19386 {
19387 	ill_t				*ill;
19388 	ipif_t				*ipif;
19389 	mib2_ipRouteEntry_t		*re;
19390 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19391 	ipaddr_t			gw_addr;
19392 	tsol_ire_gw_secattr_t		*attrp;
19393 	tsol_gc_t			*gc = NULL;
19394 	tsol_gcgrp_t			*gcgrp = NULL;
19395 	uint_t				sacnt = 0;
19396 	int				i;
19397 
19398 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19399 
19400 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19401 		return;
19402 
19403 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19404 		mutex_enter(&attrp->igsa_lock);
19405 		if ((gc = attrp->igsa_gc) != NULL) {
19406 			gcgrp = gc->gc_grp;
19407 			ASSERT(gcgrp != NULL);
19408 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19409 			sacnt = 1;
19410 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19411 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19412 			gc = gcgrp->gcgrp_head;
19413 			sacnt = gcgrp->gcgrp_count;
19414 		}
19415 		mutex_exit(&attrp->igsa_lock);
19416 
19417 		/* do nothing if there's no gc to report */
19418 		if (gc == NULL) {
19419 			ASSERT(sacnt == 0);
19420 			if (gcgrp != NULL) {
19421 				/* we might as well drop the lock now */
19422 				rw_exit(&gcgrp->gcgrp_rwlock);
19423 				gcgrp = NULL;
19424 			}
19425 			attrp = NULL;
19426 		}
19427 
19428 		ASSERT(gc == NULL || (gcgrp != NULL &&
19429 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19430 	}
19431 	ASSERT(sacnt == 0 || gc != NULL);
19432 
19433 	if (sacnt != 0 &&
19434 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19435 		kmem_free(re, sizeof (*re));
19436 		rw_exit(&gcgrp->gcgrp_rwlock);
19437 		return;
19438 	}
19439 
19440 	/*
19441 	 * Return all IRE types for route table... let caller pick and choose
19442 	 */
19443 	re->ipRouteDest = ire->ire_addr;
19444 	ipif = ire->ire_ipif;
19445 	re->ipRouteIfIndex.o_length = 0;
19446 	if (ire->ire_type == IRE_CACHE) {
19447 		ill = (ill_t *)ire->ire_stq->q_ptr;
19448 		re->ipRouteIfIndex.o_length =
19449 		    ill->ill_name_length == 0 ? 0 :
19450 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19451 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19452 		    re->ipRouteIfIndex.o_length);
19453 	} else if (ipif != NULL) {
19454 		(void) ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes,
19455 		    OCTET_LENGTH);
19456 		re->ipRouteIfIndex.o_length =
19457 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19458 	}
19459 	re->ipRouteMetric1 = -1;
19460 	re->ipRouteMetric2 = -1;
19461 	re->ipRouteMetric3 = -1;
19462 	re->ipRouteMetric4 = -1;
19463 
19464 	gw_addr = ire->ire_gateway_addr;
19465 
19466 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19467 		re->ipRouteNextHop = ire->ire_src_addr;
19468 	else
19469 		re->ipRouteNextHop = gw_addr;
19470 	/* indirect(4), direct(3), or invalid(2) */
19471 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19472 		re->ipRouteType = 2;
19473 	else
19474 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19475 	re->ipRouteProto = -1;
19476 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19477 	re->ipRouteMask = ire->ire_mask;
19478 	re->ipRouteMetric5 = -1;
19479 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19480 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19481 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19482 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19483 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19484 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19485 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19486 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19487 	re->ipRouteInfo.re_in_ill.o_length = 0;
19488 
19489 	if (ire->ire_flags & RTF_DYNAMIC) {
19490 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19491 	} else {
19492 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19493 	}
19494 
19495 	if (ire->ire_in_ill != NULL) {
19496 		re->ipRouteInfo.re_in_ill.o_length =
19497 		    ire->ire_in_ill->ill_name_length == 0 ? 0 :
19498 		    MIN(OCTET_LENGTH, ire->ire_in_ill->ill_name_length - 1);
19499 		bcopy(ire->ire_in_ill->ill_name,
19500 		    re->ipRouteInfo.re_in_ill.o_bytes,
19501 		    re->ipRouteInfo.re_in_ill.o_length);
19502 	}
19503 	re->ipRouteInfo.re_in_src_addr = ire->ire_in_src_addr;
19504 
19505 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19506 	    (char *)re, (int)sizeof (*re))) {
19507 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19508 		    (uint_t)sizeof (*re)));
19509 	}
19510 
19511 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19512 		iaeptr->iae_routeidx = ird->ird_idx;
19513 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19514 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19515 	}
19516 
19517 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19518 	    (char *)iae, sacnt * sizeof (*iae))) {
19519 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19520 		    (unsigned)(sacnt * sizeof (*iae))));
19521 	}
19522 
19523 	/* bump route index for next pass */
19524 	ird->ird_idx++;
19525 
19526 	kmem_free(re, sizeof (*re));
19527 	if (sacnt != 0)
19528 		kmem_free(iae, sacnt * sizeof (*iae));
19529 
19530 	if (gcgrp != NULL)
19531 		rw_exit(&gcgrp->gcgrp_rwlock);
19532 }
19533 
19534 /*
19535  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19536  */
19537 static void
19538 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19539 {
19540 	ill_t				*ill;
19541 	ipif_t				*ipif;
19542 	mib2_ipv6RouteEntry_t		*re;
19543 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19544 	in6_addr_t			gw_addr_v6;
19545 	tsol_ire_gw_secattr_t		*attrp;
19546 	tsol_gc_t			*gc = NULL;
19547 	tsol_gcgrp_t			*gcgrp = NULL;
19548 	uint_t				sacnt = 0;
19549 	int				i;
19550 
19551 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19552 
19553 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19554 		return;
19555 
19556 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19557 		mutex_enter(&attrp->igsa_lock);
19558 		if ((gc = attrp->igsa_gc) != NULL) {
19559 			gcgrp = gc->gc_grp;
19560 			ASSERT(gcgrp != NULL);
19561 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19562 			sacnt = 1;
19563 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19564 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19565 			gc = gcgrp->gcgrp_head;
19566 			sacnt = gcgrp->gcgrp_count;
19567 		}
19568 		mutex_exit(&attrp->igsa_lock);
19569 
19570 		/* do nothing if there's no gc to report */
19571 		if (gc == NULL) {
19572 			ASSERT(sacnt == 0);
19573 			if (gcgrp != NULL) {
19574 				/* we might as well drop the lock now */
19575 				rw_exit(&gcgrp->gcgrp_rwlock);
19576 				gcgrp = NULL;
19577 			}
19578 			attrp = NULL;
19579 		}
19580 
19581 		ASSERT(gc == NULL || (gcgrp != NULL &&
19582 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19583 	}
19584 	ASSERT(sacnt == 0 || gc != NULL);
19585 
19586 	if (sacnt != 0 &&
19587 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19588 		kmem_free(re, sizeof (*re));
19589 		rw_exit(&gcgrp->gcgrp_rwlock);
19590 		return;
19591 	}
19592 
19593 	/*
19594 	 * Return all IRE types for route table... let caller pick and choose
19595 	 */
19596 	re->ipv6RouteDest = ire->ire_addr_v6;
19597 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19598 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19599 	re->ipv6RouteIfIndex.o_length = 0;
19600 	ipif = ire->ire_ipif;
19601 	if (ire->ire_type == IRE_CACHE) {
19602 		ill = (ill_t *)ire->ire_stq->q_ptr;
19603 		re->ipv6RouteIfIndex.o_length =
19604 		    ill->ill_name_length == 0 ? 0 :
19605 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19606 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19607 		    re->ipv6RouteIfIndex.o_length);
19608 	} else if (ipif != NULL) {
19609 		(void) ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes,
19610 		    OCTET_LENGTH);
19611 		re->ipv6RouteIfIndex.o_length =
19612 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19613 	}
19614 
19615 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19616 
19617 	mutex_enter(&ire->ire_lock);
19618 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19619 	mutex_exit(&ire->ire_lock);
19620 
19621 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19622 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19623 	else
19624 		re->ipv6RouteNextHop = gw_addr_v6;
19625 
19626 	/* remote(4), local(3), or discard(2) */
19627 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19628 		re->ipv6RouteType = 2;
19629 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19630 		re->ipv6RouteType = 3;
19631 	else
19632 		re->ipv6RouteType = 4;
19633 
19634 	re->ipv6RouteProtocol	= -1;
19635 	re->ipv6RoutePolicy	= 0;
19636 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19637 	re->ipv6RouteNextHopRDI	= 0;
19638 	re->ipv6RouteWeight	= 0;
19639 	re->ipv6RouteMetric	= 0;
19640 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19641 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19642 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19643 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19644 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19645 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19646 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19647 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19648 
19649 	if (ire->ire_flags & RTF_DYNAMIC) {
19650 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19651 	} else {
19652 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19653 	}
19654 
19655 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19656 	    (char *)re, (int)sizeof (*re))) {
19657 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19658 		    (uint_t)sizeof (*re)));
19659 	}
19660 
19661 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19662 		iaeptr->iae_routeidx = ird->ird_idx;
19663 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19664 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19665 	}
19666 
19667 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19668 	    (char *)iae, sacnt * sizeof (*iae))) {
19669 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19670 		    (unsigned)(sacnt * sizeof (*iae))));
19671 	}
19672 
19673 	/* bump route index for next pass */
19674 	ird->ird_idx++;
19675 
19676 	kmem_free(re, sizeof (*re));
19677 	if (sacnt != 0)
19678 		kmem_free(iae, sacnt * sizeof (*iae));
19679 
19680 	if (gcgrp != NULL)
19681 		rw_exit(&gcgrp->gcgrp_rwlock);
19682 }
19683 
19684 /*
19685  * ndp_walk routine to create ipv6NetToMediaEntryTable
19686  */
19687 static int
19688 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19689 {
19690 	ill_t				*ill;
19691 	mib2_ipv6NetToMediaEntry_t	ntme;
19692 	dl_unitdata_req_t		*dl;
19693 
19694 	ill = nce->nce_ill;
19695 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19696 		return (0);
19697 
19698 	/*
19699 	 * Neighbor cache entry attached to IRE with on-link
19700 	 * destination.
19701 	 */
19702 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19703 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19704 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19705 	    (nce->nce_res_mp != NULL)) {
19706 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19707 		ntme.ipv6NetToMediaPhysAddress.o_length =
19708 		    dl->dl_dest_addr_length;
19709 	} else {
19710 		ntme.ipv6NetToMediaPhysAddress.o_length =
19711 		    ill->ill_phys_addr_length;
19712 	}
19713 	if (nce->nce_res_mp != NULL) {
19714 		bcopy((char *)nce->nce_res_mp->b_rptr +
19715 		    NCE_LL_ADDR_OFFSET(ill),
19716 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19717 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19718 	} else {
19719 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19720 		    ill->ill_phys_addr_length);
19721 	}
19722 	/*
19723 	 * Note: Returns ND_* states. Should be:
19724 	 * reachable(1), stale(2), delay(3), probe(4),
19725 	 * invalid(5), unknown(6)
19726 	 */
19727 	ntme.ipv6NetToMediaState = nce->nce_state;
19728 	ntme.ipv6NetToMediaLastUpdated = 0;
19729 
19730 	/* other(1), dynamic(2), static(3), local(4) */
19731 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19732 		ntme.ipv6NetToMediaType = 4;
19733 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19734 		ntme.ipv6NetToMediaType = 1;
19735 	} else {
19736 		ntme.ipv6NetToMediaType = 2;
19737 	}
19738 
19739 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19740 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19741 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19742 		    (uint_t)sizeof (ntme)));
19743 	}
19744 	return (0);
19745 }
19746 
19747 /*
19748  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19749  */
19750 /* ARGSUSED */
19751 int
19752 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19753 {
19754 	switch (level) {
19755 	case MIB2_IP:
19756 	case MIB2_ICMP:
19757 		switch (name) {
19758 		default:
19759 			break;
19760 		}
19761 		return (1);
19762 	default:
19763 		return (1);
19764 	}
19765 }
19766 
19767 /*
19768  * When there exists both a 64- and 32-bit counter of a particular type
19769  * (i.e., InReceives), only the 64-bit counters are added.
19770  */
19771 void
19772 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19773 {
19774 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19775 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19776 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19777 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19778 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19779 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19780 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19781 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19782 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19783 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19784 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19785 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19786 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19787 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19788 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
19789 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
19790 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
19791 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
19792 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
19793 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
19794 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
19795 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
19796 	    o2->ipIfStatsInWrongIPVersion);
19797 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
19798 	    o2->ipIfStatsInWrongIPVersion);
19799 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
19800 	    o2->ipIfStatsOutSwitchIPVersion);
19801 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
19802 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
19803 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
19804 	    o2->ipIfStatsHCInForwDatagrams);
19805 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
19806 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
19807 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
19808 	    o2->ipIfStatsHCOutForwDatagrams);
19809 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
19810 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
19811 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
19812 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
19813 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
19814 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
19815 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
19816 	    o2->ipIfStatsHCOutMcastOctets);
19817 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
19818 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
19819 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
19820 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
19821 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
19822 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
19823 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
19824 }
19825 
19826 void
19827 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
19828 {
19829 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
19830 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
19831 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
19832 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
19833 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
19834 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
19835 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
19836 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
19837 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
19838 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
19839 	    o2->ipv6IfIcmpInRouterSolicits);
19840 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
19841 	    o2->ipv6IfIcmpInRouterAdvertisements);
19842 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
19843 	    o2->ipv6IfIcmpInNeighborSolicits);
19844 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
19845 	    o2->ipv6IfIcmpInNeighborAdvertisements);
19846 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
19847 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
19848 	    o2->ipv6IfIcmpInGroupMembQueries);
19849 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
19850 	    o2->ipv6IfIcmpInGroupMembResponses);
19851 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
19852 	    o2->ipv6IfIcmpInGroupMembReductions);
19853 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
19854 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
19855 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
19856 	    o2->ipv6IfIcmpOutDestUnreachs);
19857 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
19858 	    o2->ipv6IfIcmpOutAdminProhibs);
19859 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
19860 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
19861 	    o2->ipv6IfIcmpOutParmProblems);
19862 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
19863 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
19864 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
19865 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
19866 	    o2->ipv6IfIcmpOutRouterSolicits);
19867 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
19868 	    o2->ipv6IfIcmpOutRouterAdvertisements);
19869 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
19870 	    o2->ipv6IfIcmpOutNeighborSolicits);
19871 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
19872 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
19873 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
19874 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
19875 	    o2->ipv6IfIcmpOutGroupMembQueries);
19876 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
19877 	    o2->ipv6IfIcmpOutGroupMembResponses);
19878 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
19879 	    o2->ipv6IfIcmpOutGroupMembReductions);
19880 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
19881 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
19882 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
19883 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
19884 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
19885 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
19886 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
19887 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
19888 	    o2->ipv6IfIcmpInGroupMembTotal);
19889 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
19890 	    o2->ipv6IfIcmpInGroupMembBadQueries);
19891 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
19892 	    o2->ipv6IfIcmpInGroupMembBadReports);
19893 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
19894 	    o2->ipv6IfIcmpInGroupMembOurReports);
19895 }
19896 
19897 /*
19898  * Called before the options are updated to check if this packet will
19899  * be source routed from here.
19900  * This routine assumes that the options are well formed i.e. that they
19901  * have already been checked.
19902  */
19903 static boolean_t
19904 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
19905 {
19906 	ipoptp_t	opts;
19907 	uchar_t		*opt;
19908 	uint8_t		optval;
19909 	uint8_t		optlen;
19910 	ipaddr_t	dst;
19911 	ire_t		*ire;
19912 
19913 	if (IS_SIMPLE_IPH(ipha)) {
19914 		ip2dbg(("not source routed\n"));
19915 		return (B_FALSE);
19916 	}
19917 	dst = ipha->ipha_dst;
19918 	for (optval = ipoptp_first(&opts, ipha);
19919 	    optval != IPOPT_EOL;
19920 	    optval = ipoptp_next(&opts)) {
19921 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19922 		opt = opts.ipoptp_cur;
19923 		optlen = opts.ipoptp_len;
19924 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19925 		    optval, optlen));
19926 		switch (optval) {
19927 			uint32_t off;
19928 		case IPOPT_SSRR:
19929 		case IPOPT_LSRR:
19930 			/*
19931 			 * If dst is one of our addresses and there are some
19932 			 * entries left in the source route return (true).
19933 			 */
19934 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19935 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
19936 			if (ire == NULL) {
19937 				ip2dbg(("ip_source_routed: not next"
19938 				    " source route 0x%x\n",
19939 				    ntohl(dst)));
19940 				return (B_FALSE);
19941 			}
19942 			ire_refrele(ire);
19943 			off = opt[IPOPT_OFFSET];
19944 			off--;
19945 			if (optlen < IP_ADDR_LEN ||
19946 			    off > optlen - IP_ADDR_LEN) {
19947 				/* End of source route */
19948 				ip1dbg(("ip_source_routed: end of SR\n"));
19949 				return (B_FALSE);
19950 			}
19951 			return (B_TRUE);
19952 		}
19953 	}
19954 	ip2dbg(("not source routed\n"));
19955 	return (B_FALSE);
19956 }
19957 
19958 /*
19959  * Check if the packet contains any source route.
19960  */
19961 static boolean_t
19962 ip_source_route_included(ipha_t *ipha)
19963 {
19964 	ipoptp_t	opts;
19965 	uint8_t		optval;
19966 
19967 	if (IS_SIMPLE_IPH(ipha))
19968 		return (B_FALSE);
19969 	for (optval = ipoptp_first(&opts, ipha);
19970 	    optval != IPOPT_EOL;
19971 	    optval = ipoptp_next(&opts)) {
19972 		switch (optval) {
19973 		case IPOPT_SSRR:
19974 		case IPOPT_LSRR:
19975 			return (B_TRUE);
19976 		}
19977 	}
19978 	return (B_FALSE);
19979 }
19980 
19981 /*
19982  * Called when the IRE expiration timer fires.
19983  */
19984 void
19985 ip_trash_timer_expire(void *args)
19986 {
19987 	int			flush_flag = 0;
19988 	ire_expire_arg_t	iea;
19989 	ip_stack_t		*ipst = (ip_stack_t *)args;
19990 
19991 	iea.iea_ipst = ipst;	/* No netstack_hold */
19992 
19993 	/*
19994 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
19995 	 * This lock makes sure that a new invocation of this function
19996 	 * that occurs due to an almost immediate timer firing will not
19997 	 * progress beyond this point until the current invocation is done
19998 	 */
19999 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20000 	ipst->ips_ip_ire_expire_id = 0;
20001 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20002 
20003 	/* Periodic timer */
20004 	if (ipst->ips_ip_ire_arp_time_elapsed >=
20005 	    ipst->ips_ip_ire_arp_interval) {
20006 		/*
20007 		 * Remove all IRE_CACHE entries since they might
20008 		 * contain arp information.
20009 		 */
20010 		flush_flag |= FLUSH_ARP_TIME;
20011 		ipst->ips_ip_ire_arp_time_elapsed = 0;
20012 		IP_STAT(ipst, ip_ire_arp_timer_expired);
20013 	}
20014 	if (ipst->ips_ip_ire_rd_time_elapsed >=
20015 	    ipst->ips_ip_ire_redir_interval) {
20016 		/* Remove all redirects */
20017 		flush_flag |= FLUSH_REDIRECT_TIME;
20018 		ipst->ips_ip_ire_rd_time_elapsed = 0;
20019 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
20020 	}
20021 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
20022 	    ipst->ips_ip_ire_pathmtu_interval) {
20023 		/* Increase path mtu */
20024 		flush_flag |= FLUSH_MTU_TIME;
20025 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
20026 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
20027 	}
20028 
20029 	/*
20030 	 * Optimize for the case when there are no redirects in the
20031 	 * ftable, that is, no need to walk the ftable in that case.
20032 	 */
20033 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
20034 		iea.iea_flush_flag = flush_flag;
20035 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
20036 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
20037 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
20038 		    NULL, ALL_ZONES, ipst);
20039 	}
20040 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
20041 	    ipst->ips_ip_redirect_cnt > 0) {
20042 		iea.iea_flush_flag = flush_flag;
20043 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
20044 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
20045 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
20046 	}
20047 	if (flush_flag & FLUSH_MTU_TIME) {
20048 		/*
20049 		 * Walk all IPv6 IRE's and update them
20050 		 * Note that ARP and redirect timers are not
20051 		 * needed since NUD handles stale entries.
20052 		 */
20053 		flush_flag = FLUSH_MTU_TIME;
20054 		iea.iea_flush_flag = flush_flag;
20055 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
20056 		    ALL_ZONES, ipst);
20057 	}
20058 
20059 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
20060 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
20061 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
20062 
20063 	/*
20064 	 * Hold the lock to serialize timeout calls and prevent
20065 	 * stale values in ip_ire_expire_id. Otherwise it is possible
20066 	 * for the timer to fire and a new invocation of this function
20067 	 * to start before the return value of timeout has been stored
20068 	 * in ip_ire_expire_id by the current invocation.
20069 	 */
20070 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20071 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
20072 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
20073 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20074 }
20075 
20076 /*
20077  * Called by the memory allocator subsystem directly, when the system
20078  * is running low on memory.
20079  */
20080 /* ARGSUSED */
20081 void
20082 ip_trash_ire_reclaim(void *args)
20083 {
20084 	netstack_handle_t nh;
20085 	netstack_t *ns;
20086 
20087 	netstack_next_init(&nh);
20088 	while ((ns = netstack_next(&nh)) != NULL) {
20089 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
20090 		netstack_rele(ns);
20091 	}
20092 	netstack_next_fini(&nh);
20093 }
20094 
20095 static void
20096 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
20097 {
20098 	ire_cache_count_t icc;
20099 	ire_cache_reclaim_t icr;
20100 	ncc_cache_count_t ncc;
20101 	nce_cache_reclaim_t ncr;
20102 	uint_t delete_cnt;
20103 	/*
20104 	 * Memory reclaim call back.
20105 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
20106 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
20107 	 * entries, determine what fraction to free for
20108 	 * each category of IRE_CACHE entries giving absolute priority
20109 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
20110 	 * entry will be freed unless all offlink entries are freed).
20111 	 */
20112 	icc.icc_total = 0;
20113 	icc.icc_unused = 0;
20114 	icc.icc_offlink = 0;
20115 	icc.icc_pmtu = 0;
20116 	icc.icc_onlink = 0;
20117 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20118 
20119 	/*
20120 	 * Free NCEs for IPv6 like the onlink ires.
20121 	 */
20122 	ncc.ncc_total = 0;
20123 	ncc.ncc_host = 0;
20124 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
20125 
20126 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
20127 	    icc.icc_pmtu + icc.icc_onlink);
20128 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
20129 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
20130 	if (delete_cnt == 0)
20131 		return;
20132 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
20133 	/* Always delete all unused offlink entries */
20134 	icr.icr_ipst = ipst;
20135 	icr.icr_unused = 1;
20136 	if (delete_cnt <= icc.icc_unused) {
20137 		/*
20138 		 * Only need to free unused entries.  In other words,
20139 		 * there are enough unused entries to free to meet our
20140 		 * target number of freed ire cache entries.
20141 		 */
20142 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
20143 		ncr.ncr_host = 0;
20144 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
20145 		/*
20146 		 * Only need to free unused entries, plus a fraction of offlink
20147 		 * entries.  It follows from the first if statement that
20148 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
20149 		 */
20150 		delete_cnt -= icc.icc_unused;
20151 		/* Round up # deleted by truncating fraction */
20152 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
20153 		icr.icr_pmtu = icr.icr_onlink = 0;
20154 		ncr.ncr_host = 0;
20155 	} else if (delete_cnt <=
20156 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
20157 		/*
20158 		 * Free all unused and offlink entries, plus a fraction of
20159 		 * pmtu entries.  It follows from the previous if statement
20160 		 * that icc_pmtu is non-zero, and that
20161 		 * delete_cnt != icc_unused + icc_offlink.
20162 		 */
20163 		icr.icr_offlink = 1;
20164 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
20165 		/* Round up # deleted by truncating fraction */
20166 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
20167 		icr.icr_onlink = 0;
20168 		ncr.ncr_host = 0;
20169 	} else {
20170 		/*
20171 		 * Free all unused, offlink, and pmtu entries, plus a fraction
20172 		 * of onlink entries.  If we're here, then we know that
20173 		 * icc_onlink is non-zero, and that
20174 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
20175 		 */
20176 		icr.icr_offlink = icr.icr_pmtu = 1;
20177 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
20178 		    icc.icc_pmtu;
20179 		/* Round up # deleted by truncating fraction */
20180 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
20181 		/* Using the same delete fraction as for onlink IREs */
20182 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
20183 	}
20184 #ifdef DEBUG
20185 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
20186 	    "fractions %d/%d/%d/%d\n",
20187 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
20188 	    icc.icc_unused, icc.icc_offlink,
20189 	    icc.icc_pmtu, icc.icc_onlink,
20190 	    icr.icr_unused, icr.icr_offlink,
20191 	    icr.icr_pmtu, icr.icr_onlink));
20192 #endif
20193 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
20194 	if (ncr.ncr_host != 0)
20195 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
20196 		    (uchar_t *)&ncr, ipst);
20197 #ifdef DEBUG
20198 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
20199 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
20200 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20201 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
20202 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
20203 	    icc.icc_pmtu, icc.icc_onlink));
20204 #endif
20205 }
20206 
20207 /*
20208  * ip_unbind is called when a copy of an unbind request is received from the
20209  * upper level protocol.  We remove this conn from any fanout hash list it is
20210  * on, and zero out the bind information.  No reply is expected up above.
20211  */
20212 mblk_t *
20213 ip_unbind(queue_t *q, mblk_t *mp)
20214 {
20215 	conn_t	*connp = Q_TO_CONN(q);
20216 
20217 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
20218 
20219 	if (is_system_labeled() && connp->conn_anon_port) {
20220 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
20221 		    connp->conn_mlp_type, connp->conn_ulp,
20222 		    ntohs(connp->conn_lport), B_FALSE);
20223 		connp->conn_anon_port = 0;
20224 	}
20225 	connp->conn_mlp_type = mlptSingle;
20226 
20227 	ipcl_hash_remove(connp);
20228 
20229 	ASSERT(mp->b_cont == NULL);
20230 	/*
20231 	 * Convert mp into a T_OK_ACK
20232 	 */
20233 	mp = mi_tpi_ok_ack_alloc(mp);
20234 
20235 	/*
20236 	 * should not happen in practice... T_OK_ACK is smaller than the
20237 	 * original message.
20238 	 */
20239 	if (mp == NULL)
20240 		return (NULL);
20241 
20242 	/*
20243 	 * Don't bzero the ports if its TCP since TCP still needs the
20244 	 * lport to remove it from its own bind hash. TCP will do the
20245 	 * cleanup.
20246 	 */
20247 	if (!IPCL_IS_TCP(connp))
20248 		bzero(&connp->u_port, sizeof (connp->u_port));
20249 
20250 	return (mp);
20251 }
20252 
20253 /*
20254  * Write side put procedure.  Outbound data, IOCTLs, responses from
20255  * resolvers, etc, come down through here.
20256  *
20257  * arg2 is always a queue_t *.
20258  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
20259  * the zoneid.
20260  * When that queue is not an ill_t, then arg must be a conn_t pointer.
20261  */
20262 void
20263 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
20264 {
20265 	ip_output_options(arg, mp, arg2, caller, &zero_info);
20266 }
20267 
20268 void
20269 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20270     ip_opt_info_t *infop)
20271 {
20272 	conn_t		*connp = NULL;
20273 	queue_t		*q = (queue_t *)arg2;
20274 	ipha_t		*ipha;
20275 #define	rptr	((uchar_t *)ipha)
20276 	ire_t		*ire = NULL;
20277 	ire_t		*sctp_ire = NULL;
20278 	uint32_t	v_hlen_tos_len;
20279 	ipaddr_t	dst;
20280 	mblk_t		*first_mp = NULL;
20281 	boolean_t	mctl_present;
20282 	ipsec_out_t	*io;
20283 	int		match_flags;
20284 	ill_t		*attach_ill = NULL;
20285 					/* Bind to IPIF_NOFAILOVER ill etc. */
20286 	ill_t		*xmit_ill = NULL;	/* IP_XMIT_IF etc. */
20287 	ipif_t		*dst_ipif;
20288 	boolean_t	multirt_need_resolve = B_FALSE;
20289 	mblk_t		*copy_mp = NULL;
20290 	int		err;
20291 	zoneid_t	zoneid;
20292 	int	adjust;
20293 	uint16_t iplen;
20294 	boolean_t	need_decref = B_FALSE;
20295 	boolean_t	ignore_dontroute = B_FALSE;
20296 	boolean_t	ignore_nexthop = B_FALSE;
20297 	boolean_t	ip_nexthop = B_FALSE;
20298 	ipaddr_t	nexthop_addr;
20299 	ip_stack_t	*ipst;
20300 
20301 #ifdef	_BIG_ENDIAN
20302 #define	V_HLEN	(v_hlen_tos_len >> 24)
20303 #else
20304 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20305 #endif
20306 
20307 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20308 	    "ip_wput_start: q %p", q);
20309 
20310 	/*
20311 	 * ip_wput fast path
20312 	 */
20313 
20314 	/* is packet from ARP ? */
20315 	if (q->q_next != NULL) {
20316 		zoneid = (zoneid_t)(uintptr_t)arg;
20317 		goto qnext;
20318 	}
20319 
20320 	connp = (conn_t *)arg;
20321 	ASSERT(connp != NULL);
20322 	zoneid = connp->conn_zoneid;
20323 	ipst = connp->conn_netstack->netstack_ip;
20324 
20325 	/* is queue flow controlled? */
20326 	if ((q->q_first != NULL || connp->conn_draining) &&
20327 	    (caller == IP_WPUT)) {
20328 		ASSERT(!need_decref);
20329 		(void) putq(q, mp);
20330 		return;
20331 	}
20332 
20333 	/* Multidata transmit? */
20334 	if (DB_TYPE(mp) == M_MULTIDATA) {
20335 		/*
20336 		 * We should never get here, since all Multidata messages
20337 		 * originating from tcp should have been directed over to
20338 		 * tcp_multisend() in the first place.
20339 		 */
20340 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20341 		freemsg(mp);
20342 		return;
20343 	} else if (DB_TYPE(mp) != M_DATA)
20344 		goto notdata;
20345 
20346 	if (mp->b_flag & MSGHASREF) {
20347 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20348 		mp->b_flag &= ~MSGHASREF;
20349 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20350 		need_decref = B_TRUE;
20351 	}
20352 	ipha = (ipha_t *)mp->b_rptr;
20353 
20354 	/* is IP header non-aligned or mblk smaller than basic IP header */
20355 #ifndef SAFETY_BEFORE_SPEED
20356 	if (!OK_32PTR(rptr) ||
20357 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20358 		goto hdrtoosmall;
20359 #endif
20360 
20361 	ASSERT(OK_32PTR(ipha));
20362 
20363 	/*
20364 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20365 	 * wrong version, we'll catch it again in ip_output_v6.
20366 	 *
20367 	 * Note that this is *only* locally-generated output here, and never
20368 	 * forwarded data, and that we need to deal only with transports that
20369 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20370 	 * label.)
20371 	 */
20372 	if (is_system_labeled() &&
20373 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20374 	    !connp->conn_ulp_labeled) {
20375 		err = tsol_check_label(BEST_CRED(mp, connp), &mp, &adjust,
20376 		    connp->conn_mac_exempt, ipst);
20377 		ipha = (ipha_t *)mp->b_rptr;
20378 		if (err != 0) {
20379 			first_mp = mp;
20380 			if (err == EINVAL)
20381 				goto icmp_parameter_problem;
20382 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20383 			goto discard_pkt;
20384 		}
20385 		iplen = ntohs(ipha->ipha_length) + adjust;
20386 		ipha->ipha_length = htons(iplen);
20387 	}
20388 
20389 	ASSERT(infop != NULL);
20390 
20391 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20392 		/*
20393 		 * IP_PKTINFO ancillary option is present.
20394 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20395 		 * allows using address of any zone as the source address.
20396 		 */
20397 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20398 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20399 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20400 		if (ire == NULL)
20401 			goto drop_pkt;
20402 		ire_refrele(ire);
20403 		ire = NULL;
20404 	}
20405 
20406 	/*
20407 	 * IP_DONTFAILOVER_IF and IP_XMIT_IF have precedence over
20408 	 * ill index passed in IP_PKTINFO.
20409 	 */
20410 	if (infop->ip_opt_ill_index != 0 &&
20411 	    connp->conn_xmit_if_ill == NULL &&
20412 	    connp->conn_nofailover_ill == NULL) {
20413 
20414 		xmit_ill = ill_lookup_on_ifindex(
20415 		    infop->ip_opt_ill_index, B_FALSE, NULL, NULL, NULL, NULL,
20416 		    ipst);
20417 
20418 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20419 			goto drop_pkt;
20420 		/*
20421 		 * check that there is an ipif belonging
20422 		 * to our zone. IPCL_ZONEID is not used because
20423 		 * IP_ALLZONES option is valid only when the ill is
20424 		 * accessible from all zones i.e has a valid ipif in
20425 		 * all zones.
20426 		 */
20427 		if (!ipif_lookup_zoneid_group(xmit_ill, zoneid, 0, NULL)) {
20428 			goto drop_pkt;
20429 		}
20430 	}
20431 
20432 	/*
20433 	 * If there is a policy, try to attach an ipsec_out in
20434 	 * the front. At the end, first_mp either points to a
20435 	 * M_DATA message or IPSEC_OUT message linked to a
20436 	 * M_DATA message. We have to do it now as we might
20437 	 * lose the "conn" if we go through ip_newroute.
20438 	 */
20439 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20440 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
20441 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20442 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20443 			if (need_decref)
20444 				CONN_DEC_REF(connp);
20445 			return;
20446 		} else {
20447 			ASSERT(mp->b_datap->db_type == M_CTL);
20448 			first_mp = mp;
20449 			mp = mp->b_cont;
20450 			mctl_present = B_TRUE;
20451 		}
20452 	} else {
20453 		first_mp = mp;
20454 		mctl_present = B_FALSE;
20455 	}
20456 
20457 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20458 
20459 	/* is wrong version or IP options present */
20460 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20461 		goto version_hdrlen_check;
20462 	dst = ipha->ipha_dst;
20463 
20464 	if (connp->conn_nofailover_ill != NULL) {
20465 		attach_ill = conn_get_held_ill(connp,
20466 		    &connp->conn_nofailover_ill, &err);
20467 		if (err == ILL_LOOKUP_FAILED) {
20468 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20469 			if (need_decref)
20470 				CONN_DEC_REF(connp);
20471 			freemsg(first_mp);
20472 			return;
20473 		}
20474 	}
20475 
20476 
20477 	/* is packet multicast? */
20478 	if (CLASSD(dst))
20479 		goto multicast;
20480 
20481 	/*
20482 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20483 	 * takes precedence over conn_dontroute and conn_nexthop_set
20484 	 */
20485 	if (xmit_ill != NULL) {
20486 		goto send_from_ill;
20487 	}
20488 
20489 	if ((connp->conn_dontroute) || (connp->conn_xmit_if_ill != NULL) ||
20490 	    (connp->conn_nexthop_set)) {
20491 		/*
20492 		 * If the destination is a broadcast or a loopback
20493 		 * address, SO_DONTROUTE, IP_XMIT_IF and IP_NEXTHOP go
20494 		 * through the standard path. But in the case of local
20495 		 * destination only SO_DONTROUTE and IP_NEXTHOP go through
20496 		 * the standard path not IP_XMIT_IF.
20497 		 */
20498 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20499 		if ((ire == NULL) || ((ire->ire_type != IRE_BROADCAST) &&
20500 		    (ire->ire_type != IRE_LOOPBACK))) {
20501 			if ((connp->conn_dontroute ||
20502 			    connp->conn_nexthop_set) && (ire != NULL) &&
20503 			    (ire->ire_type == IRE_LOCAL))
20504 				goto standard_path;
20505 
20506 			if (ire != NULL) {
20507 				ire_refrele(ire);
20508 				/* No more access to ire */
20509 				ire = NULL;
20510 			}
20511 			/*
20512 			 * bypass routing checks and go directly to
20513 			 * interface.
20514 			 */
20515 			if (connp->conn_dontroute) {
20516 				goto dontroute;
20517 			} else if (connp->conn_nexthop_set) {
20518 				ip_nexthop = B_TRUE;
20519 				nexthop_addr = connp->conn_nexthop_v4;
20520 				goto send_from_ill;
20521 			}
20522 
20523 			/*
20524 			 * If IP_XMIT_IF socket option is set,
20525 			 * then we allow unicast and multicast
20526 			 * packets to go through the ill. It is
20527 			 * quite possible that the destination
20528 			 * is not in the ire cache table and we
20529 			 * do not want to go to ip_newroute()
20530 			 * instead we call ip_newroute_ipif.
20531 			 */
20532 			xmit_ill = conn_get_held_ill(connp,
20533 			    &connp->conn_xmit_if_ill, &err);
20534 			if (err == ILL_LOOKUP_FAILED) {
20535 				BUMP_MIB(&ipst->ips_ip_mib,
20536 				    ipIfStatsOutDiscards);
20537 				if (attach_ill != NULL)
20538 					ill_refrele(attach_ill);
20539 				if (need_decref)
20540 					CONN_DEC_REF(connp);
20541 				freemsg(first_mp);
20542 				return;
20543 			}
20544 			goto send_from_ill;
20545 		}
20546 standard_path:
20547 		/* Must be a broadcast, a loopback or a local ire */
20548 		if (ire != NULL) {
20549 			ire_refrele(ire);
20550 			/* No more access to ire */
20551 			ire = NULL;
20552 		}
20553 	}
20554 
20555 	if (attach_ill != NULL)
20556 		goto send_from_ill;
20557 
20558 	/*
20559 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20560 	 * this for the tcp global queue and listen end point
20561 	 * as it does not really have a real destination to
20562 	 * talk to.  This is also true for SCTP.
20563 	 */
20564 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20565 	    !connp->conn_fully_bound) {
20566 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20567 		if (ire == NULL)
20568 			goto noirefound;
20569 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20570 		    "ip_wput_end: q %p (%S)", q, "end");
20571 
20572 		/*
20573 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20574 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20575 		 */
20576 		if (ire->ire_flags & RTF_MULTIRT) {
20577 
20578 			/*
20579 			 * Force the TTL of multirouted packets if required.
20580 			 * The TTL of such packets is bounded by the
20581 			 * ip_multirt_ttl ndd variable.
20582 			 */
20583 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20584 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20585 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20586 				    "(was %d), dst 0x%08x\n",
20587 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20588 				    ntohl(ire->ire_addr)));
20589 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20590 			}
20591 			/*
20592 			 * We look at this point if there are pending
20593 			 * unresolved routes. ire_multirt_resolvable()
20594 			 * checks in O(n) that all IRE_OFFSUBNET ire
20595 			 * entries for the packet's destination and
20596 			 * flagged RTF_MULTIRT are currently resolved.
20597 			 * If some remain unresolved, we make a copy
20598 			 * of the current message. It will be used
20599 			 * to initiate additional route resolutions.
20600 			 */
20601 			multirt_need_resolve =
20602 			    ire_multirt_need_resolve(ire->ire_addr,
20603 			    MBLK_GETLABEL(first_mp), ipst);
20604 			ip2dbg(("ip_wput[TCP]: ire %p, "
20605 			    "multirt_need_resolve %d, first_mp %p\n",
20606 			    (void *)ire, multirt_need_resolve,
20607 			    (void *)first_mp));
20608 			if (multirt_need_resolve) {
20609 				copy_mp = copymsg(first_mp);
20610 				if (copy_mp != NULL) {
20611 					MULTIRT_DEBUG_TAG(copy_mp);
20612 				}
20613 			}
20614 		}
20615 
20616 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20617 
20618 		/*
20619 		 * Try to resolve another multiroute if
20620 		 * ire_multirt_need_resolve() deemed it necessary.
20621 		 */
20622 		if (copy_mp != NULL) {
20623 			ip_newroute(q, copy_mp, dst, NULL, connp, zoneid, ipst);
20624 		}
20625 		if (need_decref)
20626 			CONN_DEC_REF(connp);
20627 		return;
20628 	}
20629 
20630 	/*
20631 	 * Access to conn_ire_cache. (protected by conn_lock)
20632 	 *
20633 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20634 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20635 	 * send a packet or two with the IRE_CACHE that is going away.
20636 	 * Access to the ire requires an ire refhold on the ire prior to
20637 	 * its use since an interface unplumb thread may delete the cached
20638 	 * ire and release the refhold at any time.
20639 	 *
20640 	 * Caching an ire in the conn_ire_cache
20641 	 *
20642 	 * o Caching an ire pointer in the conn requires a strict check for
20643 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20644 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20645 	 * in the conn is done after making sure under the bucket lock that the
20646 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20647 	 * caching an ire after the unplumb thread has cleaned up the conn.
20648 	 * If the conn does not send a packet subsequently the unplumb thread
20649 	 * will be hanging waiting for the ire count to drop to zero.
20650 	 *
20651 	 * o We also need to atomically test for a null conn_ire_cache and
20652 	 * set the conn_ire_cache under the the protection of the conn_lock
20653 	 * to avoid races among concurrent threads trying to simultaneously
20654 	 * cache an ire in the conn_ire_cache.
20655 	 */
20656 	mutex_enter(&connp->conn_lock);
20657 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20658 
20659 	if (ire != NULL && ire->ire_addr == dst &&
20660 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20661 
20662 		IRE_REFHOLD(ire);
20663 		mutex_exit(&connp->conn_lock);
20664 
20665 	} else {
20666 		boolean_t cached = B_FALSE;
20667 		connp->conn_ire_cache = NULL;
20668 		mutex_exit(&connp->conn_lock);
20669 		/* Release the old ire */
20670 		if (ire != NULL && sctp_ire == NULL)
20671 			IRE_REFRELE_NOTR(ire);
20672 
20673 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20674 		if (ire == NULL)
20675 			goto noirefound;
20676 		IRE_REFHOLD_NOTR(ire);
20677 
20678 		mutex_enter(&connp->conn_lock);
20679 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20680 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20681 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20682 				if (connp->conn_ulp == IPPROTO_TCP)
20683 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20684 				connp->conn_ire_cache = ire;
20685 				cached = B_TRUE;
20686 			}
20687 			rw_exit(&ire->ire_bucket->irb_lock);
20688 		}
20689 		mutex_exit(&connp->conn_lock);
20690 
20691 		/*
20692 		 * We can continue to use the ire but since it was
20693 		 * not cached, we should drop the extra reference.
20694 		 */
20695 		if (!cached)
20696 			IRE_REFRELE_NOTR(ire);
20697 	}
20698 
20699 
20700 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20701 	    "ip_wput_end: q %p (%S)", q, "end");
20702 
20703 	/*
20704 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20705 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20706 	 */
20707 	if (ire->ire_flags & RTF_MULTIRT) {
20708 
20709 		/*
20710 		 * Force the TTL of multirouted packets if required.
20711 		 * The TTL of such packets is bounded by the
20712 		 * ip_multirt_ttl ndd variable.
20713 		 */
20714 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20715 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20716 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20717 			    "(was %d), dst 0x%08x\n",
20718 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20719 			    ntohl(ire->ire_addr)));
20720 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20721 		}
20722 
20723 		/*
20724 		 * At this point, we check to see if there are any pending
20725 		 * unresolved routes. ire_multirt_resolvable()
20726 		 * checks in O(n) that all IRE_OFFSUBNET ire
20727 		 * entries for the packet's destination and
20728 		 * flagged RTF_MULTIRT are currently resolved.
20729 		 * If some remain unresolved, we make a copy
20730 		 * of the current message. It will be used
20731 		 * to initiate additional route resolutions.
20732 		 */
20733 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20734 		    MBLK_GETLABEL(first_mp), ipst);
20735 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20736 		    "multirt_need_resolve %d, first_mp %p\n",
20737 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20738 		if (multirt_need_resolve) {
20739 			copy_mp = copymsg(first_mp);
20740 			if (copy_mp != NULL) {
20741 				MULTIRT_DEBUG_TAG(copy_mp);
20742 			}
20743 		}
20744 	}
20745 
20746 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20747 
20748 	/*
20749 	 * Try to resolve another multiroute if
20750 	 * ire_multirt_resolvable() deemed it necessary
20751 	 */
20752 	if (copy_mp != NULL) {
20753 		ip_newroute(q, copy_mp, dst, NULL, connp, zoneid, ipst);
20754 	}
20755 	if (need_decref)
20756 		CONN_DEC_REF(connp);
20757 	return;
20758 
20759 qnext:
20760 	/*
20761 	 * Upper Level Protocols pass down complete IP datagrams
20762 	 * as M_DATA messages.	Everything else is a sideshow.
20763 	 *
20764 	 * 1) We could be re-entering ip_wput because of ip_neworute
20765 	 *    in which case we could have a IPSEC_OUT message. We
20766 	 *    need to pass through ip_wput like other datagrams and
20767 	 *    hence cannot branch to ip_wput_nondata.
20768 	 *
20769 	 * 2) ARP, AH, ESP, and other clients who are on the module
20770 	 *    instance of IP stream, give us something to deal with.
20771 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20772 	 *
20773 	 * 3) ICMP replies also could come here.
20774 	 */
20775 	ipst = ILLQ_TO_IPST(q);
20776 
20777 	if (DB_TYPE(mp) != M_DATA) {
20778 notdata:
20779 		if (DB_TYPE(mp) == M_CTL) {
20780 			/*
20781 			 * M_CTL messages are used by ARP, AH and ESP to
20782 			 * communicate with IP. We deal with IPSEC_IN and
20783 			 * IPSEC_OUT here. ip_wput_nondata handles other
20784 			 * cases.
20785 			 */
20786 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20787 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20788 				first_mp = mp->b_cont;
20789 				first_mp->b_flag &= ~MSGHASREF;
20790 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20791 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20792 				CONN_DEC_REF(connp);
20793 				connp = NULL;
20794 			}
20795 			if (ii->ipsec_info_type == IPSEC_IN) {
20796 				/*
20797 				 * Either this message goes back to
20798 				 * IPSEC for further processing or to
20799 				 * ULP after policy checks.
20800 				 */
20801 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20802 				return;
20803 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20804 				io = (ipsec_out_t *)ii;
20805 				if (io->ipsec_out_proc_begin) {
20806 					/*
20807 					 * IPSEC processing has already started.
20808 					 * Complete it.
20809 					 * IPQoS notes: We don't care what is
20810 					 * in ipsec_out_ill_index since this
20811 					 * won't be processed for IPQoS policies
20812 					 * in ipsec_out_process.
20813 					 */
20814 					ipsec_out_process(q, mp, NULL,
20815 					    io->ipsec_out_ill_index);
20816 					return;
20817 				} else {
20818 					connp = (q->q_next != NULL) ?
20819 					    NULL : Q_TO_CONN(q);
20820 					first_mp = mp;
20821 					mp = mp->b_cont;
20822 					mctl_present = B_TRUE;
20823 				}
20824 				zoneid = io->ipsec_out_zoneid;
20825 				ASSERT(zoneid != ALL_ZONES);
20826 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20827 				/*
20828 				 * It's an IPsec control message requesting
20829 				 * an SADB update to be sent to the IPsec
20830 				 * hardware acceleration capable ills.
20831 				 */
20832 				ipsec_ctl_t *ipsec_ctl =
20833 				    (ipsec_ctl_t *)mp->b_rptr;
20834 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20835 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20836 				mblk_t *cmp = mp->b_cont;
20837 
20838 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20839 				ASSERT(cmp != NULL);
20840 
20841 				freeb(mp);
20842 				ill_ipsec_capab_send_all(satype, cmp, sa,
20843 				    ipst->ips_netstack);
20844 				return;
20845 			} else {
20846 				/*
20847 				 * This must be ARP or special TSOL signaling.
20848 				 */
20849 				ip_wput_nondata(NULL, q, mp, NULL);
20850 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20851 				    "ip_wput_end: q %p (%S)", q, "nondata");
20852 				return;
20853 			}
20854 		} else {
20855 			/*
20856 			 * This must be non-(ARP/AH/ESP) messages.
20857 			 */
20858 			ASSERT(!need_decref);
20859 			ip_wput_nondata(NULL, q, mp, NULL);
20860 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20861 			    "ip_wput_end: q %p (%S)", q, "nondata");
20862 			return;
20863 		}
20864 	} else {
20865 		first_mp = mp;
20866 		mctl_present = B_FALSE;
20867 	}
20868 
20869 	ASSERT(first_mp != NULL);
20870 	/*
20871 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
20872 	 * to make sure that this packet goes out on the same interface it
20873 	 * came in. We handle that here.
20874 	 */
20875 	if (mctl_present) {
20876 		uint_t ifindex;
20877 
20878 		io = (ipsec_out_t *)first_mp->b_rptr;
20879 		if (io->ipsec_out_attach_if ||
20880 		    io->ipsec_out_xmit_if ||
20881 		    io->ipsec_out_ip_nexthop) {
20882 			ill_t	*ill;
20883 
20884 			/*
20885 			 * We may have lost the conn context if we are
20886 			 * coming here from ip_newroute(). Copy the
20887 			 * nexthop information.
20888 			 */
20889 			if (io->ipsec_out_ip_nexthop) {
20890 				ip_nexthop = B_TRUE;
20891 				nexthop_addr = io->ipsec_out_nexthop_addr;
20892 
20893 				ipha = (ipha_t *)mp->b_rptr;
20894 				dst = ipha->ipha_dst;
20895 				goto send_from_ill;
20896 			} else {
20897 				ASSERT(io->ipsec_out_ill_index != 0);
20898 				ifindex = io->ipsec_out_ill_index;
20899 				ill = ill_lookup_on_ifindex(ifindex, B_FALSE,
20900 				    NULL, NULL, NULL, NULL, ipst);
20901 				/*
20902 				 * ipsec_out_xmit_if bit is used to tell
20903 				 * ip_wput to use the ill to send outgoing data
20904 				 * as we have no conn when data comes from ICMP
20905 				 * error msg routines. Currently this feature is
20906 				 * only used by ip_mrtun_forward routine.
20907 				 */
20908 				if (io->ipsec_out_xmit_if) {
20909 					xmit_ill = ill;
20910 					if (xmit_ill == NULL) {
20911 						ip1dbg(("ip_output:bad ifindex "
20912 						    "for xmit_ill %d\n",
20913 						    ifindex));
20914 						freemsg(first_mp);
20915 						BUMP_MIB(&ipst->ips_ip_mib,
20916 						    ipIfStatsOutDiscards);
20917 						ASSERT(!need_decref);
20918 						return;
20919 					}
20920 					/* Free up the ipsec_out_t mblk */
20921 					ASSERT(first_mp->b_cont == mp);
20922 					first_mp->b_cont = NULL;
20923 					freeb(first_mp);
20924 					/* Just send the IP header+ICMP+data */
20925 					first_mp = mp;
20926 					ipha = (ipha_t *)mp->b_rptr;
20927 					dst = ipha->ipha_dst;
20928 					goto send_from_ill;
20929 				} else {
20930 					attach_ill = ill;
20931 				}
20932 
20933 				if (attach_ill == NULL) {
20934 					ASSERT(xmit_ill == NULL);
20935 					ip1dbg(("ip_output: bad ifindex for "
20936 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
20937 					    ifindex));
20938 					freemsg(first_mp);
20939 					BUMP_MIB(&ipst->ips_ip_mib,
20940 					    ipIfStatsOutDiscards);
20941 					ASSERT(!need_decref);
20942 					return;
20943 				}
20944 			}
20945 		}
20946 	}
20947 
20948 	ASSERT(xmit_ill == NULL);
20949 
20950 	/* We have a complete IP datagram heading outbound. */
20951 	ipha = (ipha_t *)mp->b_rptr;
20952 
20953 #ifndef SPEED_BEFORE_SAFETY
20954 	/*
20955 	 * Make sure we have a full-word aligned message and that at least
20956 	 * a simple IP header is accessible in the first message.  If not,
20957 	 * try a pullup.
20958 	 */
20959 	if (!OK_32PTR(rptr) ||
20960 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
20961 hdrtoosmall:
20962 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20963 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20964 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20965 			if (first_mp == NULL)
20966 				first_mp = mp;
20967 			goto discard_pkt;
20968 		}
20969 
20970 		/* This function assumes that mp points to an IPv4 packet. */
20971 		if (is_system_labeled() && q->q_next == NULL &&
20972 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20973 		    !connp->conn_ulp_labeled) {
20974 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20975 			    &adjust, connp->conn_mac_exempt, ipst);
20976 			ipha = (ipha_t *)mp->b_rptr;
20977 			if (first_mp != NULL)
20978 				first_mp->b_cont = mp;
20979 			if (err != 0) {
20980 				if (first_mp == NULL)
20981 					first_mp = mp;
20982 				if (err == EINVAL)
20983 					goto icmp_parameter_problem;
20984 				ip2dbg(("ip_wput: label check failed (%d)\n",
20985 				    err));
20986 				goto discard_pkt;
20987 			}
20988 			iplen = ntohs(ipha->ipha_length) + adjust;
20989 			ipha->ipha_length = htons(iplen);
20990 		}
20991 
20992 		ipha = (ipha_t *)mp->b_rptr;
20993 		if (first_mp == NULL) {
20994 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
20995 			/*
20996 			 * If we got here because of "goto hdrtoosmall"
20997 			 * We need to attach a IPSEC_OUT.
20998 			 */
20999 			if (connp->conn_out_enforce_policy) {
21000 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
21001 				    NULL, ipha->ipha_protocol,
21002 				    ipst->ips_netstack)) == NULL)) {
21003 					BUMP_MIB(&ipst->ips_ip_mib,
21004 					    ipIfStatsOutDiscards);
21005 					if (need_decref)
21006 						CONN_DEC_REF(connp);
21007 					return;
21008 				} else {
21009 					ASSERT(mp->b_datap->db_type == M_CTL);
21010 					first_mp = mp;
21011 					mp = mp->b_cont;
21012 					mctl_present = B_TRUE;
21013 				}
21014 			} else {
21015 				first_mp = mp;
21016 				mctl_present = B_FALSE;
21017 			}
21018 		}
21019 	}
21020 #endif
21021 
21022 	/* Most of the code below is written for speed, not readability */
21023 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21024 
21025 	/*
21026 	 * If ip_newroute() fails, we're going to need a full
21027 	 * header for the icmp wraparound.
21028 	 */
21029 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
21030 		uint_t	v_hlen;
21031 version_hdrlen_check:
21032 		ASSERT(first_mp != NULL);
21033 		v_hlen = V_HLEN;
21034 		/*
21035 		 * siphon off IPv6 packets coming down from transport
21036 		 * layer modules here.
21037 		 * Note: high-order bit carries NUD reachability confirmation
21038 		 */
21039 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
21040 			/*
21041 			 * XXX implement a IPv4 and IPv6 packet counter per
21042 			 * conn and switch when ratio exceeds e.g. 10:1
21043 			 */
21044 #ifdef notyet
21045 			if (q->q_next == NULL) /* Avoid ill queue */
21046 				ip_setqinfo(RD(q), B_TRUE, B_TRUE, ipst);
21047 #endif
21048 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
21049 			ASSERT(xmit_ill == NULL);
21050 			if (attach_ill != NULL)
21051 				ill_refrele(attach_ill);
21052 			if (need_decref)
21053 				mp->b_flag |= MSGHASREF;
21054 			(void) ip_output_v6(arg, first_mp, arg2, caller);
21055 			return;
21056 		}
21057 
21058 		if ((v_hlen >> 4) != IP_VERSION) {
21059 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21060 			    "ip_wput_end: q %p (%S)", q, "badvers");
21061 			goto discard_pkt;
21062 		}
21063 		/*
21064 		 * Is the header length at least 20 bytes?
21065 		 *
21066 		 * Are there enough bytes accessible in the header?  If
21067 		 * not, try a pullup.
21068 		 */
21069 		v_hlen &= 0xF;
21070 		v_hlen <<= 2;
21071 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
21072 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21073 			    "ip_wput_end: q %p (%S)", q, "badlen");
21074 			goto discard_pkt;
21075 		}
21076 		if (v_hlen > (mp->b_wptr - rptr)) {
21077 			if (!pullupmsg(mp, v_hlen)) {
21078 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21079 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
21080 				goto discard_pkt;
21081 			}
21082 			ipha = (ipha_t *)mp->b_rptr;
21083 		}
21084 		/*
21085 		 * Move first entry from any source route into ipha_dst and
21086 		 * verify the options
21087 		 */
21088 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
21089 		    zoneid, ipst)) {
21090 			ASSERT(xmit_ill == NULL);
21091 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21092 			if (attach_ill != NULL)
21093 				ill_refrele(attach_ill);
21094 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21095 			    "ip_wput_end: q %p (%S)", q, "badopts");
21096 			if (need_decref)
21097 				CONN_DEC_REF(connp);
21098 			return;
21099 		}
21100 	}
21101 	dst = ipha->ipha_dst;
21102 
21103 	/*
21104 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
21105 	 * we have to run the packet through ip_newroute which will take
21106 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
21107 	 * a resolver, or assigning a default gateway, etc.
21108 	 */
21109 	if (CLASSD(dst)) {
21110 		ipif_t	*ipif;
21111 		uint32_t setsrc = 0;
21112 
21113 multicast:
21114 		ASSERT(first_mp != NULL);
21115 		ip2dbg(("ip_wput: CLASSD\n"));
21116 		if (connp == NULL) {
21117 			/*
21118 			 * Use the first good ipif on the ill.
21119 			 * XXX Should this ever happen? (Appears
21120 			 * to show up with just ppp and no ethernet due
21121 			 * to in.rdisc.)
21122 			 * However, ire_send should be able to
21123 			 * call ip_wput_ire directly.
21124 			 *
21125 			 * XXX Also, this can happen for ICMP and other packets
21126 			 * with multicast source addresses.  Perhaps we should
21127 			 * fix things so that we drop the packet in question,
21128 			 * but for now, just run with it.
21129 			 */
21130 			ill_t *ill = (ill_t *)q->q_ptr;
21131 
21132 			/*
21133 			 * Don't honor attach_if for this case. If ill
21134 			 * is part of the group, ipif could belong to
21135 			 * any ill and we cannot maintain attach_ill
21136 			 * and ipif_ill same anymore and the assert
21137 			 * below would fail.
21138 			 */
21139 			if (mctl_present && io->ipsec_out_attach_if) {
21140 				io->ipsec_out_ill_index = 0;
21141 				io->ipsec_out_attach_if = B_FALSE;
21142 				ASSERT(attach_ill != NULL);
21143 				ill_refrele(attach_ill);
21144 				attach_ill = NULL;
21145 			}
21146 
21147 			ASSERT(attach_ill == NULL);
21148 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
21149 			if (ipif == NULL) {
21150 				if (need_decref)
21151 					CONN_DEC_REF(connp);
21152 				freemsg(first_mp);
21153 				return;
21154 			}
21155 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
21156 			    ntohl(dst), ill->ill_name));
21157 		} else {
21158 			/*
21159 			 * The order of precedence is IP_XMIT_IF, IP_PKTINFO
21160 			 * and IP_MULTICAST_IF.
21161 			 * Block comment above this function explains the
21162 			 * locking mechanism used here
21163 			 */
21164 			if (xmit_ill == NULL) {
21165 				xmit_ill = conn_get_held_ill(connp,
21166 				    &connp->conn_xmit_if_ill, &err);
21167 				if (err == ILL_LOOKUP_FAILED) {
21168 					ip1dbg(("ip_wput: No ill for "
21169 					    "IP_XMIT_IF\n"));
21170 					BUMP_MIB(&ipst->ips_ip_mib,
21171 					    ipIfStatsOutNoRoutes);
21172 					goto drop_pkt;
21173 				}
21174 			}
21175 
21176 			if (xmit_ill == NULL) {
21177 				ipif = conn_get_held_ipif(connp,
21178 				    &connp->conn_multicast_ipif, &err);
21179 				if (err == IPIF_LOOKUP_FAILED) {
21180 					ip1dbg(("ip_wput: No ipif for "
21181 					    "multicast\n"));
21182 					BUMP_MIB(&ipst->ips_ip_mib,
21183 					    ipIfStatsOutNoRoutes);
21184 					goto drop_pkt;
21185 				}
21186 			}
21187 			if (xmit_ill != NULL) {
21188 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21189 				if (ipif == NULL) {
21190 					ip1dbg(("ip_wput: No ipif for "
21191 					    "IP_XMIT_IF\n"));
21192 					BUMP_MIB(&ipst->ips_ip_mib,
21193 					    ipIfStatsOutNoRoutes);
21194 					goto drop_pkt;
21195 				}
21196 			} else if (ipif == NULL || ipif->ipif_isv6) {
21197 				/*
21198 				 * We must do this ipif determination here
21199 				 * else we could pass through ip_newroute
21200 				 * and come back here without the conn context.
21201 				 *
21202 				 * Note: we do late binding i.e. we bind to
21203 				 * the interface when the first packet is sent.
21204 				 * For performance reasons we do not rebind on
21205 				 * each packet but keep the binding until the
21206 				 * next IP_MULTICAST_IF option.
21207 				 *
21208 				 * conn_multicast_{ipif,ill} are shared between
21209 				 * IPv4 and IPv6 and AF_INET6 sockets can
21210 				 * send both IPv4 and IPv6 packets. Hence
21211 				 * we have to check that "isv6" matches above.
21212 				 */
21213 				if (ipif != NULL)
21214 					ipif_refrele(ipif);
21215 				ipif = ipif_lookup_group(dst, zoneid, ipst);
21216 				if (ipif == NULL) {
21217 					ip1dbg(("ip_wput: No ipif for "
21218 					    "multicast\n"));
21219 					BUMP_MIB(&ipst->ips_ip_mib,
21220 					    ipIfStatsOutNoRoutes);
21221 					goto drop_pkt;
21222 				}
21223 				err = conn_set_held_ipif(connp,
21224 				    &connp->conn_multicast_ipif, ipif);
21225 				if (err == IPIF_LOOKUP_FAILED) {
21226 					ipif_refrele(ipif);
21227 					ip1dbg(("ip_wput: No ipif for "
21228 					    "multicast\n"));
21229 					BUMP_MIB(&ipst->ips_ip_mib,
21230 					    ipIfStatsOutNoRoutes);
21231 					goto drop_pkt;
21232 				}
21233 			}
21234 		}
21235 		ASSERT(!ipif->ipif_isv6);
21236 		/*
21237 		 * As we may lose the conn by the time we reach ip_wput_ire,
21238 		 * we copy conn_multicast_loop and conn_dontroute on to an
21239 		 * ipsec_out. In case if this datagram goes out secure,
21240 		 * we need the ill_index also. Copy that also into the
21241 		 * ipsec_out.
21242 		 */
21243 		if (mctl_present) {
21244 			io = (ipsec_out_t *)first_mp->b_rptr;
21245 			ASSERT(first_mp->b_datap->db_type == M_CTL);
21246 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
21247 		} else {
21248 			ASSERT(mp == first_mp);
21249 			if ((first_mp = allocb(sizeof (ipsec_info_t),
21250 			    BPRI_HI)) == NULL) {
21251 				ipif_refrele(ipif);
21252 				first_mp = mp;
21253 				goto discard_pkt;
21254 			}
21255 			first_mp->b_datap->db_type = M_CTL;
21256 			first_mp->b_wptr += sizeof (ipsec_info_t);
21257 			/* ipsec_out_secure is B_FALSE now */
21258 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
21259 			io = (ipsec_out_t *)first_mp->b_rptr;
21260 			io->ipsec_out_type = IPSEC_OUT;
21261 			io->ipsec_out_len = sizeof (ipsec_out_t);
21262 			io->ipsec_out_use_global_policy = B_TRUE;
21263 			io->ipsec_out_ns = ipst->ips_netstack;
21264 			first_mp->b_cont = mp;
21265 			mctl_present = B_TRUE;
21266 		}
21267 		if (attach_ill != NULL) {
21268 			ASSERT(attach_ill == ipif->ipif_ill);
21269 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21270 
21271 			/*
21272 			 * Check if we need an ire that will not be
21273 			 * looked up by anybody else i.e. HIDDEN.
21274 			 */
21275 			if (ill_is_probeonly(attach_ill)) {
21276 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21277 			}
21278 			io->ipsec_out_ill_index =
21279 			    attach_ill->ill_phyint->phyint_ifindex;
21280 			io->ipsec_out_attach_if = B_TRUE;
21281 		} else {
21282 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
21283 			io->ipsec_out_ill_index =
21284 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
21285 		}
21286 		if (connp != NULL) {
21287 			io->ipsec_out_multicast_loop =
21288 			    connp->conn_multicast_loop;
21289 			io->ipsec_out_dontroute = connp->conn_dontroute;
21290 			io->ipsec_out_zoneid = connp->conn_zoneid;
21291 		}
21292 		/*
21293 		 * If the application uses IP_MULTICAST_IF with
21294 		 * different logical addresses of the same ILL, we
21295 		 * need to make sure that the soruce address of
21296 		 * the packet matches the logical IP address used
21297 		 * in the option. We do it by initializing ipha_src
21298 		 * here. This should keep IPSEC also happy as
21299 		 * when we return from IPSEC processing, we don't
21300 		 * have to worry about getting the right address on
21301 		 * the packet. Thus it is sufficient to look for
21302 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
21303 		 * MATCH_IRE_IPIF.
21304 		 *
21305 		 * NOTE : We need to do it for non-secure case also as
21306 		 * this might go out secure if there is a global policy
21307 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
21308 		 * address, the source should be initialized already and
21309 		 * hence we won't be initializing here.
21310 		 *
21311 		 * As we do not have the ire yet, it is possible that
21312 		 * we set the source address here and then later discover
21313 		 * that the ire implies the source address to be assigned
21314 		 * through the RTF_SETSRC flag.
21315 		 * In that case, the setsrc variable will remind us
21316 		 * that overwritting the source address by the one
21317 		 * of the RTF_SETSRC-flagged ire is allowed.
21318 		 */
21319 		if (ipha->ipha_src == INADDR_ANY &&
21320 		    (connp == NULL || !connp->conn_unspec_src)) {
21321 			ipha->ipha_src = ipif->ipif_src_addr;
21322 			setsrc = RTF_SETSRC;
21323 		}
21324 		/*
21325 		 * Find an IRE which matches the destination and the outgoing
21326 		 * queue (i.e. the outgoing interface.)
21327 		 * For loopback use a unicast IP address for
21328 		 * the ire lookup.
21329 		 */
21330 		if (IS_LOOPBACK(ipif->ipif_ill))
21331 			dst = ipif->ipif_lcl_addr;
21332 
21333 		/*
21334 		 * If IP_XMIT_IF is set, we branch out to ip_newroute_ipif.
21335 		 * We don't need to lookup ire in ctable as the packet
21336 		 * needs to be sent to the destination through the specified
21337 		 * ill irrespective of ires in the cache table.
21338 		 */
21339 		ire = NULL;
21340 		if (xmit_ill == NULL) {
21341 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21342 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21343 		}
21344 
21345 		/*
21346 		 * refrele attach_ill as its not needed anymore.
21347 		 */
21348 		if (attach_ill != NULL) {
21349 			ill_refrele(attach_ill);
21350 			attach_ill = NULL;
21351 		}
21352 
21353 		if (ire == NULL) {
21354 			/*
21355 			 * Multicast loopback and multicast forwarding is
21356 			 * done in ip_wput_ire.
21357 			 *
21358 			 * Mark this packet to make it be delivered to
21359 			 * ip_wput_ire after the new ire has been
21360 			 * created.
21361 			 *
21362 			 * The call to ip_newroute_ipif takes into account
21363 			 * the setsrc reminder. In any case, we take care
21364 			 * of the RTF_MULTIRT flag.
21365 			 */
21366 			mp->b_prev = mp->b_next = NULL;
21367 			if (xmit_ill == NULL ||
21368 			    xmit_ill->ill_ipif_up_count > 0) {
21369 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21370 				    setsrc | RTF_MULTIRT, zoneid, infop);
21371 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21372 				    "ip_wput_end: q %p (%S)", q, "noire");
21373 			} else {
21374 				freemsg(first_mp);
21375 			}
21376 			ipif_refrele(ipif);
21377 			if (xmit_ill != NULL)
21378 				ill_refrele(xmit_ill);
21379 			if (need_decref)
21380 				CONN_DEC_REF(connp);
21381 			return;
21382 		}
21383 
21384 		ipif_refrele(ipif);
21385 		ipif = NULL;
21386 		ASSERT(xmit_ill == NULL);
21387 
21388 		/*
21389 		 * Honor the RTF_SETSRC flag for multicast packets,
21390 		 * if allowed by the setsrc reminder.
21391 		 */
21392 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21393 			ipha->ipha_src = ire->ire_src_addr;
21394 		}
21395 
21396 		/*
21397 		 * Unconditionally force the TTL to 1 for
21398 		 * multirouted multicast packets:
21399 		 * multirouted multicast should not cross
21400 		 * multicast routers.
21401 		 */
21402 		if (ire->ire_flags & RTF_MULTIRT) {
21403 			if (ipha->ipha_ttl > 1) {
21404 				ip2dbg(("ip_wput: forcing multicast "
21405 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21406 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21407 				ipha->ipha_ttl = 1;
21408 			}
21409 		}
21410 	} else {
21411 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
21412 		if ((ire != NULL) && (ire->ire_type &
21413 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21414 			ignore_dontroute = B_TRUE;
21415 			ignore_nexthop = B_TRUE;
21416 		}
21417 		if (ire != NULL) {
21418 			ire_refrele(ire);
21419 			ire = NULL;
21420 		}
21421 		/*
21422 		 * Guard against coming in from arp in which case conn is NULL.
21423 		 * Also guard against non M_DATA with dontroute set but
21424 		 * destined to local, loopback or broadcast addresses.
21425 		 */
21426 		if (connp != NULL && connp->conn_dontroute &&
21427 		    !ignore_dontroute) {
21428 dontroute:
21429 			/*
21430 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21431 			 * routing protocols from seeing false direct
21432 			 * connectivity.
21433 			 */
21434 			ipha->ipha_ttl = 1;
21435 			/*
21436 			 * If IP_XMIT_IF is also set (conn_xmit_if_ill != NULL)
21437 			 * along with SO_DONTROUTE, higher precedence is
21438 			 * given to IP_XMIT_IF and the IP_XMIT_IF ipif is used.
21439 			 */
21440 			if (connp->conn_xmit_if_ill == NULL) {
21441 				/* If suitable ipif not found, drop packet */
21442 				dst_ipif = ipif_lookup_onlink_addr(dst, zoneid,
21443 				    ipst);
21444 				if (dst_ipif == NULL) {
21445 					ip1dbg(("ip_wput: no route for "
21446 					    "dst using SO_DONTROUTE\n"));
21447 					BUMP_MIB(&ipst->ips_ip_mib,
21448 					    ipIfStatsOutNoRoutes);
21449 					mp->b_prev = mp->b_next = NULL;
21450 					if (first_mp == NULL)
21451 						first_mp = mp;
21452 					goto drop_pkt;
21453 				} else {
21454 					/*
21455 					 * If suitable ipif has been found, set
21456 					 * xmit_ill to the corresponding
21457 					 * ipif_ill because we'll be following
21458 					 * the IP_XMIT_IF logic.
21459 					 */
21460 					ASSERT(xmit_ill == NULL);
21461 					xmit_ill = dst_ipif->ipif_ill;
21462 					mutex_enter(&xmit_ill->ill_lock);
21463 					if (!ILL_CAN_LOOKUP(xmit_ill)) {
21464 						mutex_exit(&xmit_ill->ill_lock);
21465 						xmit_ill = NULL;
21466 						ipif_refrele(dst_ipif);
21467 						ip1dbg(("ip_wput: no route for"
21468 						    " dst using"
21469 						    " SO_DONTROUTE\n"));
21470 						BUMP_MIB(&ipst->ips_ip_mib,
21471 						    ipIfStatsOutNoRoutes);
21472 						mp->b_prev = mp->b_next = NULL;
21473 						if (first_mp == NULL)
21474 							first_mp = mp;
21475 						goto drop_pkt;
21476 					}
21477 					ill_refhold_locked(xmit_ill);
21478 					mutex_exit(&xmit_ill->ill_lock);
21479 					ipif_refrele(dst_ipif);
21480 				}
21481 			}
21482 
21483 		}
21484 		/*
21485 		 * If we are bound to IPIF_NOFAILOVER address, look for
21486 		 * an IRE_CACHE matching the ill.
21487 		 */
21488 send_from_ill:
21489 		if (attach_ill != NULL) {
21490 			ipif_t	*attach_ipif;
21491 
21492 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21493 
21494 			/*
21495 			 * Check if we need an ire that will not be
21496 			 * looked up by anybody else i.e. HIDDEN.
21497 			 */
21498 			if (ill_is_probeonly(attach_ill)) {
21499 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21500 			}
21501 
21502 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
21503 			if (attach_ipif == NULL) {
21504 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
21505 				goto discard_pkt;
21506 			}
21507 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
21508 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21509 			ipif_refrele(attach_ipif);
21510 		} else if (xmit_ill != NULL || (connp != NULL &&
21511 		    connp->conn_xmit_if_ill != NULL)) {
21512 			/*
21513 			 * Mark this packet as originated locally
21514 			 */
21515 			mp->b_prev = mp->b_next = NULL;
21516 			/*
21517 			 * xmit_ill could be NULL if SO_DONTROUTE
21518 			 * is also set.
21519 			 */
21520 			if (xmit_ill == NULL) {
21521 				xmit_ill = conn_get_held_ill(connp,
21522 				    &connp->conn_xmit_if_ill, &err);
21523 				if (err == ILL_LOOKUP_FAILED) {
21524 					BUMP_MIB(&ipst->ips_ip_mib,
21525 					    ipIfStatsOutDiscards);
21526 					if (need_decref)
21527 						CONN_DEC_REF(connp);
21528 					freemsg(first_mp);
21529 					return;
21530 				}
21531 				if (xmit_ill == NULL) {
21532 					if (connp->conn_dontroute)
21533 						goto dontroute;
21534 					goto send_from_ill;
21535 				}
21536 			}
21537 			/*
21538 			 * Could be SO_DONTROUTE case also.
21539 			 * check at least one interface is UP as
21540 			 * specified by this ILL
21541 			 */
21542 			if (xmit_ill->ill_ipif_up_count > 0) {
21543 				ipif_t *ipif;
21544 
21545 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21546 				if (ipif == NULL) {
21547 					ip1dbg(("ip_output: "
21548 					    "xmit_ill NULL ipif\n"));
21549 					goto drop_pkt;
21550 				}
21551 				/*
21552 				 * Look for a ire that is part of the group,
21553 				 * if found use it else call ip_newroute_ipif.
21554 				 * IPCL_ZONEID is not used for matching because
21555 				 * IP_ALLZONES option is valid only when the
21556 				 * ill is accessible from all zones i.e has a
21557 				 * valid ipif in all zones.
21558 				 */
21559 				match_flags = MATCH_IRE_ILL_GROUP |
21560 				    MATCH_IRE_SECATTR;
21561 				ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21562 				    MBLK_GETLABEL(mp), match_flags, ipst);
21563 				/*
21564 				 * If an ire exists use it or else create
21565 				 * an ire but don't add it to the cache.
21566 				 * Adding an ire may cause issues with
21567 				 * asymmetric routing.
21568 				 * In case of multiroute always act as if
21569 				 * ire does not exist.
21570 				 */
21571 				if (ire == NULL ||
21572 				    ire->ire_flags & RTF_MULTIRT) {
21573 					if (ire != NULL)
21574 						ire_refrele(ire);
21575 					ip_newroute_ipif(q, first_mp, ipif,
21576 					    dst, connp, 0, zoneid, infop);
21577 					ipif_refrele(ipif);
21578 					ip1dbg(("ip_wput: ip_unicast_if\n"));
21579 					ill_refrele(xmit_ill);
21580 					if (need_decref)
21581 						CONN_DEC_REF(connp);
21582 					return;
21583 				}
21584 				ipif_refrele(ipif);
21585 			} else {
21586 				goto drop_pkt;
21587 			}
21588 		} else if (ip_nexthop || (connp != NULL &&
21589 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21590 			if (!ip_nexthop) {
21591 				ip_nexthop = B_TRUE;
21592 				nexthop_addr = connp->conn_nexthop_v4;
21593 			}
21594 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21595 			    MATCH_IRE_GW;
21596 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21597 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21598 		} else {
21599 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp),
21600 			    ipst);
21601 		}
21602 		if (!ire) {
21603 			/*
21604 			 * Make sure we don't load spread if this
21605 			 * is IPIF_NOFAILOVER case.
21606 			 */
21607 			if ((attach_ill != NULL) ||
21608 			    (ip_nexthop && !ignore_nexthop)) {
21609 				if (mctl_present) {
21610 					io = (ipsec_out_t *)first_mp->b_rptr;
21611 					ASSERT(first_mp->b_datap->db_type ==
21612 					    M_CTL);
21613 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21614 				} else {
21615 					ASSERT(mp == first_mp);
21616 					first_mp = allocb(
21617 					    sizeof (ipsec_info_t), BPRI_HI);
21618 					if (first_mp == NULL) {
21619 						first_mp = mp;
21620 						goto discard_pkt;
21621 					}
21622 					first_mp->b_datap->db_type = M_CTL;
21623 					first_mp->b_wptr +=
21624 					    sizeof (ipsec_info_t);
21625 					/* ipsec_out_secure is B_FALSE now */
21626 					bzero(first_mp->b_rptr,
21627 					    sizeof (ipsec_info_t));
21628 					io = (ipsec_out_t *)first_mp->b_rptr;
21629 					io->ipsec_out_type = IPSEC_OUT;
21630 					io->ipsec_out_len =
21631 					    sizeof (ipsec_out_t);
21632 					io->ipsec_out_use_global_policy =
21633 					    B_TRUE;
21634 					io->ipsec_out_ns = ipst->ips_netstack;
21635 					first_mp->b_cont = mp;
21636 					mctl_present = B_TRUE;
21637 				}
21638 				if (attach_ill != NULL) {
21639 					io->ipsec_out_ill_index = attach_ill->
21640 					    ill_phyint->phyint_ifindex;
21641 					io->ipsec_out_attach_if = B_TRUE;
21642 				} else {
21643 					io->ipsec_out_ip_nexthop = ip_nexthop;
21644 					io->ipsec_out_nexthop_addr =
21645 					    nexthop_addr;
21646 				}
21647 			}
21648 noirefound:
21649 			/*
21650 			 * Mark this packet as having originated on
21651 			 * this machine.  This will be noted in
21652 			 * ire_add_then_send, which needs to know
21653 			 * whether to run it back through ip_wput or
21654 			 * ip_rput following successful resolution.
21655 			 */
21656 			mp->b_prev = NULL;
21657 			mp->b_next = NULL;
21658 			ip_newroute(q, first_mp, dst, NULL, connp, zoneid,
21659 			    ipst);
21660 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21661 			    "ip_wput_end: q %p (%S)", q, "newroute");
21662 			if (attach_ill != NULL)
21663 				ill_refrele(attach_ill);
21664 			if (xmit_ill != NULL)
21665 				ill_refrele(xmit_ill);
21666 			if (need_decref)
21667 				CONN_DEC_REF(connp);
21668 			return;
21669 		}
21670 	}
21671 
21672 	/* We now know where we are going with it. */
21673 
21674 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21675 	    "ip_wput_end: q %p (%S)", q, "end");
21676 
21677 	/*
21678 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21679 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21680 	 */
21681 	if (ire->ire_flags & RTF_MULTIRT) {
21682 		/*
21683 		 * Force the TTL of multirouted packets if required.
21684 		 * The TTL of such packets is bounded by the
21685 		 * ip_multirt_ttl ndd variable.
21686 		 */
21687 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21688 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21689 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21690 			    "(was %d), dst 0x%08x\n",
21691 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21692 			    ntohl(ire->ire_addr)));
21693 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21694 		}
21695 		/*
21696 		 * At this point, we check to see if there are any pending
21697 		 * unresolved routes. ire_multirt_resolvable()
21698 		 * checks in O(n) that all IRE_OFFSUBNET ire
21699 		 * entries for the packet's destination and
21700 		 * flagged RTF_MULTIRT are currently resolved.
21701 		 * If some remain unresolved, we make a copy
21702 		 * of the current message. It will be used
21703 		 * to initiate additional route resolutions.
21704 		 */
21705 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21706 		    MBLK_GETLABEL(first_mp), ipst);
21707 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21708 		    "multirt_need_resolve %d, first_mp %p\n",
21709 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21710 		if (multirt_need_resolve) {
21711 			copy_mp = copymsg(first_mp);
21712 			if (copy_mp != NULL) {
21713 				MULTIRT_DEBUG_TAG(copy_mp);
21714 			}
21715 		}
21716 	}
21717 
21718 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21719 	/*
21720 	 * Try to resolve another multiroute if
21721 	 * ire_multirt_resolvable() deemed it necessary.
21722 	 * At this point, we need to distinguish
21723 	 * multicasts from other packets. For multicasts,
21724 	 * we call ip_newroute_ipif() and request that both
21725 	 * multirouting and setsrc flags are checked.
21726 	 */
21727 	if (copy_mp != NULL) {
21728 		if (CLASSD(dst)) {
21729 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21730 			if (ipif) {
21731 				ASSERT(infop->ip_opt_ill_index == 0);
21732 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21733 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21734 				ipif_refrele(ipif);
21735 			} else {
21736 				MULTIRT_DEBUG_UNTAG(copy_mp);
21737 				freemsg(copy_mp);
21738 				copy_mp = NULL;
21739 			}
21740 		} else {
21741 			ip_newroute(q, copy_mp, dst, NULL, connp, zoneid, ipst);
21742 		}
21743 	}
21744 	if (attach_ill != NULL)
21745 		ill_refrele(attach_ill);
21746 	if (xmit_ill != NULL)
21747 		ill_refrele(xmit_ill);
21748 	if (need_decref)
21749 		CONN_DEC_REF(connp);
21750 	return;
21751 
21752 icmp_parameter_problem:
21753 	/* could not have originated externally */
21754 	ASSERT(mp->b_prev == NULL);
21755 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21756 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21757 		/* it's the IP header length that's in trouble */
21758 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21759 		first_mp = NULL;
21760 	}
21761 
21762 discard_pkt:
21763 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21764 drop_pkt:
21765 	ip1dbg(("ip_wput: dropped packet\n"));
21766 	if (ire != NULL)
21767 		ire_refrele(ire);
21768 	if (need_decref)
21769 		CONN_DEC_REF(connp);
21770 	freemsg(first_mp);
21771 	if (attach_ill != NULL)
21772 		ill_refrele(attach_ill);
21773 	if (xmit_ill != NULL)
21774 		ill_refrele(xmit_ill);
21775 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21776 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21777 }
21778 
21779 /*
21780  * If this is a conn_t queue, then we pass in the conn. This includes the
21781  * zoneid.
21782  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21783  * in which case we use the global zoneid since those are all part of
21784  * the global zone.
21785  */
21786 void
21787 ip_wput(queue_t *q, mblk_t *mp)
21788 {
21789 	if (CONN_Q(q))
21790 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21791 	else
21792 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21793 }
21794 
21795 /*
21796  *
21797  * The following rules must be observed when accessing any ipif or ill
21798  * that has been cached in the conn. Typically conn_nofailover_ill,
21799  * conn_xmit_if_ill, conn_multicast_ipif and conn_multicast_ill.
21800  *
21801  * Access: The ipif or ill pointed to from the conn can be accessed under
21802  * the protection of the conn_lock or after it has been refheld under the
21803  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21804  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21805  * The reason for this is that a concurrent unplumb could actually be
21806  * cleaning up these cached pointers by walking the conns and might have
21807  * finished cleaning up the conn in question. The macros check that an
21808  * unplumb has not yet started on the ipif or ill.
21809  *
21810  * Caching: An ipif or ill pointer may be cached in the conn only after
21811  * making sure that an unplumb has not started. So the caching is done
21812  * while holding both the conn_lock and the ill_lock and after using the
21813  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21814  * flag before starting the cleanup of conns.
21815  *
21816  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21817  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21818  * or a reference to the ipif or a reference to an ire that references the
21819  * ipif. An ipif does not change its ill except for failover/failback. Since
21820  * failover/failback happens only after bringing down the ipif and making sure
21821  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
21822  * the above holds.
21823  */
21824 ipif_t *
21825 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21826 {
21827 	ipif_t	*ipif;
21828 	ill_t	*ill;
21829 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21830 
21831 	*err = 0;
21832 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21833 	mutex_enter(&connp->conn_lock);
21834 	ipif = *ipifp;
21835 	if (ipif != NULL) {
21836 		ill = ipif->ipif_ill;
21837 		mutex_enter(&ill->ill_lock);
21838 		if (IPIF_CAN_LOOKUP(ipif)) {
21839 			ipif_refhold_locked(ipif);
21840 			mutex_exit(&ill->ill_lock);
21841 			mutex_exit(&connp->conn_lock);
21842 			rw_exit(&ipst->ips_ill_g_lock);
21843 			return (ipif);
21844 		} else {
21845 			*err = IPIF_LOOKUP_FAILED;
21846 		}
21847 		mutex_exit(&ill->ill_lock);
21848 	}
21849 	mutex_exit(&connp->conn_lock);
21850 	rw_exit(&ipst->ips_ill_g_lock);
21851 	return (NULL);
21852 }
21853 
21854 ill_t *
21855 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21856 {
21857 	ill_t	*ill;
21858 
21859 	*err = 0;
21860 	mutex_enter(&connp->conn_lock);
21861 	ill = *illp;
21862 	if (ill != NULL) {
21863 		mutex_enter(&ill->ill_lock);
21864 		if (ILL_CAN_LOOKUP(ill)) {
21865 			ill_refhold_locked(ill);
21866 			mutex_exit(&ill->ill_lock);
21867 			mutex_exit(&connp->conn_lock);
21868 			return (ill);
21869 		} else {
21870 			*err = ILL_LOOKUP_FAILED;
21871 		}
21872 		mutex_exit(&ill->ill_lock);
21873 	}
21874 	mutex_exit(&connp->conn_lock);
21875 	return (NULL);
21876 }
21877 
21878 static int
21879 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21880 {
21881 	ill_t	*ill;
21882 
21883 	ill = ipif->ipif_ill;
21884 	mutex_enter(&connp->conn_lock);
21885 	mutex_enter(&ill->ill_lock);
21886 	if (IPIF_CAN_LOOKUP(ipif)) {
21887 		*ipifp = ipif;
21888 		mutex_exit(&ill->ill_lock);
21889 		mutex_exit(&connp->conn_lock);
21890 		return (0);
21891 	}
21892 	mutex_exit(&ill->ill_lock);
21893 	mutex_exit(&connp->conn_lock);
21894 	return (IPIF_LOOKUP_FAILED);
21895 }
21896 
21897 /*
21898  * This is called if the outbound datagram needs fragmentation.
21899  *
21900  * NOTE : This function does not ire_refrele the ire argument passed in.
21901  */
21902 static void
21903 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21904     ip_stack_t *ipst)
21905 {
21906 	ipha_t		*ipha;
21907 	mblk_t		*mp;
21908 	uint32_t	v_hlen_tos_len;
21909 	uint32_t	max_frag;
21910 	uint32_t	frag_flag;
21911 	boolean_t	dont_use;
21912 
21913 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21914 		mp = ipsec_mp->b_cont;
21915 	} else {
21916 		mp = ipsec_mp;
21917 	}
21918 
21919 	ipha = (ipha_t *)mp->b_rptr;
21920 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21921 
21922 #ifdef	_BIG_ENDIAN
21923 #define	V_HLEN	(v_hlen_tos_len >> 24)
21924 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21925 #else
21926 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21927 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21928 #endif
21929 
21930 #ifndef SPEED_BEFORE_SAFETY
21931 	/*
21932 	 * Check that ipha_length is consistent with
21933 	 * the mblk length
21934 	 */
21935 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21936 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21937 		    LENGTH, msgdsize(mp)));
21938 		freemsg(ipsec_mp);
21939 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21940 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21941 		    "packet length mismatch");
21942 		return;
21943 	}
21944 #endif
21945 	/*
21946 	 * Don't use frag_flag if pre-built packet or source
21947 	 * routed or if multicast (since multicast packets do not solicit
21948 	 * ICMP "packet too big" messages). Get the values of
21949 	 * max_frag and frag_flag atomically by acquiring the
21950 	 * ire_lock.
21951 	 */
21952 	mutex_enter(&ire->ire_lock);
21953 	max_frag = ire->ire_max_frag;
21954 	frag_flag = ire->ire_frag_flag;
21955 	mutex_exit(&ire->ire_lock);
21956 
21957 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21958 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21959 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21960 
21961 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21962 	    (dont_use ? 0 : frag_flag), zoneid, ipst);
21963 }
21964 
21965 /*
21966  * Used for deciding the MSS size for the upper layer. Thus
21967  * we need to check the outbound policy values in the conn.
21968  */
21969 int
21970 conn_ipsec_length(conn_t *connp)
21971 {
21972 	ipsec_latch_t *ipl;
21973 
21974 	ipl = connp->conn_latch;
21975 	if (ipl == NULL)
21976 		return (0);
21977 
21978 	if (ipl->ipl_out_policy == NULL)
21979 		return (0);
21980 
21981 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21982 }
21983 
21984 /*
21985  * Returns an estimate of the IPSEC headers size. This is used if
21986  * we don't want to call into IPSEC to get the exact size.
21987  */
21988 int
21989 ipsec_out_extra_length(mblk_t *ipsec_mp)
21990 {
21991 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21992 	ipsec_action_t *a;
21993 
21994 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21995 	if (!io->ipsec_out_secure)
21996 		return (0);
21997 
21998 	a = io->ipsec_out_act;
21999 
22000 	if (a == NULL) {
22001 		ASSERT(io->ipsec_out_policy != NULL);
22002 		a = io->ipsec_out_policy->ipsp_act;
22003 	}
22004 	ASSERT(a != NULL);
22005 
22006 	return (a->ipa_ovhd);
22007 }
22008 
22009 /*
22010  * Returns an estimate of the IPSEC headers size. This is used if
22011  * we don't want to call into IPSEC to get the exact size.
22012  */
22013 int
22014 ipsec_in_extra_length(mblk_t *ipsec_mp)
22015 {
22016 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
22017 	ipsec_action_t *a;
22018 
22019 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
22020 
22021 	a = ii->ipsec_in_action;
22022 	return (a == NULL ? 0 : a->ipa_ovhd);
22023 }
22024 
22025 /*
22026  * If there are any source route options, return the true final
22027  * destination. Otherwise, return the destination.
22028  */
22029 ipaddr_t
22030 ip_get_dst(ipha_t *ipha)
22031 {
22032 	ipoptp_t	opts;
22033 	uchar_t		*opt;
22034 	uint8_t		optval;
22035 	uint8_t		optlen;
22036 	ipaddr_t	dst;
22037 	uint32_t off;
22038 
22039 	dst = ipha->ipha_dst;
22040 
22041 	if (IS_SIMPLE_IPH(ipha))
22042 		return (dst);
22043 
22044 	for (optval = ipoptp_first(&opts, ipha);
22045 	    optval != IPOPT_EOL;
22046 	    optval = ipoptp_next(&opts)) {
22047 		opt = opts.ipoptp_cur;
22048 		optlen = opts.ipoptp_len;
22049 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
22050 		switch (optval) {
22051 		case IPOPT_SSRR:
22052 		case IPOPT_LSRR:
22053 			off = opt[IPOPT_OFFSET];
22054 			/*
22055 			 * If one of the conditions is true, it means
22056 			 * end of options and dst already has the right
22057 			 * value.
22058 			 */
22059 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
22060 				off = optlen - IP_ADDR_LEN;
22061 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
22062 			}
22063 			return (dst);
22064 		default:
22065 			break;
22066 		}
22067 	}
22068 
22069 	return (dst);
22070 }
22071 
22072 mblk_t *
22073 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
22074     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
22075 {
22076 	ipsec_out_t	*io;
22077 	mblk_t		*first_mp;
22078 	boolean_t policy_present;
22079 	ip_stack_t	*ipst;
22080 	ipsec_stack_t	*ipss;
22081 
22082 	ASSERT(ire != NULL);
22083 	ipst = ire->ire_ipst;
22084 	ipss = ipst->ips_netstack->netstack_ipsec;
22085 
22086 	first_mp = mp;
22087 	if (mp->b_datap->db_type == M_CTL) {
22088 		io = (ipsec_out_t *)first_mp->b_rptr;
22089 		/*
22090 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
22091 		 *
22092 		 * 1) There is per-socket policy (including cached global
22093 		 *    policy) or a policy on the IP-in-IP tunnel.
22094 		 * 2) There is no per-socket policy, but it is
22095 		 *    a multicast packet that needs to go out
22096 		 *    on a specific interface. This is the case
22097 		 *    where (ip_wput and ip_wput_multicast) attaches
22098 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
22099 		 *
22100 		 * In case (2) we check with global policy to
22101 		 * see if there is a match and set the ill_index
22102 		 * appropriately so that we can lookup the ire
22103 		 * properly in ip_wput_ipsec_out.
22104 		 */
22105 
22106 		/*
22107 		 * ipsec_out_use_global_policy is set to B_FALSE
22108 		 * in ipsec_in_to_out(). Refer to that function for
22109 		 * details.
22110 		 */
22111 		if ((io->ipsec_out_latch == NULL) &&
22112 		    (io->ipsec_out_use_global_policy)) {
22113 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
22114 			    ire, connp, unspec_src, zoneid));
22115 		}
22116 		if (!io->ipsec_out_secure) {
22117 			/*
22118 			 * If this is not a secure packet, drop
22119 			 * the IPSEC_OUT mp and treat it as a clear
22120 			 * packet. This happens when we are sending
22121 			 * a ICMP reply back to a clear packet. See
22122 			 * ipsec_in_to_out() for details.
22123 			 */
22124 			mp = first_mp->b_cont;
22125 			freeb(first_mp);
22126 		}
22127 		return (mp);
22128 	}
22129 	/*
22130 	 * See whether we need to attach a global policy here. We
22131 	 * don't depend on the conn (as it could be null) for deciding
22132 	 * what policy this datagram should go through because it
22133 	 * should have happened in ip_wput if there was some
22134 	 * policy. This normally happens for connections which are not
22135 	 * fully bound preventing us from caching policies in
22136 	 * ip_bind. Packets coming from the TCP listener/global queue
22137 	 * - which are non-hard_bound - could also be affected by
22138 	 * applying policy here.
22139 	 *
22140 	 * If this packet is coming from tcp global queue or listener,
22141 	 * we will be applying policy here.  This may not be *right*
22142 	 * if these packets are coming from the detached connection as
22143 	 * it could have gone in clear before. This happens only if a
22144 	 * TCP connection started when there is no policy and somebody
22145 	 * added policy before it became detached. Thus packets of the
22146 	 * detached connection could go out secure and the other end
22147 	 * would drop it because it will be expecting in clear. The
22148 	 * converse is not true i.e if somebody starts a TCP
22149 	 * connection and deletes the policy, all the packets will
22150 	 * still go out with the policy that existed before deleting
22151 	 * because ip_unbind sends up policy information which is used
22152 	 * by TCP on subsequent ip_wputs. The right solution is to fix
22153 	 * TCP to attach a dummy IPSEC_OUT and set
22154 	 * ipsec_out_use_global_policy to B_FALSE. As this might
22155 	 * affect performance for normal cases, we are not doing it.
22156 	 * Thus, set policy before starting any TCP connections.
22157 	 *
22158 	 * NOTE - We might apply policy even for a hard bound connection
22159 	 * - for which we cached policy in ip_bind - if somebody added
22160 	 * global policy after we inherited the policy in ip_bind.
22161 	 * This means that the packets that were going out in clear
22162 	 * previously would start going secure and hence get dropped
22163 	 * on the other side. To fix this, TCP attaches a dummy
22164 	 * ipsec_out and make sure that we don't apply global policy.
22165 	 */
22166 	if (ipha != NULL)
22167 		policy_present = ipss->ipsec_outbound_v4_policy_present;
22168 	else
22169 		policy_present = ipss->ipsec_outbound_v6_policy_present;
22170 	if (!policy_present)
22171 		return (mp);
22172 
22173 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
22174 	    zoneid));
22175 }
22176 
22177 ire_t *
22178 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
22179 {
22180 	ipaddr_t addr;
22181 	ire_t *save_ire;
22182 	irb_t *irb;
22183 	ill_group_t *illgrp;
22184 	int	err;
22185 
22186 	save_ire = ire;
22187 	addr = ire->ire_addr;
22188 
22189 	ASSERT(ire->ire_type == IRE_BROADCAST);
22190 
22191 	illgrp = connp->conn_outgoing_ill->ill_group;
22192 	if (illgrp == NULL) {
22193 		*conn_outgoing_ill = conn_get_held_ill(connp,
22194 		    &connp->conn_outgoing_ill, &err);
22195 		if (err == ILL_LOOKUP_FAILED) {
22196 			ire_refrele(save_ire);
22197 			return (NULL);
22198 		}
22199 		return (save_ire);
22200 	}
22201 	/*
22202 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
22203 	 * If it is part of the group, we need to send on the ire
22204 	 * that has been cleared of IRE_MARK_NORECV and that belongs
22205 	 * to this group. This is okay as IP_BOUND_IF really means
22206 	 * any ill in the group. We depend on the fact that the
22207 	 * first ire in the group is always cleared of IRE_MARK_NORECV
22208 	 * if such an ire exists. This is possible only if you have
22209 	 * at least one ill in the group that has not failed.
22210 	 *
22211 	 * First get to the ire that matches the address and group.
22212 	 *
22213 	 * We don't look for an ire with a matching zoneid because a given zone
22214 	 * won't always have broadcast ires on all ills in the group.
22215 	 */
22216 	irb = ire->ire_bucket;
22217 	rw_enter(&irb->irb_lock, RW_READER);
22218 	if (ire->ire_marks & IRE_MARK_NORECV) {
22219 		/*
22220 		 * If the current zone only has an ire broadcast for this
22221 		 * address marked NORECV, the ire we want is ahead in the
22222 		 * bucket, so we look it up deliberately ignoring the zoneid.
22223 		 */
22224 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
22225 			if (ire->ire_addr != addr)
22226 				continue;
22227 			/* skip over deleted ires */
22228 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
22229 				continue;
22230 		}
22231 	}
22232 	while (ire != NULL) {
22233 		/*
22234 		 * If a new interface is coming up, we could end up
22235 		 * seeing the loopback ire and the non-loopback ire
22236 		 * may not have been added yet. So check for ire_stq
22237 		 */
22238 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
22239 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
22240 			break;
22241 		}
22242 		ire = ire->ire_next;
22243 	}
22244 	if (ire != NULL && ire->ire_addr == addr &&
22245 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
22246 		IRE_REFHOLD(ire);
22247 		rw_exit(&irb->irb_lock);
22248 		ire_refrele(save_ire);
22249 		*conn_outgoing_ill = ire_to_ill(ire);
22250 		/*
22251 		 * Refhold the ill to make the conn_outgoing_ill
22252 		 * independent of the ire. ip_wput_ire goes in a loop
22253 		 * and may refrele the ire. Since we have an ire at this
22254 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
22255 		 */
22256 		ill_refhold(*conn_outgoing_ill);
22257 		return (ire);
22258 	}
22259 	rw_exit(&irb->irb_lock);
22260 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
22261 	/*
22262 	 * If we can't find a suitable ire, return the original ire.
22263 	 */
22264 	return (save_ire);
22265 }
22266 
22267 /*
22268  * This function does the ire_refrele of the ire passed in as the
22269  * argument. As this function looks up more ires i.e broadcast ires,
22270  * it needs to REFRELE them. Currently, for simplicity we don't
22271  * differentiate the one passed in and looked up here. We always
22272  * REFRELE.
22273  * IPQoS Notes:
22274  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
22275  * IPSec packets are done in ipsec_out_process.
22276  *
22277  */
22278 void
22279 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
22280     zoneid_t zoneid)
22281 {
22282 	ipha_t		*ipha;
22283 #define	rptr	((uchar_t *)ipha)
22284 	queue_t		*stq;
22285 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
22286 	uint32_t	v_hlen_tos_len;
22287 	uint32_t	ttl_protocol;
22288 	ipaddr_t	src;
22289 	ipaddr_t	dst;
22290 	uint32_t	cksum;
22291 	ipaddr_t	orig_src;
22292 	ire_t		*ire1;
22293 	mblk_t		*next_mp;
22294 	uint_t		hlen;
22295 	uint16_t	*up;
22296 	uint32_t	max_frag = ire->ire_max_frag;
22297 	ill_t		*ill = ire_to_ill(ire);
22298 	int		clusterwide;
22299 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
22300 	int		ipsec_len;
22301 	mblk_t		*first_mp;
22302 	ipsec_out_t	*io;
22303 	boolean_t	conn_dontroute;		/* conn value for multicast */
22304 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
22305 	boolean_t	multicast_forward;	/* Should we forward ? */
22306 	boolean_t	unspec_src;
22307 	ill_t		*conn_outgoing_ill = NULL;
22308 	ill_t		*ire_ill;
22309 	ill_t		*ire1_ill;
22310 	ill_t		*out_ill;
22311 	uint32_t 	ill_index = 0;
22312 	boolean_t	multirt_send = B_FALSE;
22313 	int		err;
22314 	ipxmit_state_t	pktxmit_state;
22315 	ip_stack_t	*ipst = ire->ire_ipst;
22316 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
22317 
22318 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
22319 	    "ip_wput_ire_start: q %p", q);
22320 
22321 	multicast_forward = B_FALSE;
22322 	unspec_src = (connp != NULL && connp->conn_unspec_src);
22323 
22324 	if (ire->ire_flags & RTF_MULTIRT) {
22325 		/*
22326 		 * Multirouting case. The bucket where ire is stored
22327 		 * probably holds other RTF_MULTIRT flagged ire
22328 		 * to the destination. In this call to ip_wput_ire,
22329 		 * we attempt to send the packet through all
22330 		 * those ires. Thus, we first ensure that ire is the
22331 		 * first RTF_MULTIRT ire in the bucket,
22332 		 * before walking the ire list.
22333 		 */
22334 		ire_t *first_ire;
22335 		irb_t *irb = ire->ire_bucket;
22336 		ASSERT(irb != NULL);
22337 
22338 		/* Make sure we do not omit any multiroute ire. */
22339 		IRB_REFHOLD(irb);
22340 		for (first_ire = irb->irb_ire;
22341 		    first_ire != NULL;
22342 		    first_ire = first_ire->ire_next) {
22343 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22344 			    (first_ire->ire_addr == ire->ire_addr) &&
22345 			    !(first_ire->ire_marks &
22346 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
22347 				break;
22348 			}
22349 		}
22350 
22351 		if ((first_ire != NULL) && (first_ire != ire)) {
22352 			IRE_REFHOLD(first_ire);
22353 			ire_refrele(ire);
22354 			ire = first_ire;
22355 			ill = ire_to_ill(ire);
22356 		}
22357 		IRB_REFRELE(irb);
22358 	}
22359 
22360 	/*
22361 	 * conn_outgoing_ill is used only in the broadcast loop.
22362 	 * for performance we don't grab the mutexs in the fastpath
22363 	 */
22364 	if ((connp != NULL) &&
22365 	    (connp->conn_xmit_if_ill == NULL) &&
22366 	    (ire->ire_type == IRE_BROADCAST) &&
22367 	    ((connp->conn_nofailover_ill != NULL) ||
22368 	    (connp->conn_outgoing_ill != NULL))) {
22369 		/*
22370 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
22371 		 * option. So, see if this endpoint is bound to a
22372 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
22373 		 * that if the interface is failed, we will still send
22374 		 * the packet on the same ill which is what we want.
22375 		 */
22376 		conn_outgoing_ill = conn_get_held_ill(connp,
22377 		    &connp->conn_nofailover_ill, &err);
22378 		if (err == ILL_LOOKUP_FAILED) {
22379 			ire_refrele(ire);
22380 			freemsg(mp);
22381 			return;
22382 		}
22383 		if (conn_outgoing_ill == NULL) {
22384 			/*
22385 			 * Choose a good ill in the group to send the
22386 			 * packets on.
22387 			 */
22388 			ire = conn_set_outgoing_ill(connp, ire,
22389 			    &conn_outgoing_ill);
22390 			if (ire == NULL) {
22391 				freemsg(mp);
22392 				return;
22393 			}
22394 		}
22395 	}
22396 
22397 	if (mp->b_datap->db_type != M_CTL) {
22398 		ipha = (ipha_t *)mp->b_rptr;
22399 	} else {
22400 		io = (ipsec_out_t *)mp->b_rptr;
22401 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22402 		ASSERT(zoneid == io->ipsec_out_zoneid);
22403 		ASSERT(zoneid != ALL_ZONES);
22404 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22405 		dst = ipha->ipha_dst;
22406 		/*
22407 		 * For the multicast case, ipsec_out carries conn_dontroute and
22408 		 * conn_multicast_loop as conn may not be available here. We
22409 		 * need this for multicast loopback and forwarding which is done
22410 		 * later in the code.
22411 		 */
22412 		if (CLASSD(dst)) {
22413 			conn_dontroute = io->ipsec_out_dontroute;
22414 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22415 			/*
22416 			 * If conn_dontroute is not set or conn_multicast_loop
22417 			 * is set, we need to do forwarding/loopback. For
22418 			 * datagrams from ip_wput_multicast, conn_dontroute is
22419 			 * set to B_TRUE and conn_multicast_loop is set to
22420 			 * B_FALSE so that we neither do forwarding nor
22421 			 * loopback.
22422 			 */
22423 			if (!conn_dontroute || conn_multicast_loop)
22424 				multicast_forward = B_TRUE;
22425 		}
22426 	}
22427 
22428 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22429 	    ire->ire_zoneid != ALL_ZONES) {
22430 		/*
22431 		 * When a zone sends a packet to another zone, we try to deliver
22432 		 * the packet under the same conditions as if the destination
22433 		 * was a real node on the network. To do so, we look for a
22434 		 * matching route in the forwarding table.
22435 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22436 		 * ip_newroute() does.
22437 		 * Note that IRE_LOCAL are special, since they are used
22438 		 * when the zoneid doesn't match in some cases. This means that
22439 		 * we need to handle ipha_src differently since ire_src_addr
22440 		 * belongs to the receiving zone instead of the sending zone.
22441 		 * When ip_restrict_interzone_loopback is set, then
22442 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22443 		 * for loopback between zones when the logical "Ethernet" would
22444 		 * have looped them back.
22445 		 */
22446 		ire_t *src_ire;
22447 
22448 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22449 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22450 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22451 		if (src_ire != NULL &&
22452 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22453 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22454 		    ire_local_same_ill_group(ire, src_ire))) {
22455 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22456 				ipha->ipha_src = src_ire->ire_src_addr;
22457 			ire_refrele(src_ire);
22458 		} else {
22459 			ire_refrele(ire);
22460 			if (conn_outgoing_ill != NULL)
22461 				ill_refrele(conn_outgoing_ill);
22462 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22463 			if (src_ire != NULL) {
22464 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22465 					ire_refrele(src_ire);
22466 					freemsg(mp);
22467 					return;
22468 				}
22469 				ire_refrele(src_ire);
22470 			}
22471 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22472 				/* Failed */
22473 				freemsg(mp);
22474 				return;
22475 			}
22476 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22477 			    ipst);
22478 			return;
22479 		}
22480 	}
22481 
22482 	if (mp->b_datap->db_type == M_CTL ||
22483 	    ipss->ipsec_outbound_v4_policy_present) {
22484 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22485 		    unspec_src, zoneid);
22486 		if (mp == NULL) {
22487 			ire_refrele(ire);
22488 			if (conn_outgoing_ill != NULL)
22489 				ill_refrele(conn_outgoing_ill);
22490 			return;
22491 		}
22492 	}
22493 
22494 	first_mp = mp;
22495 	ipsec_len = 0;
22496 
22497 	if (first_mp->b_datap->db_type == M_CTL) {
22498 		io = (ipsec_out_t *)first_mp->b_rptr;
22499 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22500 		mp = first_mp->b_cont;
22501 		ipsec_len = ipsec_out_extra_length(first_mp);
22502 		ASSERT(ipsec_len >= 0);
22503 		/* We already picked up the zoneid from the M_CTL above */
22504 		ASSERT(zoneid == io->ipsec_out_zoneid);
22505 		ASSERT(zoneid != ALL_ZONES);
22506 
22507 		/*
22508 		 * Drop M_CTL here if IPsec processing is not needed.
22509 		 * (Non-IPsec use of M_CTL extracted any information it
22510 		 * needed above).
22511 		 */
22512 		if (ipsec_len == 0) {
22513 			freeb(first_mp);
22514 			first_mp = mp;
22515 		}
22516 	}
22517 
22518 	/*
22519 	 * Fast path for ip_wput_ire
22520 	 */
22521 
22522 	ipha = (ipha_t *)mp->b_rptr;
22523 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22524 	dst = ipha->ipha_dst;
22525 
22526 	/*
22527 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22528 	 * if the socket is a SOCK_RAW type. The transport checksum should
22529 	 * be provided in the pre-built packet, so we don't need to compute it.
22530 	 * Also, other application set flags, like DF, should not be altered.
22531 	 * Other transport MUST pass down zero.
22532 	 */
22533 	ip_hdr_included = ipha->ipha_ident;
22534 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22535 
22536 	if (CLASSD(dst)) {
22537 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22538 		    ntohl(dst),
22539 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22540 		    ntohl(ire->ire_addr)));
22541 	}
22542 
22543 /* Macros to extract header fields from data already in registers */
22544 #ifdef	_BIG_ENDIAN
22545 #define	V_HLEN	(v_hlen_tos_len >> 24)
22546 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22547 #define	PROTO	(ttl_protocol & 0xFF)
22548 #else
22549 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22550 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22551 #define	PROTO	(ttl_protocol >> 8)
22552 #endif
22553 
22554 
22555 	orig_src = src = ipha->ipha_src;
22556 	/* (The loop back to "another" is explained down below.) */
22557 another:;
22558 	/*
22559 	 * Assign an ident value for this packet.  We assign idents on
22560 	 * a per destination basis out of the IRE.  There could be
22561 	 * other threads targeting the same destination, so we have to
22562 	 * arrange for a atomic increment.  Note that we use a 32-bit
22563 	 * atomic add because it has better performance than its
22564 	 * 16-bit sibling.
22565 	 *
22566 	 * If running in cluster mode and if the source address
22567 	 * belongs to a replicated service then vector through
22568 	 * cl_inet_ipident vector to allocate ip identifier
22569 	 * NOTE: This is a contract private interface with the
22570 	 * clustering group.
22571 	 */
22572 	clusterwide = 0;
22573 	if (cl_inet_ipident) {
22574 		ASSERT(cl_inet_isclusterwide);
22575 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
22576 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
22577 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
22578 			    AF_INET, (uint8_t *)(uintptr_t)src,
22579 			    (uint8_t *)(uintptr_t)dst);
22580 			clusterwide = 1;
22581 		}
22582 	}
22583 	if (!clusterwide) {
22584 		ipha->ipha_ident =
22585 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22586 	}
22587 
22588 #ifndef _BIG_ENDIAN
22589 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22590 #endif
22591 
22592 	/*
22593 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22594 	 * This is needed to obey conn_unspec_src when packets go through
22595 	 * ip_newroute + arp.
22596 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22597 	 */
22598 	if (src == INADDR_ANY && !unspec_src) {
22599 		/*
22600 		 * Assign the appropriate source address from the IRE if none
22601 		 * was specified.
22602 		 */
22603 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22604 
22605 		/*
22606 		 * With IP multipathing, broadcast packets are sent on the ire
22607 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
22608 		 * the group. However, this ire might not be in the same zone so
22609 		 * we can't always use its source address. We look for a
22610 		 * broadcast ire in the same group and in the right zone.
22611 		 */
22612 		if (ire->ire_type == IRE_BROADCAST &&
22613 		    ire->ire_zoneid != zoneid) {
22614 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
22615 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
22616 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
22617 			if (src_ire != NULL) {
22618 				src = src_ire->ire_src_addr;
22619 				ire_refrele(src_ire);
22620 			} else {
22621 				ire_refrele(ire);
22622 				if (conn_outgoing_ill != NULL)
22623 					ill_refrele(conn_outgoing_ill);
22624 				freemsg(first_mp);
22625 				if (ill != NULL) {
22626 					BUMP_MIB(ill->ill_ip_mib,
22627 					    ipIfStatsOutDiscards);
22628 				} else {
22629 					BUMP_MIB(&ipst->ips_ip_mib,
22630 					    ipIfStatsOutDiscards);
22631 				}
22632 				return;
22633 			}
22634 		} else {
22635 			src = ire->ire_src_addr;
22636 		}
22637 
22638 		if (connp == NULL) {
22639 			ip1dbg(("ip_wput_ire: no connp and no src "
22640 			    "address for dst 0x%x, using src 0x%x\n",
22641 			    ntohl(dst),
22642 			    ntohl(src)));
22643 		}
22644 		ipha->ipha_src = src;
22645 	}
22646 	stq = ire->ire_stq;
22647 
22648 	/*
22649 	 * We only allow ire chains for broadcasts since there will
22650 	 * be multiple IRE_CACHE entries for the same multicast
22651 	 * address (one per ipif).
22652 	 */
22653 	next_mp = NULL;
22654 
22655 	/* broadcast packet */
22656 	if (ire->ire_type == IRE_BROADCAST)
22657 		goto broadcast;
22658 
22659 	/* loopback ? */
22660 	if (stq == NULL)
22661 		goto nullstq;
22662 
22663 	/* The ill_index for outbound ILL */
22664 	ill_index = Q_TO_INDEX(stq);
22665 
22666 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22667 	ttl_protocol = ((uint16_t *)ipha)[4];
22668 
22669 	/* pseudo checksum (do it in parts for IP header checksum) */
22670 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22671 
22672 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22673 		queue_t *dev_q = stq->q_next;
22674 
22675 		/* flow controlled */
22676 		if ((dev_q->q_next || dev_q->q_first) &&
22677 		    !canput(dev_q))
22678 			goto blocked;
22679 		if ((PROTO == IPPROTO_UDP) &&
22680 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22681 			hlen = (V_HLEN & 0xF) << 2;
22682 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22683 			if (*up != 0) {
22684 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22685 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22686 				/* Software checksum? */
22687 				if (DB_CKSUMFLAGS(mp) == 0) {
22688 					IP_STAT(ipst, ip_out_sw_cksum);
22689 					IP_STAT_UPDATE(ipst,
22690 					    ip_udp_out_sw_cksum_bytes,
22691 					    LENGTH - hlen);
22692 				}
22693 			}
22694 		}
22695 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22696 		hlen = (V_HLEN & 0xF) << 2;
22697 		if (PROTO == IPPROTO_TCP) {
22698 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22699 			/*
22700 			 * The packet header is processed once and for all, even
22701 			 * in the multirouting case. We disable hardware
22702 			 * checksum if the packet is multirouted, as it will be
22703 			 * replicated via several interfaces, and not all of
22704 			 * them may have this capability.
22705 			 */
22706 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22707 			    LENGTH, max_frag, ipsec_len, cksum);
22708 			/* Software checksum? */
22709 			if (DB_CKSUMFLAGS(mp) == 0) {
22710 				IP_STAT(ipst, ip_out_sw_cksum);
22711 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22712 				    LENGTH - hlen);
22713 			}
22714 		} else {
22715 			sctp_hdr_t	*sctph;
22716 
22717 			ASSERT(PROTO == IPPROTO_SCTP);
22718 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22719 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22720 			/*
22721 			 * Zero out the checksum field to ensure proper
22722 			 * checksum calculation.
22723 			 */
22724 			sctph->sh_chksum = 0;
22725 #ifdef	DEBUG
22726 			if (!skip_sctp_cksum)
22727 #endif
22728 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22729 		}
22730 	}
22731 
22732 	/*
22733 	 * If this is a multicast packet and originated from ip_wput
22734 	 * we need to do loopback and forwarding checks. If it comes
22735 	 * from ip_wput_multicast, we SHOULD not do this.
22736 	 */
22737 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22738 
22739 	/* checksum */
22740 	cksum += ttl_protocol;
22741 
22742 	/* fragment the packet */
22743 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22744 		goto fragmentit;
22745 	/*
22746 	 * Don't use frag_flag if packet is pre-built or source
22747 	 * routed or if multicast (since multicast packets do
22748 	 * not solicit ICMP "packet too big" messages).
22749 	 */
22750 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22751 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22752 	    !ip_source_route_included(ipha)) &&
22753 	    !CLASSD(ipha->ipha_dst))
22754 		ipha->ipha_fragment_offset_and_flags |=
22755 		    htons(ire->ire_frag_flag);
22756 
22757 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22758 		/* calculate IP header checksum */
22759 		cksum += ipha->ipha_ident;
22760 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22761 		cksum += ipha->ipha_fragment_offset_and_flags;
22762 
22763 		/* IP options present */
22764 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22765 		if (hlen)
22766 			goto checksumoptions;
22767 
22768 		/* calculate hdr checksum */
22769 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22770 		cksum = ~(cksum + (cksum >> 16));
22771 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22772 	}
22773 	if (ipsec_len != 0) {
22774 		/*
22775 		 * We will do the rest of the processing after
22776 		 * we come back from IPSEC in ip_wput_ipsec_out().
22777 		 */
22778 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22779 
22780 		io = (ipsec_out_t *)first_mp->b_rptr;
22781 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
22782 		    ill_phyint->phyint_ifindex;
22783 
22784 		ipsec_out_process(q, first_mp, ire, ill_index);
22785 		ire_refrele(ire);
22786 		if (conn_outgoing_ill != NULL)
22787 			ill_refrele(conn_outgoing_ill);
22788 		return;
22789 	}
22790 
22791 	/*
22792 	 * In most cases, the emission loop below is entered only
22793 	 * once. Only in the case where the ire holds the
22794 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22795 	 * flagged ires in the bucket, and send the packet
22796 	 * through all crossed RTF_MULTIRT routes.
22797 	 */
22798 	if (ire->ire_flags & RTF_MULTIRT) {
22799 		multirt_send = B_TRUE;
22800 	}
22801 	do {
22802 		if (multirt_send) {
22803 			irb_t *irb;
22804 			/*
22805 			 * We are in a multiple send case, need to get
22806 			 * the next ire and make a duplicate of the packet.
22807 			 * ire1 holds here the next ire to process in the
22808 			 * bucket. If multirouting is expected,
22809 			 * any non-RTF_MULTIRT ire that has the
22810 			 * right destination address is ignored.
22811 			 */
22812 			irb = ire->ire_bucket;
22813 			ASSERT(irb != NULL);
22814 
22815 			IRB_REFHOLD(irb);
22816 			for (ire1 = ire->ire_next;
22817 			    ire1 != NULL;
22818 			    ire1 = ire1->ire_next) {
22819 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22820 					continue;
22821 				if (ire1->ire_addr != ire->ire_addr)
22822 					continue;
22823 				if (ire1->ire_marks &
22824 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
22825 					continue;
22826 
22827 				/* Got one */
22828 				IRE_REFHOLD(ire1);
22829 				break;
22830 			}
22831 			IRB_REFRELE(irb);
22832 
22833 			if (ire1 != NULL) {
22834 				next_mp = copyb(mp);
22835 				if ((next_mp == NULL) ||
22836 				    ((mp->b_cont != NULL) &&
22837 				    ((next_mp->b_cont =
22838 				    dupmsg(mp->b_cont)) == NULL))) {
22839 					freemsg(next_mp);
22840 					next_mp = NULL;
22841 					ire_refrele(ire1);
22842 					ire1 = NULL;
22843 				}
22844 			}
22845 
22846 			/* Last multiroute ire; don't loop anymore. */
22847 			if (ire1 == NULL) {
22848 				multirt_send = B_FALSE;
22849 			}
22850 		}
22851 
22852 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22853 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22854 		    mblk_t *, mp);
22855 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22856 		    ipst->ips_ipv4firewall_physical_out,
22857 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, ipst);
22858 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22859 		if (mp == NULL)
22860 			goto release_ire_and_ill;
22861 
22862 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22863 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22864 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE);
22865 		if ((pktxmit_state == SEND_FAILED) ||
22866 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22867 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22868 			    "- packet dropped\n"));
22869 release_ire_and_ill:
22870 			ire_refrele(ire);
22871 			if (next_mp != NULL) {
22872 				freemsg(next_mp);
22873 				ire_refrele(ire1);
22874 			}
22875 			if (conn_outgoing_ill != NULL)
22876 				ill_refrele(conn_outgoing_ill);
22877 			return;
22878 		}
22879 
22880 		if (CLASSD(dst)) {
22881 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22882 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22883 			    LENGTH);
22884 		}
22885 
22886 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22887 		    "ip_wput_ire_end: q %p (%S)",
22888 		    q, "last copy out");
22889 		IRE_REFRELE(ire);
22890 
22891 		if (multirt_send) {
22892 			ASSERT(ire1);
22893 			/*
22894 			 * Proceed with the next RTF_MULTIRT ire,
22895 			 * Also set up the send-to queue accordingly.
22896 			 */
22897 			ire = ire1;
22898 			ire1 = NULL;
22899 			stq = ire->ire_stq;
22900 			mp = next_mp;
22901 			next_mp = NULL;
22902 			ipha = (ipha_t *)mp->b_rptr;
22903 			ill_index = Q_TO_INDEX(stq);
22904 			ill = (ill_t *)stq->q_ptr;
22905 		}
22906 	} while (multirt_send);
22907 	if (conn_outgoing_ill != NULL)
22908 		ill_refrele(conn_outgoing_ill);
22909 	return;
22910 
22911 	/*
22912 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22913 	 */
22914 broadcast:
22915 	{
22916 		/*
22917 		 * Avoid broadcast storms by setting the ttl to 1
22918 		 * for broadcasts. This parameter can be set
22919 		 * via ndd, so make sure that for the SO_DONTROUTE
22920 		 * case that ipha_ttl is always set to 1.
22921 		 * In the event that we are replying to incoming
22922 		 * ICMP packets, conn could be NULL.
22923 		 */
22924 		if ((connp != NULL) && connp->conn_dontroute)
22925 			ipha->ipha_ttl = 1;
22926 		else
22927 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22928 
22929 		/*
22930 		 * Note that we are not doing a IRB_REFHOLD here.
22931 		 * Actually we don't care if the list changes i.e
22932 		 * if somebody deletes an IRE from the list while
22933 		 * we drop the lock, the next time we come around
22934 		 * ire_next will be NULL and hence we won't send
22935 		 * out multiple copies which is fine.
22936 		 */
22937 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22938 		ire1 = ire->ire_next;
22939 		if (conn_outgoing_ill != NULL) {
22940 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22941 				ASSERT(ire1 == ire->ire_next);
22942 				if (ire1 != NULL && ire1->ire_addr == dst) {
22943 					ire_refrele(ire);
22944 					ire = ire1;
22945 					IRE_REFHOLD(ire);
22946 					ire1 = ire->ire_next;
22947 					continue;
22948 				}
22949 				rw_exit(&ire->ire_bucket->irb_lock);
22950 				/* Did not find a matching ill */
22951 				ip1dbg(("ip_wput_ire: broadcast with no "
22952 				    "matching IP_BOUND_IF ill %s\n",
22953 				    conn_outgoing_ill->ill_name));
22954 				freemsg(first_mp);
22955 				if (ire != NULL)
22956 					ire_refrele(ire);
22957 				ill_refrele(conn_outgoing_ill);
22958 				return;
22959 			}
22960 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22961 			/*
22962 			 * If the next IRE has the same address and is not one
22963 			 * of the two copies that we need to send, try to see
22964 			 * whether this copy should be sent at all. This
22965 			 * assumes that we insert loopbacks first and then
22966 			 * non-loopbacks. This is acheived by inserting the
22967 			 * loopback always before non-loopback.
22968 			 * This is used to send a single copy of a broadcast
22969 			 * packet out all physical interfaces that have an
22970 			 * matching IRE_BROADCAST while also looping
22971 			 * back one copy (to ip_wput_local) for each
22972 			 * matching physical interface. However, we avoid
22973 			 * sending packets out different logical that match by
22974 			 * having ipif_up/ipif_down supress duplicate
22975 			 * IRE_BROADCASTS.
22976 			 *
22977 			 * This feature is currently used to get broadcasts
22978 			 * sent to multiple interfaces, when the broadcast
22979 			 * address being used applies to multiple interfaces.
22980 			 * For example, a whole net broadcast will be
22981 			 * replicated on every connected subnet of
22982 			 * the target net.
22983 			 *
22984 			 * Each zone has its own set of IRE_BROADCASTs, so that
22985 			 * we're able to distribute inbound packets to multiple
22986 			 * zones who share a broadcast address. We avoid looping
22987 			 * back outbound packets in different zones but on the
22988 			 * same ill, as the application would see duplicates.
22989 			 *
22990 			 * If the interfaces are part of the same group,
22991 			 * we would want to send only one copy out for
22992 			 * whole group.
22993 			 *
22994 			 * This logic assumes that ire_add_v4() groups the
22995 			 * IRE_BROADCAST entries so that those with the same
22996 			 * ire_addr and ill_group are kept together.
22997 			 */
22998 			ire_ill = ire->ire_ipif->ipif_ill;
22999 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
23000 				if (ire_ill->ill_group != NULL &&
23001 				    (ire->ire_marks & IRE_MARK_NORECV)) {
23002 					/*
23003 					 * If the current zone only has an ire
23004 					 * broadcast for this address marked
23005 					 * NORECV, the ire we want is ahead in
23006 					 * the bucket, so we look it up
23007 					 * deliberately ignoring the zoneid.
23008 					 */
23009 					for (ire1 = ire->ire_bucket->irb_ire;
23010 					    ire1 != NULL;
23011 					    ire1 = ire1->ire_next) {
23012 						ire1_ill =
23013 						    ire1->ire_ipif->ipif_ill;
23014 						if (ire1->ire_addr != dst)
23015 							continue;
23016 						/* skip over the current ire */
23017 						if (ire1 == ire)
23018 							continue;
23019 						/* skip over deleted ires */
23020 						if (ire1->ire_marks &
23021 						    IRE_MARK_CONDEMNED)
23022 							continue;
23023 						/*
23024 						 * non-loopback ire in our
23025 						 * group: use it for the next
23026 						 * pass in the loop
23027 						 */
23028 						if (ire1->ire_stq != NULL &&
23029 						    ire1_ill->ill_group ==
23030 						    ire_ill->ill_group)
23031 							break;
23032 					}
23033 				}
23034 			} else {
23035 				while (ire1 != NULL && ire1->ire_addr == dst) {
23036 					ire1_ill = ire1->ire_ipif->ipif_ill;
23037 					/*
23038 					 * We can have two broadcast ires on the
23039 					 * same ill in different zones; here
23040 					 * we'll send a copy of the packet on
23041 					 * each ill and the fanout code will
23042 					 * call conn_wantpacket() to check that
23043 					 * the zone has the broadcast address
23044 					 * configured on the ill. If the two
23045 					 * ires are in the same group we only
23046 					 * send one copy up.
23047 					 */
23048 					if (ire1_ill != ire_ill &&
23049 					    (ire1_ill->ill_group == NULL ||
23050 					    ire_ill->ill_group == NULL ||
23051 					    ire1_ill->ill_group !=
23052 					    ire_ill->ill_group)) {
23053 						break;
23054 					}
23055 					ire1 = ire1->ire_next;
23056 				}
23057 			}
23058 		}
23059 		ASSERT(multirt_send == B_FALSE);
23060 		if (ire1 != NULL && ire1->ire_addr == dst) {
23061 			if ((ire->ire_flags & RTF_MULTIRT) &&
23062 			    (ire1->ire_flags & RTF_MULTIRT)) {
23063 				/*
23064 				 * We are in the multirouting case.
23065 				 * The message must be sent at least
23066 				 * on both ires. These ires have been
23067 				 * inserted AFTER the standard ones
23068 				 * in ip_rt_add(). There are thus no
23069 				 * other ire entries for the destination
23070 				 * address in the rest of the bucket
23071 				 * that do not have the RTF_MULTIRT
23072 				 * flag. We don't process a copy
23073 				 * of the message here. This will be
23074 				 * done in the final sending loop.
23075 				 */
23076 				multirt_send = B_TRUE;
23077 			} else {
23078 				next_mp = ip_copymsg(first_mp);
23079 				if (next_mp != NULL)
23080 					IRE_REFHOLD(ire1);
23081 			}
23082 		}
23083 		rw_exit(&ire->ire_bucket->irb_lock);
23084 	}
23085 
23086 	if (stq) {
23087 		/*
23088 		 * A non-NULL send-to queue means this packet is going
23089 		 * out of this machine.
23090 		 */
23091 		out_ill = (ill_t *)stq->q_ptr;
23092 
23093 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
23094 		ttl_protocol = ((uint16_t *)ipha)[4];
23095 		/*
23096 		 * We accumulate the pseudo header checksum in cksum.
23097 		 * This is pretty hairy code, so watch close.  One
23098 		 * thing to keep in mind is that UDP and TCP have
23099 		 * stored their respective datagram lengths in their
23100 		 * checksum fields.  This lines things up real nice.
23101 		 */
23102 		cksum = (dst >> 16) + (dst & 0xFFFF) +
23103 		    (src >> 16) + (src & 0xFFFF);
23104 		/*
23105 		 * We assume the udp checksum field contains the
23106 		 * length, so to compute the pseudo header checksum,
23107 		 * all we need is the protocol number and src/dst.
23108 		 */
23109 		/* Provide the checksums for UDP and TCP. */
23110 		if ((PROTO == IPPROTO_TCP) &&
23111 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
23112 			/* hlen gets the number of uchar_ts in the IP header */
23113 			hlen = (V_HLEN & 0xF) << 2;
23114 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
23115 			IP_STAT(ipst, ip_out_sw_cksum);
23116 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
23117 			    LENGTH - hlen);
23118 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
23119 		} else if (PROTO == IPPROTO_SCTP &&
23120 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
23121 			sctp_hdr_t	*sctph;
23122 
23123 			hlen = (V_HLEN & 0xF) << 2;
23124 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
23125 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
23126 			sctph->sh_chksum = 0;
23127 #ifdef	DEBUG
23128 			if (!skip_sctp_cksum)
23129 #endif
23130 				sctph->sh_chksum = sctp_cksum(mp, hlen);
23131 		} else {
23132 			queue_t *dev_q = stq->q_next;
23133 
23134 			if ((dev_q->q_next || dev_q->q_first) &&
23135 			    !canput(dev_q)) {
23136 blocked:
23137 				ipha->ipha_ident = ip_hdr_included;
23138 				/*
23139 				 * If we don't have a conn to apply
23140 				 * backpressure, free the message.
23141 				 * In the ire_send path, we don't know
23142 				 * the position to requeue the packet. Rather
23143 				 * than reorder packets, we just drop this
23144 				 * packet.
23145 				 */
23146 				if (ipst->ips_ip_output_queue &&
23147 				    connp != NULL &&
23148 				    caller != IRE_SEND) {
23149 					if (caller == IP_WSRV) {
23150 						connp->conn_did_putbq = 1;
23151 						(void) putbq(connp->conn_wq,
23152 						    first_mp);
23153 						conn_drain_insert(connp);
23154 						/*
23155 						 * This is the service thread,
23156 						 * and the queue is already
23157 						 * noenabled. The check for
23158 						 * canput and the putbq is not
23159 						 * atomic. So we need to check
23160 						 * again.
23161 						 */
23162 						if (canput(stq->q_next))
23163 							connp->conn_did_putbq
23164 							    = 0;
23165 						IP_STAT(ipst, ip_conn_flputbq);
23166 					} else {
23167 						/*
23168 						 * We are not the service proc.
23169 						 * ip_wsrv will be scheduled or
23170 						 * is already running.
23171 						 */
23172 						(void) putq(connp->conn_wq,
23173 						    first_mp);
23174 					}
23175 				} else {
23176 					out_ill = (ill_t *)stq->q_ptr;
23177 					BUMP_MIB(out_ill->ill_ip_mib,
23178 					    ipIfStatsOutDiscards);
23179 					freemsg(first_mp);
23180 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23181 					    "ip_wput_ire_end: q %p (%S)",
23182 					    q, "discard");
23183 				}
23184 				ire_refrele(ire);
23185 				if (next_mp) {
23186 					ire_refrele(ire1);
23187 					freemsg(next_mp);
23188 				}
23189 				if (conn_outgoing_ill != NULL)
23190 					ill_refrele(conn_outgoing_ill);
23191 				return;
23192 			}
23193 			if ((PROTO == IPPROTO_UDP) &&
23194 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
23195 				/*
23196 				 * hlen gets the number of uchar_ts in the
23197 				 * IP header
23198 				 */
23199 				hlen = (V_HLEN & 0xF) << 2;
23200 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
23201 				max_frag = ire->ire_max_frag;
23202 				if (*up != 0) {
23203 					IP_CKSUM_XMIT(ire_ill, ire, mp, ipha,
23204 					    up, PROTO, hlen, LENGTH, max_frag,
23205 					    ipsec_len, cksum);
23206 					/* Software checksum? */
23207 					if (DB_CKSUMFLAGS(mp) == 0) {
23208 						IP_STAT(ipst, ip_out_sw_cksum);
23209 						IP_STAT_UPDATE(ipst,
23210 						    ip_udp_out_sw_cksum_bytes,
23211 						    LENGTH - hlen);
23212 					}
23213 				}
23214 			}
23215 		}
23216 		/*
23217 		 * Need to do this even when fragmenting. The local
23218 		 * loopback can be done without computing checksums
23219 		 * but forwarding out other interface must be done
23220 		 * after the IP checksum (and ULP checksums) have been
23221 		 * computed.
23222 		 *
23223 		 * NOTE : multicast_forward is set only if this packet
23224 		 * originated from ip_wput. For packets originating from
23225 		 * ip_wput_multicast, it is not set.
23226 		 */
23227 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
23228 multi_loopback:
23229 			ip2dbg(("ip_wput: multicast, loop %d\n",
23230 			    conn_multicast_loop));
23231 
23232 			/*  Forget header checksum offload */
23233 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
23234 
23235 			/*
23236 			 * Local loopback of multicasts?  Check the
23237 			 * ill.
23238 			 *
23239 			 * Note that the loopback function will not come
23240 			 * in through ip_rput - it will only do the
23241 			 * client fanout thus we need to do an mforward
23242 			 * as well.  The is different from the BSD
23243 			 * logic.
23244 			 */
23245 			if (ill != NULL) {
23246 				ilm_t	*ilm;
23247 
23248 				ILM_WALKER_HOLD(ill);
23249 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
23250 				    ALL_ZONES);
23251 				ILM_WALKER_RELE(ill);
23252 				if (ilm != NULL) {
23253 					/*
23254 					 * Pass along the virtual output q.
23255 					 * ip_wput_local() will distribute the
23256 					 * packet to all the matching zones,
23257 					 * except the sending zone when
23258 					 * IP_MULTICAST_LOOP is false.
23259 					 */
23260 					ip_multicast_loopback(q, ill, first_mp,
23261 					    conn_multicast_loop ? 0 :
23262 					    IP_FF_NO_MCAST_LOOP, zoneid);
23263 				}
23264 			}
23265 			if (ipha->ipha_ttl == 0) {
23266 				/*
23267 				 * 0 => only to this host i.e. we are
23268 				 * done. We are also done if this was the
23269 				 * loopback interface since it is sufficient
23270 				 * to loopback one copy of a multicast packet.
23271 				 */
23272 				freemsg(first_mp);
23273 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23274 				    "ip_wput_ire_end: q %p (%S)",
23275 				    q, "loopback");
23276 				ire_refrele(ire);
23277 				if (conn_outgoing_ill != NULL)
23278 					ill_refrele(conn_outgoing_ill);
23279 				return;
23280 			}
23281 			/*
23282 			 * ILLF_MULTICAST is checked in ip_newroute
23283 			 * i.e. we don't need to check it here since
23284 			 * all IRE_CACHEs come from ip_newroute.
23285 			 * For multicast traffic, SO_DONTROUTE is interpreted
23286 			 * to mean only send the packet out the interface
23287 			 * (optionally specified with IP_MULTICAST_IF)
23288 			 * and do not forward it out additional interfaces.
23289 			 * RSVP and the rsvp daemon is an example of a
23290 			 * protocol and user level process that
23291 			 * handles it's own routing. Hence, it uses the
23292 			 * SO_DONTROUTE option to accomplish this.
23293 			 */
23294 
23295 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
23296 			    ill != NULL) {
23297 				/* Unconditionally redo the checksum */
23298 				ipha->ipha_hdr_checksum = 0;
23299 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23300 
23301 				/*
23302 				 * If this needs to go out secure, we need
23303 				 * to wait till we finish the IPSEC
23304 				 * processing.
23305 				 */
23306 				if (ipsec_len == 0 &&
23307 				    ip_mforward(ill, ipha, mp)) {
23308 					freemsg(first_mp);
23309 					ip1dbg(("ip_wput: mforward failed\n"));
23310 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23311 					    "ip_wput_ire_end: q %p (%S)",
23312 					    q, "mforward failed");
23313 					ire_refrele(ire);
23314 					if (conn_outgoing_ill != NULL)
23315 						ill_refrele(conn_outgoing_ill);
23316 					return;
23317 				}
23318 			}
23319 		}
23320 		max_frag = ire->ire_max_frag;
23321 		cksum += ttl_protocol;
23322 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
23323 			/* No fragmentation required for this one. */
23324 			/*
23325 			 * Don't use frag_flag if packet is pre-built or source
23326 			 * routed or if multicast (since multicast packets do
23327 			 * not solicit ICMP "packet too big" messages).
23328 			 */
23329 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
23330 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
23331 			    !ip_source_route_included(ipha)) &&
23332 			    !CLASSD(ipha->ipha_dst))
23333 				ipha->ipha_fragment_offset_and_flags |=
23334 				    htons(ire->ire_frag_flag);
23335 
23336 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
23337 				/* Complete the IP header checksum. */
23338 				cksum += ipha->ipha_ident;
23339 				cksum += (v_hlen_tos_len >> 16)+
23340 				    (v_hlen_tos_len & 0xFFFF);
23341 				cksum += ipha->ipha_fragment_offset_and_flags;
23342 				hlen = (V_HLEN & 0xF) -
23343 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
23344 				if (hlen) {
23345 checksumoptions:
23346 					/*
23347 					 * Account for the IP Options in the IP
23348 					 * header checksum.
23349 					 */
23350 					up = (uint16_t *)(rptr+
23351 					    IP_SIMPLE_HDR_LENGTH);
23352 					do {
23353 						cksum += up[0];
23354 						cksum += up[1];
23355 						up += 2;
23356 					} while (--hlen);
23357 				}
23358 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
23359 				cksum = ~(cksum + (cksum >> 16));
23360 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
23361 			}
23362 			if (ipsec_len != 0) {
23363 				ipsec_out_process(q, first_mp, ire, ill_index);
23364 				if (!next_mp) {
23365 					ire_refrele(ire);
23366 					if (conn_outgoing_ill != NULL)
23367 						ill_refrele(conn_outgoing_ill);
23368 					return;
23369 				}
23370 				goto next;
23371 			}
23372 
23373 			/*
23374 			 * multirt_send has already been handled
23375 			 * for broadcast, but not yet for multicast
23376 			 * or IP options.
23377 			 */
23378 			if (next_mp == NULL) {
23379 				if (ire->ire_flags & RTF_MULTIRT) {
23380 					multirt_send = B_TRUE;
23381 				}
23382 			}
23383 
23384 			/*
23385 			 * In most cases, the emission loop below is
23386 			 * entered only once. Only in the case where
23387 			 * the ire holds the RTF_MULTIRT flag, do we loop
23388 			 * to process all RTF_MULTIRT ires in the bucket,
23389 			 * and send the packet through all crossed
23390 			 * RTF_MULTIRT routes.
23391 			 */
23392 			do {
23393 				if (multirt_send) {
23394 					irb_t *irb;
23395 
23396 					irb = ire->ire_bucket;
23397 					ASSERT(irb != NULL);
23398 					/*
23399 					 * We are in a multiple send case,
23400 					 * need to get the next IRE and make
23401 					 * a duplicate of the packet.
23402 					 */
23403 					IRB_REFHOLD(irb);
23404 					for (ire1 = ire->ire_next;
23405 					    ire1 != NULL;
23406 					    ire1 = ire1->ire_next) {
23407 						if (!(ire1->ire_flags &
23408 						    RTF_MULTIRT)) {
23409 							continue;
23410 						}
23411 						if (ire1->ire_addr !=
23412 						    ire->ire_addr) {
23413 							continue;
23414 						}
23415 						if (ire1->ire_marks &
23416 						    (IRE_MARK_CONDEMNED|
23417 						    IRE_MARK_HIDDEN)) {
23418 							continue;
23419 						}
23420 
23421 						/* Got one */
23422 						IRE_REFHOLD(ire1);
23423 						break;
23424 					}
23425 					IRB_REFRELE(irb);
23426 
23427 					if (ire1 != NULL) {
23428 						next_mp = copyb(mp);
23429 						if ((next_mp == NULL) ||
23430 						    ((mp->b_cont != NULL) &&
23431 						    ((next_mp->b_cont =
23432 						    dupmsg(mp->b_cont))
23433 						    == NULL))) {
23434 							freemsg(next_mp);
23435 							next_mp = NULL;
23436 							ire_refrele(ire1);
23437 							ire1 = NULL;
23438 						}
23439 					}
23440 
23441 					/*
23442 					 * Last multiroute ire; don't loop
23443 					 * anymore. The emission is over
23444 					 * and next_mp is NULL.
23445 					 */
23446 					if (ire1 == NULL) {
23447 						multirt_send = B_FALSE;
23448 					}
23449 				}
23450 
23451 				out_ill = ire->ire_ipif->ipif_ill;
23452 				DTRACE_PROBE4(ip4__physical__out__start,
23453 				    ill_t *, NULL,
23454 				    ill_t *, out_ill,
23455 				    ipha_t *, ipha, mblk_t *, mp);
23456 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23457 				    ipst->ips_ipv4firewall_physical_out,
23458 				    NULL, out_ill, ipha, mp, mp, ipst);
23459 				DTRACE_PROBE1(ip4__physical__out__end,
23460 				    mblk_t *, mp);
23461 				if (mp == NULL)
23462 					goto release_ire_and_ill_2;
23463 
23464 				ASSERT(ipsec_len == 0);
23465 				mp->b_prev =
23466 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23467 				DTRACE_PROBE2(ip__xmit__2,
23468 				    mblk_t *, mp, ire_t *, ire);
23469 				pktxmit_state = ip_xmit_v4(mp, ire,
23470 				    NULL, B_TRUE);
23471 				if ((pktxmit_state == SEND_FAILED) ||
23472 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23473 release_ire_and_ill_2:
23474 					if (next_mp) {
23475 						freemsg(next_mp);
23476 						ire_refrele(ire1);
23477 					}
23478 					ire_refrele(ire);
23479 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23480 					    "ip_wput_ire_end: q %p (%S)",
23481 					    q, "discard MDATA");
23482 					if (conn_outgoing_ill != NULL)
23483 						ill_refrele(conn_outgoing_ill);
23484 					return;
23485 				}
23486 
23487 				if (CLASSD(dst)) {
23488 					BUMP_MIB(out_ill->ill_ip_mib,
23489 					    ipIfStatsHCOutMcastPkts);
23490 					UPDATE_MIB(out_ill->ill_ip_mib,
23491 					    ipIfStatsHCOutMcastOctets,
23492 					    LENGTH);
23493 				} else if (ire->ire_type == IRE_BROADCAST) {
23494 					BUMP_MIB(out_ill->ill_ip_mib,
23495 					    ipIfStatsHCOutBcastPkts);
23496 				}
23497 
23498 				if (multirt_send) {
23499 					/*
23500 					 * We are in a multiple send case,
23501 					 * need to re-enter the sending loop
23502 					 * using the next ire.
23503 					 */
23504 					ire_refrele(ire);
23505 					ire = ire1;
23506 					stq = ire->ire_stq;
23507 					mp = next_mp;
23508 					next_mp = NULL;
23509 					ipha = (ipha_t *)mp->b_rptr;
23510 					ill_index = Q_TO_INDEX(stq);
23511 				}
23512 			} while (multirt_send);
23513 
23514 			if (!next_mp) {
23515 				/*
23516 				 * Last copy going out (the ultra-common
23517 				 * case).  Note that we intentionally replicate
23518 				 * the putnext rather than calling it before
23519 				 * the next_mp check in hopes of a little
23520 				 * tail-call action out of the compiler.
23521 				 */
23522 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23523 				    "ip_wput_ire_end: q %p (%S)",
23524 				    q, "last copy out(1)");
23525 				ire_refrele(ire);
23526 				if (conn_outgoing_ill != NULL)
23527 					ill_refrele(conn_outgoing_ill);
23528 				return;
23529 			}
23530 			/* More copies going out below. */
23531 		} else {
23532 			int offset;
23533 fragmentit:
23534 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23535 			/*
23536 			 * If this would generate a icmp_frag_needed message,
23537 			 * we need to handle it before we do the IPSEC
23538 			 * processing. Otherwise, we need to strip the IPSEC
23539 			 * headers before we send up the message to the ULPs
23540 			 * which becomes messy and difficult.
23541 			 */
23542 			if (ipsec_len != 0) {
23543 				if ((max_frag < (unsigned int)(LENGTH +
23544 				    ipsec_len)) && (offset & IPH_DF)) {
23545 					out_ill = (ill_t *)stq->q_ptr;
23546 					BUMP_MIB(out_ill->ill_ip_mib,
23547 					    ipIfStatsOutFragFails);
23548 					BUMP_MIB(out_ill->ill_ip_mib,
23549 					    ipIfStatsOutFragReqds);
23550 					ipha->ipha_hdr_checksum = 0;
23551 					ipha->ipha_hdr_checksum =
23552 					    (uint16_t)ip_csum_hdr(ipha);
23553 					icmp_frag_needed(ire->ire_stq, first_mp,
23554 					    max_frag, zoneid, ipst);
23555 					if (!next_mp) {
23556 						ire_refrele(ire);
23557 						if (conn_outgoing_ill != NULL) {
23558 							ill_refrele(
23559 							    conn_outgoing_ill);
23560 						}
23561 						return;
23562 					}
23563 				} else {
23564 					/*
23565 					 * This won't cause a icmp_frag_needed
23566 					 * message. to be generated. Send it on
23567 					 * the wire. Note that this could still
23568 					 * cause fragmentation and all we
23569 					 * do is the generation of the message
23570 					 * to the ULP if needed before IPSEC.
23571 					 */
23572 					if (!next_mp) {
23573 						ipsec_out_process(q, first_mp,
23574 						    ire, ill_index);
23575 						TRACE_2(TR_FAC_IP,
23576 						    TR_IP_WPUT_IRE_END,
23577 						    "ip_wput_ire_end: q %p "
23578 						    "(%S)", q,
23579 						    "last ipsec_out_process");
23580 						ire_refrele(ire);
23581 						if (conn_outgoing_ill != NULL) {
23582 							ill_refrele(
23583 							    conn_outgoing_ill);
23584 						}
23585 						return;
23586 					}
23587 					ipsec_out_process(q, first_mp,
23588 					    ire, ill_index);
23589 				}
23590 			} else {
23591 				/*
23592 				 * Initiate IPPF processing. For
23593 				 * fragmentable packets we finish
23594 				 * all QOS packet processing before
23595 				 * calling:
23596 				 * ip_wput_ire_fragmentit->ip_wput_frag
23597 				 */
23598 
23599 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23600 					ip_process(IPP_LOCAL_OUT, &mp,
23601 					    ill_index);
23602 					if (mp == NULL) {
23603 						out_ill = (ill_t *)stq->q_ptr;
23604 						BUMP_MIB(out_ill->ill_ip_mib,
23605 						    ipIfStatsOutDiscards);
23606 						if (next_mp != NULL) {
23607 							freemsg(next_mp);
23608 							ire_refrele(ire1);
23609 						}
23610 						ire_refrele(ire);
23611 						TRACE_2(TR_FAC_IP,
23612 						    TR_IP_WPUT_IRE_END,
23613 						    "ip_wput_ire: q %p (%S)",
23614 						    q, "discard MDATA");
23615 						if (conn_outgoing_ill != NULL) {
23616 							ill_refrele(
23617 							    conn_outgoing_ill);
23618 						}
23619 						return;
23620 					}
23621 				}
23622 				if (!next_mp) {
23623 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23624 					    "ip_wput_ire_end: q %p (%S)",
23625 					    q, "last fragmentation");
23626 					ip_wput_ire_fragmentit(mp, ire,
23627 					    zoneid, ipst);
23628 					ire_refrele(ire);
23629 					if (conn_outgoing_ill != NULL)
23630 						ill_refrele(conn_outgoing_ill);
23631 					return;
23632 				}
23633 				ip_wput_ire_fragmentit(mp, ire, zoneid, ipst);
23634 			}
23635 		}
23636 	} else {
23637 nullstq:
23638 		/* A NULL stq means the destination address is local. */
23639 		UPDATE_OB_PKT_COUNT(ire);
23640 		ire->ire_last_used_time = lbolt;
23641 		ASSERT(ire->ire_ipif != NULL);
23642 		if (!next_mp) {
23643 			/*
23644 			 * Is there an "in" and "out" for traffic local
23645 			 * to a host (loopback)?  The code in Solaris doesn't
23646 			 * explicitly draw a line in its code for in vs out,
23647 			 * so we've had to draw a line in the sand: ip_wput_ire
23648 			 * is considered to be the "output" side and
23649 			 * ip_wput_local to be the "input" side.
23650 			 */
23651 			out_ill = ire->ire_ipif->ipif_ill;
23652 
23653 			DTRACE_PROBE4(ip4__loopback__out__start,
23654 			    ill_t *, NULL, ill_t *, out_ill,
23655 			    ipha_t *, ipha, mblk_t *, first_mp);
23656 
23657 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23658 			    ipst->ips_ipv4firewall_loopback_out,
23659 			    NULL, out_ill, ipha, first_mp, mp, ipst);
23660 
23661 			DTRACE_PROBE1(ip4__loopback__out_end,
23662 			    mblk_t *, first_mp);
23663 
23664 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23665 			    "ip_wput_ire_end: q %p (%S)",
23666 			    q, "local address");
23667 
23668 			if (first_mp != NULL)
23669 				ip_wput_local(q, out_ill, ipha,
23670 				    first_mp, ire, 0, ire->ire_zoneid);
23671 			ire_refrele(ire);
23672 			if (conn_outgoing_ill != NULL)
23673 				ill_refrele(conn_outgoing_ill);
23674 			return;
23675 		}
23676 
23677 		out_ill = ire->ire_ipif->ipif_ill;
23678 
23679 		DTRACE_PROBE4(ip4__loopback__out__start,
23680 		    ill_t *, NULL, ill_t *, out_ill,
23681 		    ipha_t *, ipha, mblk_t *, first_mp);
23682 
23683 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23684 		    ipst->ips_ipv4firewall_loopback_out,
23685 		    NULL, out_ill, ipha, first_mp, mp, ipst);
23686 
23687 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23688 
23689 		if (first_mp != NULL)
23690 			ip_wput_local(q, out_ill, ipha,
23691 			    first_mp, ire, 0, ire->ire_zoneid);
23692 	}
23693 next:
23694 	/*
23695 	 * More copies going out to additional interfaces.
23696 	 * ire1 has already been held. We don't need the
23697 	 * "ire" anymore.
23698 	 */
23699 	ire_refrele(ire);
23700 	ire = ire1;
23701 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23702 	mp = next_mp;
23703 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23704 	ill = ire_to_ill(ire);
23705 	first_mp = mp;
23706 	if (ipsec_len != 0) {
23707 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23708 		mp = mp->b_cont;
23709 	}
23710 	dst = ire->ire_addr;
23711 	ipha = (ipha_t *)mp->b_rptr;
23712 	/*
23713 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23714 	 * Restore ipha_ident "no checksum" flag.
23715 	 */
23716 	src = orig_src;
23717 	ipha->ipha_ident = ip_hdr_included;
23718 	goto another;
23719 
23720 #undef	rptr
23721 #undef	Q_TO_INDEX
23722 }
23723 
23724 /*
23725  * Routine to allocate a message that is used to notify the ULP about MDT.
23726  * The caller may provide a pointer to the link-layer MDT capabilities,
23727  * or NULL if MDT is to be disabled on the stream.
23728  */
23729 mblk_t *
23730 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23731 {
23732 	mblk_t *mp;
23733 	ip_mdt_info_t *mdti;
23734 	ill_mdt_capab_t *idst;
23735 
23736 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23737 		DB_TYPE(mp) = M_CTL;
23738 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23739 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23740 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23741 		idst = &(mdti->mdt_capab);
23742 
23743 		/*
23744 		 * If the caller provides us with the capability, copy
23745 		 * it over into our notification message; otherwise
23746 		 * we zero out the capability portion.
23747 		 */
23748 		if (isrc != NULL)
23749 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23750 		else
23751 			bzero((caddr_t)idst, sizeof (*idst));
23752 	}
23753 	return (mp);
23754 }
23755 
23756 /*
23757  * Routine which determines whether MDT can be enabled on the destination
23758  * IRE and IPC combination, and if so, allocates and returns the MDT
23759  * notification mblk that may be used by ULP.  We also check if we need to
23760  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23761  * MDT usage in the past have been lifted.  This gets called during IP
23762  * and ULP binding.
23763  */
23764 mblk_t *
23765 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23766     ill_mdt_capab_t *mdt_cap)
23767 {
23768 	mblk_t *mp;
23769 	boolean_t rc = B_FALSE;
23770 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23771 
23772 	ASSERT(dst_ire != NULL);
23773 	ASSERT(connp != NULL);
23774 	ASSERT(mdt_cap != NULL);
23775 
23776 	/*
23777 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23778 	 * Multidata, which is handled in tcp_multisend().  This
23779 	 * is the reason why we do all these checks here, to ensure
23780 	 * that we don't enable Multidata for the cases which we
23781 	 * can't handle at the moment.
23782 	 */
23783 	do {
23784 		/* Only do TCP at the moment */
23785 		if (connp->conn_ulp != IPPROTO_TCP)
23786 			break;
23787 
23788 		/*
23789 		 * IPSEC outbound policy present?  Note that we get here
23790 		 * after calling ipsec_conn_cache_policy() where the global
23791 		 * policy checking is performed.  conn_latch will be
23792 		 * non-NULL as long as there's a policy defined,
23793 		 * i.e. conn_out_enforce_policy may be NULL in such case
23794 		 * when the connection is non-secure, and hence we check
23795 		 * further if the latch refers to an outbound policy.
23796 		 */
23797 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23798 			break;
23799 
23800 		/* CGTP (multiroute) is enabled? */
23801 		if (dst_ire->ire_flags & RTF_MULTIRT)
23802 			break;
23803 
23804 		/* Outbound IPQoS enabled? */
23805 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23806 			/*
23807 			 * In this case, we disable MDT for this and all
23808 			 * future connections going over the interface.
23809 			 */
23810 			mdt_cap->ill_mdt_on = 0;
23811 			break;
23812 		}
23813 
23814 		/* socket option(s) present? */
23815 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23816 			break;
23817 
23818 		rc = B_TRUE;
23819 	/* CONSTCOND */
23820 	} while (0);
23821 
23822 	/* Remember the result */
23823 	connp->conn_mdt_ok = rc;
23824 
23825 	if (!rc)
23826 		return (NULL);
23827 	else if (!mdt_cap->ill_mdt_on) {
23828 		/*
23829 		 * If MDT has been previously turned off in the past, and we
23830 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23831 		 * then enable it for this interface.
23832 		 */
23833 		mdt_cap->ill_mdt_on = 1;
23834 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23835 		    "interface %s\n", ill_name));
23836 	}
23837 
23838 	/* Allocate the MDT info mblk */
23839 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23840 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23841 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23842 		return (NULL);
23843 	}
23844 	return (mp);
23845 }
23846 
23847 /*
23848  * Routine to allocate a message that is used to notify the ULP about LSO.
23849  * The caller may provide a pointer to the link-layer LSO capabilities,
23850  * or NULL if LSO is to be disabled on the stream.
23851  */
23852 mblk_t *
23853 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23854 {
23855 	mblk_t *mp;
23856 	ip_lso_info_t *lsoi;
23857 	ill_lso_capab_t *idst;
23858 
23859 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23860 		DB_TYPE(mp) = M_CTL;
23861 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23862 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23863 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23864 		idst = &(lsoi->lso_capab);
23865 
23866 		/*
23867 		 * If the caller provides us with the capability, copy
23868 		 * it over into our notification message; otherwise
23869 		 * we zero out the capability portion.
23870 		 */
23871 		if (isrc != NULL)
23872 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23873 		else
23874 			bzero((caddr_t)idst, sizeof (*idst));
23875 	}
23876 	return (mp);
23877 }
23878 
23879 /*
23880  * Routine which determines whether LSO can be enabled on the destination
23881  * IRE and IPC combination, and if so, allocates and returns the LSO
23882  * notification mblk that may be used by ULP.  We also check if we need to
23883  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23884  * LSO usage in the past have been lifted.  This gets called during IP
23885  * and ULP binding.
23886  */
23887 mblk_t *
23888 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23889     ill_lso_capab_t *lso_cap)
23890 {
23891 	mblk_t *mp;
23892 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23893 
23894 	ASSERT(dst_ire != NULL);
23895 	ASSERT(connp != NULL);
23896 	ASSERT(lso_cap != NULL);
23897 
23898 	connp->conn_lso_ok = B_TRUE;
23899 
23900 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23901 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23902 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23903 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23904 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23905 		connp->conn_lso_ok = B_FALSE;
23906 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23907 			/*
23908 			 * Disable LSO for this and all future connections going
23909 			 * over the interface.
23910 			 */
23911 			lso_cap->ill_lso_on = 0;
23912 		}
23913 	}
23914 
23915 	if (!connp->conn_lso_ok)
23916 		return (NULL);
23917 	else if (!lso_cap->ill_lso_on) {
23918 		/*
23919 		 * If LSO has been previously turned off in the past, and we
23920 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23921 		 * then enable it for this interface.
23922 		 */
23923 		lso_cap->ill_lso_on = 1;
23924 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23925 		    ill_name));
23926 	}
23927 
23928 	/* Allocate the LSO info mblk */
23929 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23930 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23931 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23932 
23933 	return (mp);
23934 }
23935 
23936 /*
23937  * Create destination address attribute, and fill it with the physical
23938  * destination address and SAP taken from the template DL_UNITDATA_REQ
23939  * message block.
23940  */
23941 boolean_t
23942 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23943 {
23944 	dl_unitdata_req_t *dlurp;
23945 	pattr_t *pa;
23946 	pattrinfo_t pa_info;
23947 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23948 	uint_t das_len, das_off;
23949 
23950 	ASSERT(dlmp != NULL);
23951 
23952 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23953 	das_len = dlurp->dl_dest_addr_length;
23954 	das_off = dlurp->dl_dest_addr_offset;
23955 
23956 	pa_info.type = PATTR_DSTADDRSAP;
23957 	pa_info.len = sizeof (**das) + das_len - 1;
23958 
23959 	/* create and associate the attribute */
23960 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23961 	if (pa != NULL) {
23962 		ASSERT(*das != NULL);
23963 		(*das)->addr_is_group = 0;
23964 		(*das)->addr_len = (uint8_t)das_len;
23965 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23966 	}
23967 
23968 	return (pa != NULL);
23969 }
23970 
23971 /*
23972  * Create hardware checksum attribute and fill it with the values passed.
23973  */
23974 boolean_t
23975 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23976     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23977 {
23978 	pattr_t *pa;
23979 	pattrinfo_t pa_info;
23980 
23981 	ASSERT(mmd != NULL);
23982 
23983 	pa_info.type = PATTR_HCKSUM;
23984 	pa_info.len = sizeof (pattr_hcksum_t);
23985 
23986 	/* create and associate the attribute */
23987 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23988 	if (pa != NULL) {
23989 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23990 
23991 		hck->hcksum_start_offset = start_offset;
23992 		hck->hcksum_stuff_offset = stuff_offset;
23993 		hck->hcksum_end_offset = end_offset;
23994 		hck->hcksum_flags = flags;
23995 	}
23996 	return (pa != NULL);
23997 }
23998 
23999 /*
24000  * Create zerocopy attribute and fill it with the specified flags
24001  */
24002 boolean_t
24003 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
24004 {
24005 	pattr_t *pa;
24006 	pattrinfo_t pa_info;
24007 
24008 	ASSERT(mmd != NULL);
24009 	pa_info.type = PATTR_ZCOPY;
24010 	pa_info.len = sizeof (pattr_zcopy_t);
24011 
24012 	/* create and associate the attribute */
24013 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
24014 	if (pa != NULL) {
24015 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
24016 
24017 		zcopy->zcopy_flags = flags;
24018 	}
24019 	return (pa != NULL);
24020 }
24021 
24022 /*
24023  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
24024  * block chain. We could rewrite to handle arbitrary message block chains but
24025  * that would make the code complicated and slow. Right now there three
24026  * restrictions:
24027  *
24028  *   1. The first message block must contain the complete IP header and
24029  *	at least 1 byte of payload data.
24030  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
24031  *	so that we can use a single Multidata message.
24032  *   3. No frag must be distributed over two or more message blocks so
24033  *	that we don't need more than two packet descriptors per frag.
24034  *
24035  * The above restrictions allow us to support userland applications (which
24036  * will send down a single message block) and NFS over UDP (which will
24037  * send down a chain of at most three message blocks).
24038  *
24039  * We also don't use MDT for payloads with less than or equal to
24040  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
24041  */
24042 boolean_t
24043 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
24044 {
24045 	int	blocks;
24046 	ssize_t	total, missing, size;
24047 
24048 	ASSERT(mp != NULL);
24049 	ASSERT(hdr_len > 0);
24050 
24051 	size = MBLKL(mp) - hdr_len;
24052 	if (size <= 0)
24053 		return (B_FALSE);
24054 
24055 	/* The first mblk contains the header and some payload. */
24056 	blocks = 1;
24057 	total = size;
24058 	size %= len;
24059 	missing = (size == 0) ? 0 : (len - size);
24060 	mp = mp->b_cont;
24061 
24062 	while (mp != NULL) {
24063 		/*
24064 		 * Give up if we encounter a zero length message block.
24065 		 * In practice, this should rarely happen and therefore
24066 		 * not worth the trouble of freeing and re-linking the
24067 		 * mblk from the chain to handle such case.
24068 		 */
24069 		if ((size = MBLKL(mp)) == 0)
24070 			return (B_FALSE);
24071 
24072 		/* Too many payload buffers for a single Multidata message? */
24073 		if (++blocks > MULTIDATA_MAX_PBUFS)
24074 			return (B_FALSE);
24075 
24076 		total += size;
24077 		/* Is a frag distributed over two or more message blocks? */
24078 		if (missing > size)
24079 			return (B_FALSE);
24080 		size -= missing;
24081 
24082 		size %= len;
24083 		missing = (size == 0) ? 0 : (len - size);
24084 
24085 		mp = mp->b_cont;
24086 	}
24087 
24088 	return (total > ip_wput_frag_mdt_min);
24089 }
24090 
24091 /*
24092  * Outbound IPv4 fragmentation routine using MDT.
24093  */
24094 static void
24095 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
24096     uint32_t frag_flag, int offset)
24097 {
24098 	ipha_t		*ipha_orig;
24099 	int		i1, ip_data_end;
24100 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
24101 	mblk_t		*hdr_mp, *md_mp = NULL;
24102 	unsigned char	*hdr_ptr, *pld_ptr;
24103 	multidata_t	*mmd;
24104 	ip_pdescinfo_t	pdi;
24105 	ill_t		*ill;
24106 	ip_stack_t	*ipst = ire->ire_ipst;
24107 
24108 	ASSERT(DB_TYPE(mp) == M_DATA);
24109 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
24110 
24111 	ill = ire_to_ill(ire);
24112 	ASSERT(ill != NULL);
24113 
24114 	ipha_orig = (ipha_t *)mp->b_rptr;
24115 	mp->b_rptr += sizeof (ipha_t);
24116 
24117 	/* Calculate how many packets we will send out */
24118 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
24119 	pkts = (i1 + len - 1) / len;
24120 	ASSERT(pkts > 1);
24121 
24122 	/* Allocate a message block which will hold all the IP Headers. */
24123 	wroff = ipst->ips_ip_wroff_extra;
24124 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
24125 
24126 	i1 = pkts * hdr_chunk_len;
24127 	/*
24128 	 * Create the header buffer, Multidata and destination address
24129 	 * and SAP attribute that should be associated with it.
24130 	 */
24131 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
24132 	    ((hdr_mp->b_wptr += i1),
24133 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
24134 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
24135 		freemsg(mp);
24136 		if (md_mp == NULL) {
24137 			freemsg(hdr_mp);
24138 		} else {
24139 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
24140 			freemsg(md_mp);
24141 		}
24142 		IP_STAT(ipst, ip_frag_mdt_allocfail);
24143 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
24144 		return;
24145 	}
24146 	IP_STAT(ipst, ip_frag_mdt_allocd);
24147 
24148 	/*
24149 	 * Add a payload buffer to the Multidata; this operation must not
24150 	 * fail, or otherwise our logic in this routine is broken.  There
24151 	 * is no memory allocation done by the routine, so any returned
24152 	 * failure simply tells us that we've done something wrong.
24153 	 *
24154 	 * A failure tells us that either we're adding the same payload
24155 	 * buffer more than once, or we're trying to add more buffers than
24156 	 * allowed.  None of the above cases should happen, and we panic
24157 	 * because either there's horrible heap corruption, and/or
24158 	 * programming mistake.
24159 	 */
24160 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24161 		goto pbuf_panic;
24162 
24163 	hdr_ptr = hdr_mp->b_rptr;
24164 	pld_ptr = mp->b_rptr;
24165 
24166 	/* Establish the ending byte offset, based on the starting offset. */
24167 	offset <<= 3;
24168 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
24169 	    IP_SIMPLE_HDR_LENGTH;
24170 
24171 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
24172 
24173 	while (pld_ptr < mp->b_wptr) {
24174 		ipha_t		*ipha;
24175 		uint16_t	offset_and_flags;
24176 		uint16_t	ip_len;
24177 		int		error;
24178 
24179 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
24180 		ipha = (ipha_t *)(hdr_ptr + wroff);
24181 		ASSERT(OK_32PTR(ipha));
24182 		*ipha = *ipha_orig;
24183 
24184 		if (ip_data_end - offset > len) {
24185 			offset_and_flags = IPH_MF;
24186 		} else {
24187 			/*
24188 			 * Last frag. Set len to the length of this last piece.
24189 			 */
24190 			len = ip_data_end - offset;
24191 			/* A frag of a frag might have IPH_MF non-zero */
24192 			offset_and_flags =
24193 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24194 			    IPH_MF;
24195 		}
24196 		offset_and_flags |= (uint16_t)(offset >> 3);
24197 		offset_and_flags |= (uint16_t)frag_flag;
24198 		/* Store the offset and flags in the IP header. */
24199 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24200 
24201 		/* Store the length in the IP header. */
24202 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
24203 		ipha->ipha_length = htons(ip_len);
24204 
24205 		/*
24206 		 * Set the IP header checksum.  Note that mp is just
24207 		 * the header, so this is easy to pass to ip_csum.
24208 		 */
24209 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24210 
24211 		/*
24212 		 * Record offset and size of header and data of the next packet
24213 		 * in the multidata message.
24214 		 */
24215 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
24216 		PDESC_PLD_INIT(&pdi);
24217 		i1 = MIN(mp->b_wptr - pld_ptr, len);
24218 		ASSERT(i1 > 0);
24219 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
24220 		if (i1 == len) {
24221 			pld_ptr += len;
24222 		} else {
24223 			i1 = len - i1;
24224 			mp = mp->b_cont;
24225 			ASSERT(mp != NULL);
24226 			ASSERT(MBLKL(mp) >= i1);
24227 			/*
24228 			 * Attach the next payload message block to the
24229 			 * multidata message.
24230 			 */
24231 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24232 				goto pbuf_panic;
24233 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
24234 			pld_ptr = mp->b_rptr + i1;
24235 		}
24236 
24237 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
24238 		    KM_NOSLEEP)) == NULL) {
24239 			/*
24240 			 * Any failure other than ENOMEM indicates that we
24241 			 * have passed in invalid pdesc info or parameters
24242 			 * to mmd_addpdesc, which must not happen.
24243 			 *
24244 			 * EINVAL is a result of failure on boundary checks
24245 			 * against the pdesc info contents.  It should not
24246 			 * happen, and we panic because either there's
24247 			 * horrible heap corruption, and/or programming
24248 			 * mistake.
24249 			 */
24250 			if (error != ENOMEM) {
24251 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
24252 				    "pdesc logic error detected for "
24253 				    "mmd %p pinfo %p (%d)\n",
24254 				    (void *)mmd, (void *)&pdi, error);
24255 				/* NOTREACHED */
24256 			}
24257 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
24258 			/* Free unattached payload message blocks as well */
24259 			md_mp->b_cont = mp->b_cont;
24260 			goto free_mmd;
24261 		}
24262 
24263 		/* Advance fragment offset. */
24264 		offset += len;
24265 
24266 		/* Advance to location for next header in the buffer. */
24267 		hdr_ptr += hdr_chunk_len;
24268 
24269 		/* Did we reach the next payload message block? */
24270 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
24271 			mp = mp->b_cont;
24272 			/*
24273 			 * Attach the next message block with payload
24274 			 * data to the multidata message.
24275 			 */
24276 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24277 				goto pbuf_panic;
24278 			pld_ptr = mp->b_rptr;
24279 		}
24280 	}
24281 
24282 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
24283 	ASSERT(mp->b_wptr == pld_ptr);
24284 
24285 	/* Update IP statistics */
24286 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
24287 
24288 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
24289 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
24290 
24291 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
24292 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
24293 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
24294 
24295 	if (pkt_type == OB_PKT) {
24296 		ire->ire_ob_pkt_count += pkts;
24297 		if (ire->ire_ipif != NULL)
24298 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
24299 	} else {
24300 		/*
24301 		 * The type is IB_PKT in the forwarding path and in
24302 		 * the mobile IP case when the packet is being reverse-
24303 		 * tunneled to the home agent.
24304 		 */
24305 		ire->ire_ib_pkt_count += pkts;
24306 		ASSERT(!IRE_IS_LOCAL(ire));
24307 		if (ire->ire_type & IRE_BROADCAST) {
24308 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
24309 		} else {
24310 			UPDATE_MIB(ill->ill_ip_mib,
24311 			    ipIfStatsHCOutForwDatagrams, pkts);
24312 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
24313 		}
24314 	}
24315 	ire->ire_last_used_time = lbolt;
24316 	/* Send it down */
24317 	putnext(ire->ire_stq, md_mp);
24318 	return;
24319 
24320 pbuf_panic:
24321 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
24322 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
24323 	    pbuf_idx);
24324 	/* NOTREACHED */
24325 }
24326 
24327 /*
24328  * Outbound IP fragmentation routine.
24329  *
24330  * NOTE : This routine does not ire_refrele the ire that is passed in
24331  * as the argument.
24332  */
24333 static void
24334 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
24335     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst)
24336 {
24337 	int		i1;
24338 	mblk_t		*ll_hdr_mp;
24339 	int 		ll_hdr_len;
24340 	int		hdr_len;
24341 	mblk_t		*hdr_mp;
24342 	ipha_t		*ipha;
24343 	int		ip_data_end;
24344 	int		len;
24345 	mblk_t		*mp = mp_orig, *mp1;
24346 	int		offset;
24347 	queue_t		*q;
24348 	uint32_t	v_hlen_tos_len;
24349 	mblk_t		*first_mp;
24350 	boolean_t	mctl_present;
24351 	ill_t		*ill;
24352 	ill_t		*out_ill;
24353 	mblk_t		*xmit_mp;
24354 	mblk_t		*carve_mp;
24355 	ire_t		*ire1 = NULL;
24356 	ire_t		*save_ire = NULL;
24357 	mblk_t  	*next_mp = NULL;
24358 	boolean_t	last_frag = B_FALSE;
24359 	boolean_t	multirt_send = B_FALSE;
24360 	ire_t		*first_ire = NULL;
24361 	irb_t		*irb = NULL;
24362 	mib2_ipIfStatsEntry_t *mibptr = NULL;
24363 
24364 	ill = ire_to_ill(ire);
24365 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
24366 
24367 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
24368 
24369 	if (max_frag == 0) {
24370 		ip1dbg(("ip_wput_frag: ire frag size is 0"
24371 		    " -  dropping packet\n"));
24372 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24373 		freemsg(mp);
24374 		return;
24375 	}
24376 
24377 	/*
24378 	 * IPSEC does not allow hw accelerated packets to be fragmented
24379 	 * This check is made in ip_wput_ipsec_out prior to coming here
24380 	 * via ip_wput_ire_fragmentit.
24381 	 *
24382 	 * If at this point we have an ire whose ARP request has not
24383 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24384 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24385 	 * This packet and all fragmentable packets for this ire will
24386 	 * continue to get dropped while ire_nce->nce_state remains in
24387 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24388 	 * ND_REACHABLE, all subsquent large packets for this ire will
24389 	 * get fragemented and sent out by this function.
24390 	 */
24391 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24392 		/* If nce_state is ND_INITIAL, trigger ARP query */
24393 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
24394 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24395 		    " -  dropping packet\n"));
24396 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24397 		freemsg(mp);
24398 		return;
24399 	}
24400 
24401 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24402 	    "ip_wput_frag_start:");
24403 
24404 	if (mp->b_datap->db_type == M_CTL) {
24405 		first_mp = mp;
24406 		mp_orig = mp = mp->b_cont;
24407 		mctl_present = B_TRUE;
24408 	} else {
24409 		first_mp = mp;
24410 		mctl_present = B_FALSE;
24411 	}
24412 
24413 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24414 	ipha = (ipha_t *)mp->b_rptr;
24415 
24416 	/*
24417 	 * If the Don't Fragment flag is on, generate an ICMP destination
24418 	 * unreachable, fragmentation needed.
24419 	 */
24420 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24421 	if (offset & IPH_DF) {
24422 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24423 		if (is_system_labeled()) {
24424 			max_frag = tsol_pmtu_adjust(mp, ire->ire_max_frag,
24425 			    ire->ire_max_frag - max_frag, AF_INET);
24426 		}
24427 		/*
24428 		 * Need to compute hdr checksum if called from ip_wput_ire.
24429 		 * Note that ip_rput_forward verifies the checksum before
24430 		 * calling this routine so in that case this is a noop.
24431 		 */
24432 		ipha->ipha_hdr_checksum = 0;
24433 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24434 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24435 		    ipst);
24436 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24437 		    "ip_wput_frag_end:(%S)",
24438 		    "don't fragment");
24439 		return;
24440 	}
24441 	/*
24442 	 * Labeled systems adjust max_frag if they add a label
24443 	 * to send the correct path mtu.  We need the real mtu since we
24444 	 * are fragmenting the packet after label adjustment.
24445 	 */
24446 	if (is_system_labeled())
24447 		max_frag = ire->ire_max_frag;
24448 	if (mctl_present)
24449 		freeb(first_mp);
24450 	/*
24451 	 * Establish the starting offset.  May not be zero if we are fragging
24452 	 * a fragment that is being forwarded.
24453 	 */
24454 	offset = offset & IPH_OFFSET;
24455 
24456 	/* TODO why is this test needed? */
24457 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24458 	if (((max_frag - LENGTH) & ~7) < 8) {
24459 		/* TODO: notify ulp somehow */
24460 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24461 		freemsg(mp);
24462 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24463 		    "ip_wput_frag_end:(%S)",
24464 		    "len < 8");
24465 		return;
24466 	}
24467 
24468 	hdr_len = (V_HLEN & 0xF) << 2;
24469 
24470 	ipha->ipha_hdr_checksum = 0;
24471 
24472 	/*
24473 	 * Establish the number of bytes maximum per frag, after putting
24474 	 * in the header.
24475 	 */
24476 	len = (max_frag - hdr_len) & ~7;
24477 
24478 	/* Check if we can use MDT to send out the frags. */
24479 	ASSERT(!IRE_IS_LOCAL(ire));
24480 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24481 	    ipst->ips_ip_multidata_outbound &&
24482 	    !(ire->ire_flags & RTF_MULTIRT) &&
24483 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24484 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24485 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24486 		ASSERT(ill->ill_mdt_capab != NULL);
24487 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24488 			/*
24489 			 * If MDT has been previously turned off in the past,
24490 			 * and we currently can do MDT (due to IPQoS policy
24491 			 * removal, etc.) then enable it for this interface.
24492 			 */
24493 			ill->ill_mdt_capab->ill_mdt_on = 1;
24494 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24495 			    ill->ill_name));
24496 		}
24497 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24498 		    offset);
24499 		return;
24500 	}
24501 
24502 	/* Get a copy of the header for the trailing frags */
24503 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst);
24504 	if (!hdr_mp) {
24505 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24506 		freemsg(mp);
24507 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24508 		    "ip_wput_frag_end:(%S)",
24509 		    "couldn't copy hdr");
24510 		return;
24511 	}
24512 	if (DB_CRED(mp) != NULL)
24513 		mblk_setcred(hdr_mp, DB_CRED(mp));
24514 
24515 	/* Store the starting offset, with the MoreFrags flag. */
24516 	i1 = offset | IPH_MF | frag_flag;
24517 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24518 
24519 	/* Establish the ending byte offset, based on the starting offset. */
24520 	offset <<= 3;
24521 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24522 
24523 	/* Store the length of the first fragment in the IP header. */
24524 	i1 = len + hdr_len;
24525 	ASSERT(i1 <= IP_MAXPACKET);
24526 	ipha->ipha_length = htons((uint16_t)i1);
24527 
24528 	/*
24529 	 * Compute the IP header checksum for the first frag.  We have to
24530 	 * watch out that we stop at the end of the header.
24531 	 */
24532 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24533 
24534 	/*
24535 	 * Now carve off the first frag.  Note that this will include the
24536 	 * original IP header.
24537 	 */
24538 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24539 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24540 		freeb(hdr_mp);
24541 		freemsg(mp_orig);
24542 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24543 		    "ip_wput_frag_end:(%S)",
24544 		    "couldn't carve first");
24545 		return;
24546 	}
24547 
24548 	/*
24549 	 * Multirouting case. Each fragment is replicated
24550 	 * via all non-condemned RTF_MULTIRT routes
24551 	 * currently resolved.
24552 	 * We ensure that first_ire is the first RTF_MULTIRT
24553 	 * ire in the bucket.
24554 	 */
24555 	if (ire->ire_flags & RTF_MULTIRT) {
24556 		irb = ire->ire_bucket;
24557 		ASSERT(irb != NULL);
24558 
24559 		multirt_send = B_TRUE;
24560 
24561 		/* Make sure we do not omit any multiroute ire. */
24562 		IRB_REFHOLD(irb);
24563 		for (first_ire = irb->irb_ire;
24564 		    first_ire != NULL;
24565 		    first_ire = first_ire->ire_next) {
24566 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24567 			    (first_ire->ire_addr == ire->ire_addr) &&
24568 			    !(first_ire->ire_marks &
24569 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
24570 				break;
24571 			}
24572 		}
24573 
24574 		if (first_ire != NULL) {
24575 			if (first_ire != ire) {
24576 				IRE_REFHOLD(first_ire);
24577 				/*
24578 				 * Do not release the ire passed in
24579 				 * as the argument.
24580 				 */
24581 				ire = first_ire;
24582 			} else {
24583 				first_ire = NULL;
24584 			}
24585 		}
24586 		IRB_REFRELE(irb);
24587 
24588 		/*
24589 		 * Save the first ire; we will need to restore it
24590 		 * for the trailing frags.
24591 		 * We REFHOLD save_ire, as each iterated ire will be
24592 		 * REFRELEd.
24593 		 */
24594 		save_ire = ire;
24595 		IRE_REFHOLD(save_ire);
24596 	}
24597 
24598 	/*
24599 	 * First fragment emission loop.
24600 	 * In most cases, the emission loop below is entered only
24601 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24602 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24603 	 * bucket, and send the fragment through all crossed
24604 	 * RTF_MULTIRT routes.
24605 	 */
24606 	do {
24607 		if (ire->ire_flags & RTF_MULTIRT) {
24608 			/*
24609 			 * We are in a multiple send case, need to get
24610 			 * the next ire and make a copy of the packet.
24611 			 * ire1 holds here the next ire to process in the
24612 			 * bucket. If multirouting is expected,
24613 			 * any non-RTF_MULTIRT ire that has the
24614 			 * right destination address is ignored.
24615 			 *
24616 			 * We have to take into account the MTU of
24617 			 * each walked ire. max_frag is set by the
24618 			 * the caller and generally refers to
24619 			 * the primary ire entry. Here we ensure that
24620 			 * no route with a lower MTU will be used, as
24621 			 * fragments are carved once for all ires,
24622 			 * then replicated.
24623 			 */
24624 			ASSERT(irb != NULL);
24625 			IRB_REFHOLD(irb);
24626 			for (ire1 = ire->ire_next;
24627 			    ire1 != NULL;
24628 			    ire1 = ire1->ire_next) {
24629 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24630 					continue;
24631 				if (ire1->ire_addr != ire->ire_addr)
24632 					continue;
24633 				if (ire1->ire_marks &
24634 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
24635 					continue;
24636 				/*
24637 				 * Ensure we do not exceed the MTU
24638 				 * of the next route.
24639 				 */
24640 				if (ire1->ire_max_frag < max_frag) {
24641 					ip_multirt_bad_mtu(ire1, max_frag);
24642 					continue;
24643 				}
24644 
24645 				/* Got one. */
24646 				IRE_REFHOLD(ire1);
24647 				break;
24648 			}
24649 			IRB_REFRELE(irb);
24650 
24651 			if (ire1 != NULL) {
24652 				next_mp = copyb(mp);
24653 				if ((next_mp == NULL) ||
24654 				    ((mp->b_cont != NULL) &&
24655 				    ((next_mp->b_cont =
24656 				    dupmsg(mp->b_cont)) == NULL))) {
24657 					freemsg(next_mp);
24658 					next_mp = NULL;
24659 					ire_refrele(ire1);
24660 					ire1 = NULL;
24661 				}
24662 			}
24663 
24664 			/* Last multiroute ire; don't loop anymore. */
24665 			if (ire1 == NULL) {
24666 				multirt_send = B_FALSE;
24667 			}
24668 		}
24669 
24670 		ll_hdr_len = 0;
24671 		LOCK_IRE_FP_MP(ire);
24672 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24673 		if (ll_hdr_mp != NULL) {
24674 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24675 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24676 		} else {
24677 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24678 		}
24679 
24680 		/* If there is a transmit header, get a copy for this frag. */
24681 		/*
24682 		 * TODO: should check db_ref before calling ip_carve_mp since
24683 		 * it might give us a dup.
24684 		 */
24685 		if (!ll_hdr_mp) {
24686 			/* No xmit header. */
24687 			xmit_mp = mp;
24688 
24689 		/* We have a link-layer header that can fit in our mblk. */
24690 		} else if (mp->b_datap->db_ref == 1 &&
24691 		    ll_hdr_len != 0 &&
24692 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24693 			/* M_DATA fastpath */
24694 			mp->b_rptr -= ll_hdr_len;
24695 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24696 			xmit_mp = mp;
24697 
24698 		/* Corner case if copyb has failed */
24699 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24700 			UNLOCK_IRE_FP_MP(ire);
24701 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24702 			freeb(hdr_mp);
24703 			freemsg(mp);
24704 			freemsg(mp_orig);
24705 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24706 			    "ip_wput_frag_end:(%S)",
24707 			    "discard");
24708 
24709 			if (multirt_send) {
24710 				ASSERT(ire1);
24711 				ASSERT(next_mp);
24712 
24713 				freemsg(next_mp);
24714 				ire_refrele(ire1);
24715 			}
24716 			if (save_ire != NULL)
24717 				IRE_REFRELE(save_ire);
24718 
24719 			if (first_ire != NULL)
24720 				ire_refrele(first_ire);
24721 			return;
24722 
24723 		/*
24724 		 * Case of res_mp OR the fastpath mp can't fit
24725 		 * in the mblk
24726 		 */
24727 		} else {
24728 			xmit_mp->b_cont = mp;
24729 			if (DB_CRED(mp) != NULL)
24730 				mblk_setcred(xmit_mp, DB_CRED(mp));
24731 			/*
24732 			 * Get priority marking, if any.
24733 			 * We propagate the CoS marking from the
24734 			 * original packet that went to QoS processing
24735 			 * in ip_wput_ire to the newly carved mp.
24736 			 */
24737 			if (DB_TYPE(xmit_mp) == M_DATA)
24738 				xmit_mp->b_band = mp->b_band;
24739 		}
24740 		UNLOCK_IRE_FP_MP(ire);
24741 
24742 		q = ire->ire_stq;
24743 		out_ill = (ill_t *)q->q_ptr;
24744 
24745 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24746 
24747 		DTRACE_PROBE4(ip4__physical__out__start,
24748 		    ill_t *, NULL, ill_t *, out_ill,
24749 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24750 
24751 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24752 		    ipst->ips_ipv4firewall_physical_out,
24753 		    NULL, out_ill, ipha, xmit_mp, mp, ipst);
24754 
24755 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24756 
24757 		if (xmit_mp != NULL) {
24758 			putnext(q, xmit_mp);
24759 
24760 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24761 			UPDATE_MIB(out_ill->ill_ip_mib,
24762 			    ipIfStatsHCOutOctets, i1);
24763 
24764 			if (pkt_type != OB_PKT) {
24765 				/*
24766 				 * Update the packet count and MIB stats
24767 				 * of trailing RTF_MULTIRT ires.
24768 				 */
24769 				UPDATE_OB_PKT_COUNT(ire);
24770 				BUMP_MIB(out_ill->ill_ip_mib,
24771 				    ipIfStatsOutFragReqds);
24772 			}
24773 		}
24774 
24775 		if (multirt_send) {
24776 			/*
24777 			 * We are in a multiple send case; look for
24778 			 * the next ire and re-enter the loop.
24779 			 */
24780 			ASSERT(ire1);
24781 			ASSERT(next_mp);
24782 			/* REFRELE the current ire before looping */
24783 			ire_refrele(ire);
24784 			ire = ire1;
24785 			ire1 = NULL;
24786 			mp = next_mp;
24787 			next_mp = NULL;
24788 		}
24789 	} while (multirt_send);
24790 
24791 	ASSERT(ire1 == NULL);
24792 
24793 	/* Restore the original ire; we need it for the trailing frags */
24794 	if (save_ire != NULL) {
24795 		/* REFRELE the last iterated ire */
24796 		ire_refrele(ire);
24797 		/* save_ire has been REFHOLDed */
24798 		ire = save_ire;
24799 		save_ire = NULL;
24800 		q = ire->ire_stq;
24801 	}
24802 
24803 	if (pkt_type == OB_PKT) {
24804 		UPDATE_OB_PKT_COUNT(ire);
24805 	} else {
24806 		out_ill = (ill_t *)q->q_ptr;
24807 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24808 		UPDATE_IB_PKT_COUNT(ire);
24809 	}
24810 
24811 	/* Advance the offset to the second frag starting point. */
24812 	offset += len;
24813 	/*
24814 	 * Update hdr_len from the copied header - there might be less options
24815 	 * in the later fragments.
24816 	 */
24817 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24818 	/* Loop until done. */
24819 	for (;;) {
24820 		uint16_t	offset_and_flags;
24821 		uint16_t	ip_len;
24822 
24823 		if (ip_data_end - offset > len) {
24824 			/*
24825 			 * Carve off the appropriate amount from the original
24826 			 * datagram.
24827 			 */
24828 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24829 				mp = NULL;
24830 				break;
24831 			}
24832 			/*
24833 			 * More frags after this one.  Get another copy
24834 			 * of the header.
24835 			 */
24836 			if (carve_mp->b_datap->db_ref == 1 &&
24837 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24838 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24839 				/* Inline IP header */
24840 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24841 				    hdr_mp->b_rptr;
24842 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24843 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24844 				mp = carve_mp;
24845 			} else {
24846 				if (!(mp = copyb(hdr_mp))) {
24847 					freemsg(carve_mp);
24848 					break;
24849 				}
24850 				/* Get priority marking, if any. */
24851 				mp->b_band = carve_mp->b_band;
24852 				mp->b_cont = carve_mp;
24853 			}
24854 			ipha = (ipha_t *)mp->b_rptr;
24855 			offset_and_flags = IPH_MF;
24856 		} else {
24857 			/*
24858 			 * Last frag.  Consume the header. Set len to
24859 			 * the length of this last piece.
24860 			 */
24861 			len = ip_data_end - offset;
24862 
24863 			/*
24864 			 * Carve off the appropriate amount from the original
24865 			 * datagram.
24866 			 */
24867 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24868 				mp = NULL;
24869 				break;
24870 			}
24871 			if (carve_mp->b_datap->db_ref == 1 &&
24872 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24873 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24874 				/* Inline IP header */
24875 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24876 				    hdr_mp->b_rptr;
24877 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24878 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24879 				mp = carve_mp;
24880 				freeb(hdr_mp);
24881 				hdr_mp = mp;
24882 			} else {
24883 				mp = hdr_mp;
24884 				/* Get priority marking, if any. */
24885 				mp->b_band = carve_mp->b_band;
24886 				mp->b_cont = carve_mp;
24887 			}
24888 			ipha = (ipha_t *)mp->b_rptr;
24889 			/* A frag of a frag might have IPH_MF non-zero */
24890 			offset_and_flags =
24891 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24892 			    IPH_MF;
24893 		}
24894 		offset_and_flags |= (uint16_t)(offset >> 3);
24895 		offset_and_flags |= (uint16_t)frag_flag;
24896 		/* Store the offset and flags in the IP header. */
24897 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24898 
24899 		/* Store the length in the IP header. */
24900 		ip_len = (uint16_t)(len + hdr_len);
24901 		ipha->ipha_length = htons(ip_len);
24902 
24903 		/*
24904 		 * Set the IP header checksum.	Note that mp is just
24905 		 * the header, so this is easy to pass to ip_csum.
24906 		 */
24907 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24908 
24909 		/* Attach a transmit header, if any, and ship it. */
24910 		if (pkt_type == OB_PKT) {
24911 			UPDATE_OB_PKT_COUNT(ire);
24912 		} else {
24913 			out_ill = (ill_t *)q->q_ptr;
24914 			BUMP_MIB(out_ill->ill_ip_mib,
24915 			    ipIfStatsHCOutForwDatagrams);
24916 			UPDATE_IB_PKT_COUNT(ire);
24917 		}
24918 
24919 		if (ire->ire_flags & RTF_MULTIRT) {
24920 			irb = ire->ire_bucket;
24921 			ASSERT(irb != NULL);
24922 
24923 			multirt_send = B_TRUE;
24924 
24925 			/*
24926 			 * Save the original ire; we will need to restore it
24927 			 * for the tailing frags.
24928 			 */
24929 			save_ire = ire;
24930 			IRE_REFHOLD(save_ire);
24931 		}
24932 		/*
24933 		 * Emission loop for this fragment, similar
24934 		 * to what is done for the first fragment.
24935 		 */
24936 		do {
24937 			if (multirt_send) {
24938 				/*
24939 				 * We are in a multiple send case, need to get
24940 				 * the next ire and make a copy of the packet.
24941 				 */
24942 				ASSERT(irb != NULL);
24943 				IRB_REFHOLD(irb);
24944 				for (ire1 = ire->ire_next;
24945 				    ire1 != NULL;
24946 				    ire1 = ire1->ire_next) {
24947 					if (!(ire1->ire_flags & RTF_MULTIRT))
24948 						continue;
24949 					if (ire1->ire_addr != ire->ire_addr)
24950 						continue;
24951 					if (ire1->ire_marks &
24952 					    (IRE_MARK_CONDEMNED|
24953 					    IRE_MARK_HIDDEN)) {
24954 						continue;
24955 					}
24956 					/*
24957 					 * Ensure we do not exceed the MTU
24958 					 * of the next route.
24959 					 */
24960 					if (ire1->ire_max_frag < max_frag) {
24961 						ip_multirt_bad_mtu(ire1,
24962 						    max_frag);
24963 						continue;
24964 					}
24965 
24966 					/* Got one. */
24967 					IRE_REFHOLD(ire1);
24968 					break;
24969 				}
24970 				IRB_REFRELE(irb);
24971 
24972 				if (ire1 != NULL) {
24973 					next_mp = copyb(mp);
24974 					if ((next_mp == NULL) ||
24975 					    ((mp->b_cont != NULL) &&
24976 					    ((next_mp->b_cont =
24977 					    dupmsg(mp->b_cont)) == NULL))) {
24978 						freemsg(next_mp);
24979 						next_mp = NULL;
24980 						ire_refrele(ire1);
24981 						ire1 = NULL;
24982 					}
24983 				}
24984 
24985 				/* Last multiroute ire; don't loop anymore. */
24986 				if (ire1 == NULL) {
24987 					multirt_send = B_FALSE;
24988 				}
24989 			}
24990 
24991 			/* Update transmit header */
24992 			ll_hdr_len = 0;
24993 			LOCK_IRE_FP_MP(ire);
24994 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24995 			if (ll_hdr_mp != NULL) {
24996 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24997 				ll_hdr_len = MBLKL(ll_hdr_mp);
24998 			} else {
24999 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
25000 			}
25001 
25002 			if (!ll_hdr_mp) {
25003 				xmit_mp = mp;
25004 
25005 			/*
25006 			 * We have link-layer header that can fit in
25007 			 * our mblk.
25008 			 */
25009 			} else if (mp->b_datap->db_ref == 1 &&
25010 			    ll_hdr_len != 0 &&
25011 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
25012 				/* M_DATA fastpath */
25013 				mp->b_rptr -= ll_hdr_len;
25014 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
25015 				    ll_hdr_len);
25016 				xmit_mp = mp;
25017 
25018 			/*
25019 			 * Case of res_mp OR the fastpath mp can't fit
25020 			 * in the mblk
25021 			 */
25022 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
25023 				xmit_mp->b_cont = mp;
25024 				if (DB_CRED(mp) != NULL)
25025 					mblk_setcred(xmit_mp, DB_CRED(mp));
25026 				/* Get priority marking, if any. */
25027 				if (DB_TYPE(xmit_mp) == M_DATA)
25028 					xmit_mp->b_band = mp->b_band;
25029 
25030 			/* Corner case if copyb failed */
25031 			} else {
25032 				/*
25033 				 * Exit both the replication and
25034 				 * fragmentation loops.
25035 				 */
25036 				UNLOCK_IRE_FP_MP(ire);
25037 				goto drop_pkt;
25038 			}
25039 			UNLOCK_IRE_FP_MP(ire);
25040 
25041 			mp1 = mp;
25042 			out_ill = (ill_t *)q->q_ptr;
25043 
25044 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
25045 
25046 			DTRACE_PROBE4(ip4__physical__out__start,
25047 			    ill_t *, NULL, ill_t *, out_ill,
25048 			    ipha_t *, ipha, mblk_t *, xmit_mp);
25049 
25050 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
25051 			    ipst->ips_ipv4firewall_physical_out,
25052 			    NULL, out_ill, ipha, xmit_mp, mp, ipst);
25053 
25054 			DTRACE_PROBE1(ip4__physical__out__end,
25055 			    mblk_t *, xmit_mp);
25056 
25057 			if (mp != mp1 && hdr_mp == mp1)
25058 				hdr_mp = mp;
25059 			if (mp != mp1 && mp_orig == mp1)
25060 				mp_orig = mp;
25061 
25062 			if (xmit_mp != NULL) {
25063 				putnext(q, xmit_mp);
25064 
25065 				BUMP_MIB(out_ill->ill_ip_mib,
25066 				    ipIfStatsHCOutTransmits);
25067 				UPDATE_MIB(out_ill->ill_ip_mib,
25068 				    ipIfStatsHCOutOctets, ip_len);
25069 
25070 				if (pkt_type != OB_PKT) {
25071 					/*
25072 					 * Update the packet count of trailing
25073 					 * RTF_MULTIRT ires.
25074 					 */
25075 					UPDATE_OB_PKT_COUNT(ire);
25076 				}
25077 			}
25078 
25079 			/* All done if we just consumed the hdr_mp. */
25080 			if (mp == hdr_mp) {
25081 				last_frag = B_TRUE;
25082 				BUMP_MIB(out_ill->ill_ip_mib,
25083 				    ipIfStatsOutFragOKs);
25084 			}
25085 
25086 			if (multirt_send) {
25087 				/*
25088 				 * We are in a multiple send case; look for
25089 				 * the next ire and re-enter the loop.
25090 				 */
25091 				ASSERT(ire1);
25092 				ASSERT(next_mp);
25093 				/* REFRELE the current ire before looping */
25094 				ire_refrele(ire);
25095 				ire = ire1;
25096 				ire1 = NULL;
25097 				q = ire->ire_stq;
25098 				mp = next_mp;
25099 				next_mp = NULL;
25100 			}
25101 		} while (multirt_send);
25102 		/*
25103 		 * Restore the original ire; we need it for the
25104 		 * trailing frags
25105 		 */
25106 		if (save_ire != NULL) {
25107 			ASSERT(ire1 == NULL);
25108 			/* REFRELE the last iterated ire */
25109 			ire_refrele(ire);
25110 			/* save_ire has been REFHOLDed */
25111 			ire = save_ire;
25112 			q = ire->ire_stq;
25113 			save_ire = NULL;
25114 		}
25115 
25116 		if (last_frag) {
25117 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
25118 			    "ip_wput_frag_end:(%S)",
25119 			    "consumed hdr_mp");
25120 
25121 			if (first_ire != NULL)
25122 				ire_refrele(first_ire);
25123 			return;
25124 		}
25125 		/* Otherwise, advance and loop. */
25126 		offset += len;
25127 	}
25128 
25129 drop_pkt:
25130 	/* Clean up following allocation failure. */
25131 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
25132 	freemsg(mp);
25133 	if (mp != hdr_mp)
25134 		freeb(hdr_mp);
25135 	if (mp != mp_orig)
25136 		freemsg(mp_orig);
25137 
25138 	if (save_ire != NULL)
25139 		IRE_REFRELE(save_ire);
25140 	if (first_ire != NULL)
25141 		ire_refrele(first_ire);
25142 
25143 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
25144 	    "ip_wput_frag_end:(%S)",
25145 	    "end--alloc failure");
25146 }
25147 
25148 /*
25149  * Copy the header plus those options which have the copy bit set
25150  */
25151 static mblk_t *
25152 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst)
25153 {
25154 	mblk_t	*mp;
25155 	uchar_t	*up;
25156 
25157 	/*
25158 	 * Quick check if we need to look for options without the copy bit
25159 	 * set
25160 	 */
25161 	mp = allocb(ipst->ips_ip_wroff_extra + hdr_len, BPRI_HI);
25162 	if (!mp)
25163 		return (mp);
25164 	mp->b_rptr += ipst->ips_ip_wroff_extra;
25165 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
25166 		bcopy(rptr, mp->b_rptr, hdr_len);
25167 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
25168 		return (mp);
25169 	}
25170 	up  = mp->b_rptr;
25171 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
25172 	up += IP_SIMPLE_HDR_LENGTH;
25173 	rptr += IP_SIMPLE_HDR_LENGTH;
25174 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
25175 	while (hdr_len > 0) {
25176 		uint32_t optval;
25177 		uint32_t optlen;
25178 
25179 		optval = *rptr;
25180 		if (optval == IPOPT_EOL)
25181 			break;
25182 		if (optval == IPOPT_NOP)
25183 			optlen = 1;
25184 		else
25185 			optlen = rptr[1];
25186 		if (optval & IPOPT_COPY) {
25187 			bcopy(rptr, up, optlen);
25188 			up += optlen;
25189 		}
25190 		rptr += optlen;
25191 		hdr_len -= optlen;
25192 	}
25193 	/*
25194 	 * Make sure that we drop an even number of words by filling
25195 	 * with EOL to the next word boundary.
25196 	 */
25197 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
25198 	    hdr_len & 0x3; hdr_len++)
25199 		*up++ = IPOPT_EOL;
25200 	mp->b_wptr = up;
25201 	/* Update header length */
25202 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
25203 	return (mp);
25204 }
25205 
25206 /*
25207  * Delivery to local recipients including fanout to multiple recipients.
25208  * Does not do checksumming of UDP/TCP.
25209  * Note: q should be the read side queue for either the ill or conn.
25210  * Note: rq should be the read side q for the lower (ill) stream.
25211  * We don't send packets to IPPF processing, thus the last argument
25212  * to all the fanout calls are B_FALSE.
25213  */
25214 void
25215 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
25216     int fanout_flags, zoneid_t zoneid)
25217 {
25218 	uint32_t	protocol;
25219 	mblk_t		*first_mp;
25220 	boolean_t	mctl_present;
25221 	int		ire_type;
25222 #define	rptr	((uchar_t *)ipha)
25223 	ip_stack_t	*ipst = ill->ill_ipst;
25224 
25225 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
25226 	    "ip_wput_local_start: q %p", q);
25227 
25228 	if (ire != NULL) {
25229 		ire_type = ire->ire_type;
25230 	} else {
25231 		/*
25232 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
25233 		 * packet is not multicast, we can't tell the ire type.
25234 		 */
25235 		ASSERT(CLASSD(ipha->ipha_dst));
25236 		ire_type = IRE_BROADCAST;
25237 	}
25238 
25239 	first_mp = mp;
25240 	if (first_mp->b_datap->db_type == M_CTL) {
25241 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
25242 		if (!io->ipsec_out_secure) {
25243 			/*
25244 			 * This ipsec_out_t was allocated in ip_wput
25245 			 * for multicast packets to store the ill_index.
25246 			 * As this is being delivered locally, we don't
25247 			 * need this anymore.
25248 			 */
25249 			mp = first_mp->b_cont;
25250 			freeb(first_mp);
25251 			first_mp = mp;
25252 			mctl_present = B_FALSE;
25253 		} else {
25254 			/*
25255 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
25256 			 * security properties for the looped-back packet.
25257 			 */
25258 			mctl_present = B_TRUE;
25259 			mp = first_mp->b_cont;
25260 			ASSERT(mp != NULL);
25261 			ipsec_out_to_in(first_mp);
25262 		}
25263 	} else {
25264 		mctl_present = B_FALSE;
25265 	}
25266 
25267 	DTRACE_PROBE4(ip4__loopback__in__start,
25268 	    ill_t *, ill, ill_t *, NULL,
25269 	    ipha_t *, ipha, mblk_t *, first_mp);
25270 
25271 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
25272 	    ipst->ips_ipv4firewall_loopback_in,
25273 	    ill, NULL, ipha, first_mp, mp, ipst);
25274 
25275 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
25276 
25277 	if (first_mp == NULL)
25278 		return;
25279 
25280 	ipst->ips_loopback_packets++;
25281 
25282 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
25283 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
25284 	if (!IS_SIMPLE_IPH(ipha)) {
25285 		ip_wput_local_options(ipha, ipst);
25286 	}
25287 
25288 	protocol = ipha->ipha_protocol;
25289 	switch (protocol) {
25290 	case IPPROTO_ICMP: {
25291 		ire_t		*ire_zone;
25292 		ilm_t		*ilm;
25293 		mblk_t		*mp1;
25294 		zoneid_t	last_zoneid;
25295 
25296 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(ill)) {
25297 			ASSERT(ire_type == IRE_BROADCAST);
25298 			/*
25299 			 * In the multicast case, applications may have joined
25300 			 * the group from different zones, so we need to deliver
25301 			 * the packet to each of them. Loop through the
25302 			 * multicast memberships structures (ilm) on the receive
25303 			 * ill and send a copy of the packet up each matching
25304 			 * one. However, we don't do this for multicasts sent on
25305 			 * the loopback interface (PHYI_LOOPBACK flag set) as
25306 			 * they must stay in the sender's zone.
25307 			 *
25308 			 * ilm_add_v6() ensures that ilms in the same zone are
25309 			 * contiguous in the ill_ilm list. We use this property
25310 			 * to avoid sending duplicates needed when two
25311 			 * applications in the same zone join the same group on
25312 			 * different logical interfaces: we ignore the ilm if
25313 			 * it's zoneid is the same as the last matching one.
25314 			 * In addition, the sending of the packet for
25315 			 * ire_zoneid is delayed until all of the other ilms
25316 			 * have been exhausted.
25317 			 */
25318 			last_zoneid = -1;
25319 			ILM_WALKER_HOLD(ill);
25320 			for (ilm = ill->ill_ilm; ilm != NULL;
25321 			    ilm = ilm->ilm_next) {
25322 				if ((ilm->ilm_flags & ILM_DELETED) ||
25323 				    ipha->ipha_dst != ilm->ilm_addr ||
25324 				    ilm->ilm_zoneid == last_zoneid ||
25325 				    ilm->ilm_zoneid == zoneid ||
25326 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
25327 					continue;
25328 				mp1 = ip_copymsg(first_mp);
25329 				if (mp1 == NULL)
25330 					continue;
25331 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25332 				    mctl_present, B_FALSE, ill,
25333 				    ilm->ilm_zoneid);
25334 				last_zoneid = ilm->ilm_zoneid;
25335 			}
25336 			ILM_WALKER_RELE(ill);
25337 			/*
25338 			 * Loopback case: the sending endpoint has
25339 			 * IP_MULTICAST_LOOP disabled, therefore we don't
25340 			 * dispatch the multicast packet to the sending zone.
25341 			 */
25342 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
25343 				freemsg(first_mp);
25344 				return;
25345 			}
25346 		} else if (ire_type == IRE_BROADCAST) {
25347 			/*
25348 			 * In the broadcast case, there may be many zones
25349 			 * which need a copy of the packet delivered to them.
25350 			 * There is one IRE_BROADCAST per broadcast address
25351 			 * and per zone; we walk those using a helper function.
25352 			 * In addition, the sending of the packet for zoneid is
25353 			 * delayed until all of the other ires have been
25354 			 * processed.
25355 			 */
25356 			IRB_REFHOLD(ire->ire_bucket);
25357 			ire_zone = NULL;
25358 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25359 			    ire)) != NULL) {
25360 				mp1 = ip_copymsg(first_mp);
25361 				if (mp1 == NULL)
25362 					continue;
25363 
25364 				UPDATE_IB_PKT_COUNT(ire_zone);
25365 				ire_zone->ire_last_used_time = lbolt;
25366 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25367 				    mctl_present, B_FALSE, ill,
25368 				    ire_zone->ire_zoneid);
25369 			}
25370 			IRB_REFRELE(ire->ire_bucket);
25371 		}
25372 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25373 		    0, mctl_present, B_FALSE, ill, zoneid);
25374 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25375 		    "ip_wput_local_end: q %p (%S)",
25376 		    q, "icmp");
25377 		return;
25378 	}
25379 	case IPPROTO_IGMP:
25380 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25381 			/* Bad packet - discarded by igmp_input */
25382 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25383 			    "ip_wput_local_end: q %p (%S)",
25384 			    q, "igmp_input--bad packet");
25385 			if (mctl_present)
25386 				freeb(first_mp);
25387 			return;
25388 		}
25389 		/*
25390 		 * igmp_input() may have returned the pulled up message.
25391 		 * So first_mp and ipha need to be reinitialized.
25392 		 */
25393 		ipha = (ipha_t *)mp->b_rptr;
25394 		if (mctl_present)
25395 			first_mp->b_cont = mp;
25396 		else
25397 			first_mp = mp;
25398 		/* deliver to local raw users */
25399 		break;
25400 	case IPPROTO_ENCAP:
25401 		/*
25402 		 * This case is covered by either ip_fanout_proto, or by
25403 		 * the above security processing for self-tunneled packets.
25404 		 */
25405 		break;
25406 	case IPPROTO_UDP: {
25407 		uint16_t	*up;
25408 		uint32_t	ports;
25409 
25410 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25411 		    UDP_PORTS_OFFSET);
25412 		/* Force a 'valid' checksum. */
25413 		up[3] = 0;
25414 
25415 		ports = *(uint32_t *)up;
25416 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25417 		    (ire_type == IRE_BROADCAST),
25418 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25419 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25420 		    ill, zoneid);
25421 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25422 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25423 		return;
25424 	}
25425 	case IPPROTO_TCP: {
25426 
25427 		/*
25428 		 * For TCP, discard broadcast packets.
25429 		 */
25430 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25431 			freemsg(first_mp);
25432 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25433 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25434 			return;
25435 		}
25436 
25437 		if (mp->b_datap->db_type == M_DATA) {
25438 			/*
25439 			 * M_DATA mblk, so init mblk (chain) for no struio().
25440 			 */
25441 			mblk_t	*mp1 = mp;
25442 
25443 			do {
25444 				mp1->b_datap->db_struioflag = 0;
25445 			} while ((mp1 = mp1->b_cont) != NULL);
25446 		}
25447 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25448 		    <= mp->b_wptr);
25449 		ip_fanout_tcp(q, first_mp, ill, ipha,
25450 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25451 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25452 		    mctl_present, B_FALSE, zoneid);
25453 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25454 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25455 		return;
25456 	}
25457 	case IPPROTO_SCTP:
25458 	{
25459 		uint32_t	ports;
25460 
25461 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25462 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25463 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25464 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25465 		return;
25466 	}
25467 
25468 	default:
25469 		break;
25470 	}
25471 	/*
25472 	 * Find a client for some other protocol.  We give
25473 	 * copies to multiple clients, if more than one is
25474 	 * bound.
25475 	 */
25476 	ip_fanout_proto(q, first_mp, ill, ipha,
25477 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25478 	    mctl_present, B_FALSE, ill, zoneid);
25479 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25480 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25481 #undef	rptr
25482 }
25483 
25484 /*
25485  * Update any source route, record route, or timestamp options.
25486  * Check that we are at end of strict source route.
25487  * The options have been sanity checked by ip_wput_options().
25488  */
25489 static void
25490 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25491 {
25492 	ipoptp_t	opts;
25493 	uchar_t		*opt;
25494 	uint8_t		optval;
25495 	uint8_t		optlen;
25496 	ipaddr_t	dst;
25497 	uint32_t	ts;
25498 	ire_t		*ire;
25499 	timestruc_t	now;
25500 
25501 	ip2dbg(("ip_wput_local_options\n"));
25502 	for (optval = ipoptp_first(&opts, ipha);
25503 	    optval != IPOPT_EOL;
25504 	    optval = ipoptp_next(&opts)) {
25505 		opt = opts.ipoptp_cur;
25506 		optlen = opts.ipoptp_len;
25507 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25508 		switch (optval) {
25509 			uint32_t off;
25510 		case IPOPT_SSRR:
25511 		case IPOPT_LSRR:
25512 			off = opt[IPOPT_OFFSET];
25513 			off--;
25514 			if (optlen < IP_ADDR_LEN ||
25515 			    off > optlen - IP_ADDR_LEN) {
25516 				/* End of source route */
25517 				break;
25518 			}
25519 			/*
25520 			 * This will only happen if two consecutive entries
25521 			 * in the source route contains our address or if
25522 			 * it is a packet with a loose source route which
25523 			 * reaches us before consuming the whole source route
25524 			 */
25525 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25526 			if (optval == IPOPT_SSRR) {
25527 				return;
25528 			}
25529 			/*
25530 			 * Hack: instead of dropping the packet truncate the
25531 			 * source route to what has been used by filling the
25532 			 * rest with IPOPT_NOP.
25533 			 */
25534 			opt[IPOPT_OLEN] = (uint8_t)off;
25535 			while (off < optlen) {
25536 				opt[off++] = IPOPT_NOP;
25537 			}
25538 			break;
25539 		case IPOPT_RR:
25540 			off = opt[IPOPT_OFFSET];
25541 			off--;
25542 			if (optlen < IP_ADDR_LEN ||
25543 			    off > optlen - IP_ADDR_LEN) {
25544 				/* No more room - ignore */
25545 				ip1dbg((
25546 				    "ip_wput_forward_options: end of RR\n"));
25547 				break;
25548 			}
25549 			dst = htonl(INADDR_LOOPBACK);
25550 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25551 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25552 			break;
25553 		case IPOPT_TS:
25554 			/* Insert timestamp if there is romm */
25555 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25556 			case IPOPT_TS_TSONLY:
25557 				off = IPOPT_TS_TIMELEN;
25558 				break;
25559 			case IPOPT_TS_PRESPEC:
25560 			case IPOPT_TS_PRESPEC_RFC791:
25561 				/* Verify that the address matched */
25562 				off = opt[IPOPT_OFFSET] - 1;
25563 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25564 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25565 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25566 				    ipst);
25567 				if (ire == NULL) {
25568 					/* Not for us */
25569 					break;
25570 				}
25571 				ire_refrele(ire);
25572 				/* FALLTHRU */
25573 			case IPOPT_TS_TSANDADDR:
25574 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25575 				break;
25576 			default:
25577 				/*
25578 				 * ip_*put_options should have already
25579 				 * dropped this packet.
25580 				 */
25581 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25582 				    "unknown IT - bug in ip_wput_options?\n");
25583 				return;	/* Keep "lint" happy */
25584 			}
25585 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25586 				/* Increase overflow counter */
25587 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25588 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25589 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25590 				    (off << 4);
25591 				break;
25592 			}
25593 			off = opt[IPOPT_OFFSET] - 1;
25594 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25595 			case IPOPT_TS_PRESPEC:
25596 			case IPOPT_TS_PRESPEC_RFC791:
25597 			case IPOPT_TS_TSANDADDR:
25598 				dst = htonl(INADDR_LOOPBACK);
25599 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25600 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25601 				/* FALLTHRU */
25602 			case IPOPT_TS_TSONLY:
25603 				off = opt[IPOPT_OFFSET] - 1;
25604 				/* Compute # of milliseconds since midnight */
25605 				gethrestime(&now);
25606 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25607 				    now.tv_nsec / (NANOSEC / MILLISEC);
25608 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25609 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25610 				break;
25611 			}
25612 			break;
25613 		}
25614 	}
25615 }
25616 
25617 /*
25618  * Send out a multicast packet on interface ipif.
25619  * The sender does not have an conn.
25620  * Caller verifies that this isn't a PHYI_LOOPBACK.
25621  */
25622 void
25623 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25624 {
25625 	ipha_t	*ipha;
25626 	ire_t	*ire;
25627 	ipaddr_t	dst;
25628 	mblk_t		*first_mp;
25629 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25630 
25631 	/* igmp_sendpkt always allocates a ipsec_out_t */
25632 	ASSERT(mp->b_datap->db_type == M_CTL);
25633 	ASSERT(!ipif->ipif_isv6);
25634 	ASSERT(!IS_LOOPBACK(ipif->ipif_ill));
25635 
25636 	first_mp = mp;
25637 	mp = first_mp->b_cont;
25638 	ASSERT(mp->b_datap->db_type == M_DATA);
25639 	ipha = (ipha_t *)mp->b_rptr;
25640 
25641 	/*
25642 	 * Find an IRE which matches the destination and the outgoing
25643 	 * queue (i.e. the outgoing interface.)
25644 	 */
25645 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25646 		dst = ipif->ipif_pp_dst_addr;
25647 	else
25648 		dst = ipha->ipha_dst;
25649 	/*
25650 	 * The source address has already been initialized by the
25651 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25652 	 * be sufficient rather than MATCH_IRE_IPIF.
25653 	 *
25654 	 * This function is used for sending IGMP packets. We need
25655 	 * to make sure that we send the packet out of the interface
25656 	 * (ipif->ipif_ill) where we joined the group. This is to
25657 	 * prevent from switches doing IGMP snooping to send us multicast
25658 	 * packets for a given group on the interface we have joined.
25659 	 * If we can't find an ire, igmp_sendpkt has already initialized
25660 	 * ipsec_out_attach_if so that this will not be load spread in
25661 	 * ip_newroute_ipif.
25662 	 */
25663 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25664 	    MATCH_IRE_ILL, ipst);
25665 	if (!ire) {
25666 		/*
25667 		 * Mark this packet to make it be delivered to
25668 		 * ip_wput_ire after the new ire has been
25669 		 * created.
25670 		 */
25671 		mp->b_prev = NULL;
25672 		mp->b_next = NULL;
25673 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25674 		    zoneid, &zero_info);
25675 		return;
25676 	}
25677 
25678 	/*
25679 	 * Honor the RTF_SETSRC flag; this is the only case
25680 	 * where we force this addr whatever the current src addr is,
25681 	 * because this address is set by igmp_sendpkt(), and
25682 	 * cannot be specified by any user.
25683 	 */
25684 	if (ire->ire_flags & RTF_SETSRC) {
25685 		ipha->ipha_src = ire->ire_src_addr;
25686 	}
25687 
25688 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25689 }
25690 
25691 /*
25692  * NOTE : This function does not ire_refrele the ire argument passed in.
25693  *
25694  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25695  * failure. The nce_fp_mp can vanish any time in the case of IRE_MIPRTUN
25696  * and IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25697  * the ire_lock to access the nce_fp_mp in this case.
25698  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25699  * prepending a fastpath message IPQoS processing must precede it, we also set
25700  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25701  * (IPQoS might have set the b_band for CoS marking).
25702  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25703  * must follow it so that IPQoS can mark the dl_priority field for CoS
25704  * marking, if needed.
25705  */
25706 static mblk_t *
25707 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
25708 {
25709 	uint_t	hlen;
25710 	ipha_t *ipha;
25711 	mblk_t *mp1;
25712 	boolean_t qos_done = B_FALSE;
25713 	uchar_t	*ll_hdr;
25714 	ip_stack_t	*ipst = ire->ire_ipst;
25715 
25716 #define	rptr	((uchar_t *)ipha)
25717 
25718 	ipha = (ipha_t *)mp->b_rptr;
25719 	hlen = 0;
25720 	LOCK_IRE_FP_MP(ire);
25721 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25722 		ASSERT(DB_TYPE(mp1) == M_DATA);
25723 		/* Initiate IPPF processing */
25724 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25725 			UNLOCK_IRE_FP_MP(ire);
25726 			ip_process(proc, &mp, ill_index);
25727 			if (mp == NULL)
25728 				return (NULL);
25729 
25730 			ipha = (ipha_t *)mp->b_rptr;
25731 			LOCK_IRE_FP_MP(ire);
25732 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25733 				qos_done = B_TRUE;
25734 				goto no_fp_mp;
25735 			}
25736 			ASSERT(DB_TYPE(mp1) == M_DATA);
25737 		}
25738 		hlen = MBLKL(mp1);
25739 		/*
25740 		 * Check if we have enough room to prepend fastpath
25741 		 * header
25742 		 */
25743 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25744 			ll_hdr = rptr - hlen;
25745 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25746 			/*
25747 			 * Set the b_rptr to the start of the link layer
25748 			 * header
25749 			 */
25750 			mp->b_rptr = ll_hdr;
25751 			mp1 = mp;
25752 		} else {
25753 			mp1 = copyb(mp1);
25754 			if (mp1 == NULL)
25755 				goto unlock_err;
25756 			mp1->b_band = mp->b_band;
25757 			mp1->b_cont = mp;
25758 			/*
25759 			 * certain system generated traffic may not
25760 			 * have cred/label in ip header block. This
25761 			 * is true even for a labeled system. But for
25762 			 * labeled traffic, inherit the label in the
25763 			 * new header.
25764 			 */
25765 			if (DB_CRED(mp) != NULL)
25766 				mblk_setcred(mp1, DB_CRED(mp));
25767 			/*
25768 			 * XXX disable ICK_VALID and compute checksum
25769 			 * here; can happen if nce_fp_mp changes and
25770 			 * it can't be copied now due to insufficient
25771 			 * space. (unlikely, fp mp can change, but it
25772 			 * does not increase in length)
25773 			 */
25774 		}
25775 		UNLOCK_IRE_FP_MP(ire);
25776 	} else {
25777 no_fp_mp:
25778 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25779 		if (mp1 == NULL) {
25780 unlock_err:
25781 			UNLOCK_IRE_FP_MP(ire);
25782 			freemsg(mp);
25783 			return (NULL);
25784 		}
25785 		UNLOCK_IRE_FP_MP(ire);
25786 		mp1->b_cont = mp;
25787 		/*
25788 		 * certain system generated traffic may not
25789 		 * have cred/label in ip header block. This
25790 		 * is true even for a labeled system. But for
25791 		 * labeled traffic, inherit the label in the
25792 		 * new header.
25793 		 */
25794 		if (DB_CRED(mp) != NULL)
25795 			mblk_setcred(mp1, DB_CRED(mp));
25796 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25797 			ip_process(proc, &mp1, ill_index);
25798 			if (mp1 == NULL)
25799 				return (NULL);
25800 		}
25801 	}
25802 	return (mp1);
25803 #undef rptr
25804 }
25805 
25806 /*
25807  * Finish the outbound IPsec processing for an IPv6 packet. This function
25808  * is called from ipsec_out_process() if the IPsec packet was processed
25809  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25810  * asynchronously.
25811  */
25812 void
25813 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25814     ire_t *ire_arg)
25815 {
25816 	in6_addr_t *v6dstp;
25817 	ire_t *ire;
25818 	mblk_t *mp;
25819 	ip6_t *ip6h1;
25820 	uint_t	ill_index;
25821 	ipsec_out_t *io;
25822 	boolean_t attach_if, hwaccel;
25823 	uint32_t flags = IP6_NO_IPPOLICY;
25824 	int match_flags;
25825 	zoneid_t zoneid;
25826 	boolean_t ill_need_rele = B_FALSE;
25827 	boolean_t ire_need_rele = B_FALSE;
25828 	ip_stack_t	*ipst;
25829 
25830 	mp = ipsec_mp->b_cont;
25831 	ip6h1 = (ip6_t *)mp->b_rptr;
25832 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25833 	ASSERT(io->ipsec_out_ns != NULL);
25834 	ipst = io->ipsec_out_ns->netstack_ip;
25835 	ill_index = io->ipsec_out_ill_index;
25836 	if (io->ipsec_out_reachable) {
25837 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25838 	}
25839 	attach_if = io->ipsec_out_attach_if;
25840 	hwaccel = io->ipsec_out_accelerated;
25841 	zoneid = io->ipsec_out_zoneid;
25842 	ASSERT(zoneid != ALL_ZONES);
25843 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25844 	/* Multicast addresses should have non-zero ill_index. */
25845 	v6dstp = &ip6h->ip6_dst;
25846 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25847 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25848 	ASSERT(!attach_if || ill_index != 0);
25849 	if (ill_index != 0) {
25850 		if (ill == NULL) {
25851 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
25852 			    B_TRUE, ipst);
25853 
25854 			/* Failure case frees things for us. */
25855 			if (ill == NULL)
25856 				return;
25857 
25858 			ill_need_rele = B_TRUE;
25859 		}
25860 		/*
25861 		 * If this packet needs to go out on a particular interface
25862 		 * honor it.
25863 		 */
25864 		if (attach_if) {
25865 			match_flags = MATCH_IRE_ILL;
25866 
25867 			/*
25868 			 * Check if we need an ire that will not be
25869 			 * looked up by anybody else i.e. HIDDEN.
25870 			 */
25871 			if (ill_is_probeonly(ill)) {
25872 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25873 			}
25874 		}
25875 	}
25876 	ASSERT(mp != NULL);
25877 
25878 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25879 		boolean_t unspec_src;
25880 		ipif_t	*ipif;
25881 
25882 		/*
25883 		 * Use the ill_index to get the right ill.
25884 		 */
25885 		unspec_src = io->ipsec_out_unspec_src;
25886 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25887 		if (ipif == NULL) {
25888 			if (ill_need_rele)
25889 				ill_refrele(ill);
25890 			freemsg(ipsec_mp);
25891 			return;
25892 		}
25893 
25894 		if (ire_arg != NULL) {
25895 			ire = ire_arg;
25896 		} else {
25897 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25898 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25899 			ire_need_rele = B_TRUE;
25900 		}
25901 		if (ire != NULL) {
25902 			ipif_refrele(ipif);
25903 			/*
25904 			 * XXX Do the multicast forwarding now, as the IPSEC
25905 			 * processing has been done.
25906 			 */
25907 			goto send;
25908 		}
25909 
25910 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25911 		mp->b_prev = NULL;
25912 		mp->b_next = NULL;
25913 
25914 		/*
25915 		 * If the IPsec packet was processed asynchronously,
25916 		 * drop it now.
25917 		 */
25918 		if (q == NULL) {
25919 			if (ill_need_rele)
25920 				ill_refrele(ill);
25921 			freemsg(ipsec_mp);
25922 			return;
25923 		}
25924 
25925 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
25926 		    unspec_src, zoneid);
25927 		ipif_refrele(ipif);
25928 	} else {
25929 		if (attach_if) {
25930 			ipif_t	*ipif;
25931 
25932 			ipif = ipif_get_next_ipif(NULL, ill);
25933 			if (ipif == NULL) {
25934 				if (ill_need_rele)
25935 					ill_refrele(ill);
25936 				freemsg(ipsec_mp);
25937 				return;
25938 			}
25939 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25940 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25941 			ire_need_rele = B_TRUE;
25942 			ipif_refrele(ipif);
25943 		} else {
25944 			if (ire_arg != NULL) {
25945 				ire = ire_arg;
25946 			} else {
25947 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL,
25948 				    ipst);
25949 				ire_need_rele = B_TRUE;
25950 			}
25951 		}
25952 		if (ire != NULL)
25953 			goto send;
25954 		/*
25955 		 * ire disappeared underneath.
25956 		 *
25957 		 * What we need to do here is the ip_newroute
25958 		 * logic to get the ire without doing the IPSEC
25959 		 * processing. Follow the same old path. But this
25960 		 * time, ip_wput or ire_add_then_send will call us
25961 		 * directly as all the IPSEC operations are done.
25962 		 */
25963 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25964 		mp->b_prev = NULL;
25965 		mp->b_next = NULL;
25966 
25967 		/*
25968 		 * If the IPsec packet was processed asynchronously,
25969 		 * drop it now.
25970 		 */
25971 		if (q == NULL) {
25972 			if (ill_need_rele)
25973 				ill_refrele(ill);
25974 			freemsg(ipsec_mp);
25975 			return;
25976 		}
25977 
25978 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25979 		    zoneid, ipst);
25980 	}
25981 	if (ill != NULL && ill_need_rele)
25982 		ill_refrele(ill);
25983 	return;
25984 send:
25985 	if (ill != NULL && ill_need_rele)
25986 		ill_refrele(ill);
25987 
25988 	/* Local delivery */
25989 	if (ire->ire_stq == NULL) {
25990 		ill_t	*out_ill;
25991 		ASSERT(q != NULL);
25992 
25993 		/* PFHooks: LOOPBACK_OUT */
25994 		out_ill = ire->ire_ipif->ipif_ill;
25995 
25996 		DTRACE_PROBE4(ip6__loopback__out__start,
25997 		    ill_t *, NULL, ill_t *, out_ill,
25998 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25999 
26000 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
26001 		    ipst->ips_ipv6firewall_loopback_out,
26002 		    NULL, out_ill, ip6h1, ipsec_mp, mp, ipst);
26003 
26004 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
26005 
26006 		if (ipsec_mp != NULL)
26007 			ip_wput_local_v6(RD(q), out_ill,
26008 			    ip6h, ipsec_mp, ire, 0);
26009 		if (ire_need_rele)
26010 			ire_refrele(ire);
26011 		return;
26012 	}
26013 	/*
26014 	 * Everything is done. Send it out on the wire.
26015 	 * We force the insertion of a fragment header using the
26016 	 * IPH_FRAG_HDR flag in two cases:
26017 	 * - after reception of an ICMPv6 "packet too big" message
26018 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
26019 	 * - for multirouted IPv6 packets, so that the receiver can
26020 	 *   discard duplicates according to their fragment identifier
26021 	 */
26022 	/* XXX fix flow control problems. */
26023 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
26024 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
26025 		if (hwaccel) {
26026 			/*
26027 			 * hardware acceleration does not handle these
26028 			 * "slow path" cases.
26029 			 */
26030 			/* IPsec KSTATS: should bump bean counter here. */
26031 			if (ire_need_rele)
26032 				ire_refrele(ire);
26033 			freemsg(ipsec_mp);
26034 			return;
26035 		}
26036 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
26037 		    (mp->b_cont ? msgdsize(mp) :
26038 		    mp->b_wptr - (uchar_t *)ip6h)) {
26039 			/* IPsec KSTATS: should bump bean counter here. */
26040 			ip0dbg(("Packet length mismatch: %d, %ld\n",
26041 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
26042 			    msgdsize(mp)));
26043 			if (ire_need_rele)
26044 				ire_refrele(ire);
26045 			freemsg(ipsec_mp);
26046 			return;
26047 		}
26048 		ASSERT(mp->b_prev == NULL);
26049 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
26050 		    ntohs(ip6h->ip6_plen) +
26051 		    IPV6_HDR_LEN, ire->ire_max_frag));
26052 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
26053 		    ire->ire_max_frag);
26054 	} else {
26055 		UPDATE_OB_PKT_COUNT(ire);
26056 		ire->ire_last_used_time = lbolt;
26057 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
26058 	}
26059 	if (ire_need_rele)
26060 		ire_refrele(ire);
26061 	freeb(ipsec_mp);
26062 }
26063 
26064 void
26065 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
26066 {
26067 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
26068 	da_ipsec_t *hada;	/* data attributes */
26069 	ill_t *ill = (ill_t *)q->q_ptr;
26070 
26071 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
26072 
26073 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
26074 		/* IPsec KSTATS: Bump lose counter here! */
26075 		freemsg(mp);
26076 		return;
26077 	}
26078 
26079 	/*
26080 	 * It's an IPsec packet that must be
26081 	 * accelerated by the Provider, and the
26082 	 * outbound ill is IPsec acceleration capable.
26083 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
26084 	 * to the ill.
26085 	 * IPsec KSTATS: should bump packet counter here.
26086 	 */
26087 
26088 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
26089 	if (hada_mp == NULL) {
26090 		/* IPsec KSTATS: should bump packet counter here. */
26091 		freemsg(mp);
26092 		return;
26093 	}
26094 
26095 	hada_mp->b_datap->db_type = M_CTL;
26096 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
26097 	hada_mp->b_cont = mp;
26098 
26099 	hada = (da_ipsec_t *)hada_mp->b_rptr;
26100 	bzero(hada, sizeof (da_ipsec_t));
26101 	hada->da_type = IPHADA_M_CTL;
26102 
26103 	putnext(q, hada_mp);
26104 }
26105 
26106 /*
26107  * Finish the outbound IPsec processing. This function is called from
26108  * ipsec_out_process() if the IPsec packet was processed
26109  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
26110  * asynchronously.
26111  */
26112 void
26113 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
26114     ire_t *ire_arg)
26115 {
26116 	uint32_t v_hlen_tos_len;
26117 	ipaddr_t	dst;
26118 	ipif_t	*ipif = NULL;
26119 	ire_t *ire;
26120 	ire_t *ire1 = NULL;
26121 	mblk_t *next_mp = NULL;
26122 	uint32_t max_frag;
26123 	boolean_t multirt_send = B_FALSE;
26124 	mblk_t *mp;
26125 	mblk_t *mp1;
26126 	ipha_t *ipha1;
26127 	uint_t	ill_index;
26128 	ipsec_out_t *io;
26129 	boolean_t attach_if;
26130 	int match_flags, offset;
26131 	irb_t *irb = NULL;
26132 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
26133 	zoneid_t zoneid;
26134 	uint32_t cksum;
26135 	uint16_t *up;
26136 	ipxmit_state_t	pktxmit_state;
26137 	ip_stack_t	*ipst;
26138 
26139 #ifdef	_BIG_ENDIAN
26140 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
26141 #else
26142 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
26143 #endif
26144 
26145 	mp = ipsec_mp->b_cont;
26146 	ipha1 = (ipha_t *)mp->b_rptr;
26147 	ASSERT(mp != NULL);
26148 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
26149 	dst = ipha->ipha_dst;
26150 
26151 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26152 	ill_index = io->ipsec_out_ill_index;
26153 	attach_if = io->ipsec_out_attach_if;
26154 	zoneid = io->ipsec_out_zoneid;
26155 	ASSERT(zoneid != ALL_ZONES);
26156 	ipst = io->ipsec_out_ns->netstack_ip;
26157 	ASSERT(io->ipsec_out_ns != NULL);
26158 
26159 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
26160 	if (ill_index != 0) {
26161 		if (ill == NULL) {
26162 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
26163 			    ill_index, B_FALSE, ipst);
26164 
26165 			/* Failure case frees things for us. */
26166 			if (ill == NULL)
26167 				return;
26168 
26169 			ill_need_rele = B_TRUE;
26170 		}
26171 		/*
26172 		 * If this packet needs to go out on a particular interface
26173 		 * honor it.
26174 		 */
26175 		if (attach_if) {
26176 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
26177 
26178 			/*
26179 			 * Check if we need an ire that will not be
26180 			 * looked up by anybody else i.e. HIDDEN.
26181 			 */
26182 			if (ill_is_probeonly(ill)) {
26183 				match_flags |= MATCH_IRE_MARK_HIDDEN;
26184 			}
26185 		}
26186 	}
26187 
26188 	if (CLASSD(dst)) {
26189 		boolean_t conn_dontroute;
26190 		/*
26191 		 * Use the ill_index to get the right ipif.
26192 		 */
26193 		conn_dontroute = io->ipsec_out_dontroute;
26194 		if (ill_index == 0)
26195 			ipif = ipif_lookup_group(dst, zoneid, ipst);
26196 		else
26197 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
26198 		if (ipif == NULL) {
26199 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
26200 			    " multicast\n"));
26201 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
26202 			freemsg(ipsec_mp);
26203 			goto done;
26204 		}
26205 		/*
26206 		 * ipha_src has already been intialized with the
26207 		 * value of the ipif in ip_wput. All we need now is
26208 		 * an ire to send this downstream.
26209 		 */
26210 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
26211 		    MBLK_GETLABEL(mp), match_flags, ipst);
26212 		if (ire != NULL) {
26213 			ill_t *ill1;
26214 			/*
26215 			 * Do the multicast forwarding now, as the IPSEC
26216 			 * processing has been done.
26217 			 */
26218 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
26219 			    (ill1 = ire_to_ill(ire))) {
26220 				if (ip_mforward(ill1, ipha, mp)) {
26221 					freemsg(ipsec_mp);
26222 					ip1dbg(("ip_wput_ipsec_out: mforward "
26223 					    "failed\n"));
26224 					ire_refrele(ire);
26225 					goto done;
26226 				}
26227 			}
26228 			goto send;
26229 		}
26230 
26231 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
26232 		mp->b_prev = NULL;
26233 		mp->b_next = NULL;
26234 
26235 		/*
26236 		 * If the IPsec packet was processed asynchronously,
26237 		 * drop it now.
26238 		 */
26239 		if (q == NULL) {
26240 			freemsg(ipsec_mp);
26241 			goto done;
26242 		}
26243 
26244 		/*
26245 		 * We may be using a wrong ipif to create the ire.
26246 		 * But it is okay as the source address is assigned
26247 		 * for the packet already. Next outbound packet would
26248 		 * create the IRE with the right IPIF in ip_wput.
26249 		 *
26250 		 * Also handle RTF_MULTIRT routes.
26251 		 */
26252 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
26253 		    zoneid, &zero_info);
26254 	} else {
26255 		if (attach_if) {
26256 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
26257 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
26258 		} else {
26259 			if (ire_arg != NULL) {
26260 				ire = ire_arg;
26261 				ire_need_rele = B_FALSE;
26262 			} else {
26263 				ire = ire_cache_lookup(dst, zoneid,
26264 				    MBLK_GETLABEL(mp), ipst);
26265 			}
26266 		}
26267 		if (ire != NULL) {
26268 			goto send;
26269 		}
26270 
26271 		/*
26272 		 * ire disappeared underneath.
26273 		 *
26274 		 * What we need to do here is the ip_newroute
26275 		 * logic to get the ire without doing the IPSEC
26276 		 * processing. Follow the same old path. But this
26277 		 * time, ip_wput or ire_add_then_put will call us
26278 		 * directly as all the IPSEC operations are done.
26279 		 */
26280 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
26281 		mp->b_prev = NULL;
26282 		mp->b_next = NULL;
26283 
26284 		/*
26285 		 * If the IPsec packet was processed asynchronously,
26286 		 * drop it now.
26287 		 */
26288 		if (q == NULL) {
26289 			freemsg(ipsec_mp);
26290 			goto done;
26291 		}
26292 
26293 		/*
26294 		 * Since we're going through ip_newroute() again, we
26295 		 * need to make sure we don't:
26296 		 *
26297 		 *	1.) Trigger the ASSERT() with the ipha_ident
26298 		 *	    overloading.
26299 		 *	2.) Redo transport-layer checksumming, since we've
26300 		 *	    already done all that to get this far.
26301 		 *
26302 		 * The easiest way not do either of the above is to set
26303 		 * the ipha_ident field to IP_HDR_INCLUDED.
26304 		 */
26305 		ipha->ipha_ident = IP_HDR_INCLUDED;
26306 		ip_newroute(q, ipsec_mp, dst, NULL,
26307 		    (CONN_Q(q) ? Q_TO_CONN(q) : NULL), zoneid, ipst);
26308 	}
26309 	goto done;
26310 send:
26311 	if (ipha->ipha_protocol == IPPROTO_UDP &&
26312 	    udp_compute_checksum(ipst->ips_netstack)) {
26313 		/*
26314 		 * ESP NAT-Traversal packet.
26315 		 *
26316 		 * Just do software checksum for now.
26317 		 */
26318 
26319 		offset = IP_SIMPLE_HDR_LENGTH + UDP_CHECKSUM_OFFSET;
26320 		IP_STAT(ipst, ip_out_sw_cksum);
26321 		IP_STAT_UPDATE(ipst, ip_udp_out_sw_cksum_bytes,
26322 		    ntohs(htons(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH));
26323 #define	iphs	((uint16_t *)ipha)
26324 		cksum = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
26325 		    iphs[9] + ntohs(htons(ipha->ipha_length) -
26326 		    IP_SIMPLE_HDR_LENGTH);
26327 #undef iphs
26328 		cksum = IP_CSUM(mp, IP_SIMPLE_HDR_LENGTH, cksum);
26329 		for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont)
26330 			if (mp1->b_wptr - mp1->b_rptr >=
26331 			    offset + sizeof (uint16_t)) {
26332 				up = (uint16_t *)(mp1->b_rptr + offset);
26333 				*up = cksum;
26334 				break;	/* out of for loop */
26335 			} else {
26336 				offset -= (mp->b_wptr - mp->b_rptr);
26337 			}
26338 	} /* Otherwise, just keep the all-zero checksum. */
26339 
26340 	if (ire->ire_stq == NULL) {
26341 		ill_t	*out_ill;
26342 		/*
26343 		 * Loopbacks go through ip_wput_local except for one case.
26344 		 * We come here if we generate a icmp_frag_needed message
26345 		 * after IPSEC processing is over. When this function calls
26346 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
26347 		 * icmp_frag_needed. The message generated comes back here
26348 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
26349 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
26350 		 * source address as it is usually set in ip_wput_ire. As
26351 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
26352 		 * and we end up here. We can't enter ip_wput_ire once the
26353 		 * IPSEC processing is over and hence we need to do it here.
26354 		 */
26355 		ASSERT(q != NULL);
26356 		UPDATE_OB_PKT_COUNT(ire);
26357 		ire->ire_last_used_time = lbolt;
26358 		if (ipha->ipha_src == 0)
26359 			ipha->ipha_src = ire->ire_src_addr;
26360 
26361 		/* PFHooks: LOOPBACK_OUT */
26362 		out_ill = ire->ire_ipif->ipif_ill;
26363 
26364 		DTRACE_PROBE4(ip4__loopback__out__start,
26365 		    ill_t *, NULL, ill_t *, out_ill,
26366 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
26367 
26368 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
26369 		    ipst->ips_ipv4firewall_loopback_out,
26370 		    NULL, out_ill, ipha1, ipsec_mp, mp, ipst);
26371 
26372 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
26373 
26374 		if (ipsec_mp != NULL)
26375 			ip_wput_local(RD(q), out_ill,
26376 			    ipha, ipsec_mp, ire, 0, zoneid);
26377 		if (ire_need_rele)
26378 			ire_refrele(ire);
26379 		goto done;
26380 	}
26381 
26382 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
26383 		/*
26384 		 * We are through with IPSEC processing.
26385 		 * Fragment this and send it on the wire.
26386 		 */
26387 		if (io->ipsec_out_accelerated) {
26388 			/*
26389 			 * The packet has been accelerated but must
26390 			 * be fragmented. This should not happen
26391 			 * since AH and ESP must not accelerate
26392 			 * packets that need fragmentation, however
26393 			 * the configuration could have changed
26394 			 * since the AH or ESP processing.
26395 			 * Drop packet.
26396 			 * IPsec KSTATS: bump bean counter here.
26397 			 */
26398 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
26399 			    "fragmented accelerated packet!\n"));
26400 			freemsg(ipsec_mp);
26401 		} else {
26402 			ip_wput_ire_fragmentit(ipsec_mp, ire, zoneid, ipst);
26403 		}
26404 		if (ire_need_rele)
26405 			ire_refrele(ire);
26406 		goto done;
26407 	}
26408 
26409 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
26410 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
26411 	    (void *)ire->ire_ipif, (void *)ipif));
26412 
26413 	/*
26414 	 * Multiroute the secured packet, unless IPsec really
26415 	 * requires the packet to go out only through a particular
26416 	 * interface.
26417 	 */
26418 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
26419 		ire_t *first_ire;
26420 		irb = ire->ire_bucket;
26421 		ASSERT(irb != NULL);
26422 		/*
26423 		 * This ire has been looked up as the one that
26424 		 * goes through the given ipif;
26425 		 * make sure we do not omit any other multiroute ire
26426 		 * that may be present in the bucket before this one.
26427 		 */
26428 		IRB_REFHOLD(irb);
26429 		for (first_ire = irb->irb_ire;
26430 		    first_ire != NULL;
26431 		    first_ire = first_ire->ire_next) {
26432 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
26433 			    (first_ire->ire_addr == ire->ire_addr) &&
26434 			    !(first_ire->ire_marks &
26435 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
26436 				break;
26437 			}
26438 		}
26439 
26440 		if ((first_ire != NULL) && (first_ire != ire)) {
26441 			/*
26442 			 * Don't change the ire if the packet must
26443 			 * be fragmented if sent via this new one.
26444 			 */
26445 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26446 				IRE_REFHOLD(first_ire);
26447 				if (ire_need_rele)
26448 					ire_refrele(ire);
26449 				else
26450 					ire_need_rele = B_TRUE;
26451 				ire = first_ire;
26452 			}
26453 		}
26454 		IRB_REFRELE(irb);
26455 
26456 		multirt_send = B_TRUE;
26457 		max_frag = ire->ire_max_frag;
26458 	} else {
26459 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
26460 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
26461 			    "flag, attach_if %d\n", attach_if));
26462 		}
26463 	}
26464 
26465 	/*
26466 	 * In most cases, the emission loop below is entered only once.
26467 	 * Only in the case where the ire holds the RTF_MULTIRT
26468 	 * flag, we loop to process all RTF_MULTIRT ires in the
26469 	 * bucket, and send the packet through all crossed
26470 	 * RTF_MULTIRT routes.
26471 	 */
26472 	do {
26473 		if (multirt_send) {
26474 			/*
26475 			 * ire1 holds here the next ire to process in the
26476 			 * bucket. If multirouting is expected,
26477 			 * any non-RTF_MULTIRT ire that has the
26478 			 * right destination address is ignored.
26479 			 */
26480 			ASSERT(irb != NULL);
26481 			IRB_REFHOLD(irb);
26482 			for (ire1 = ire->ire_next;
26483 			    ire1 != NULL;
26484 			    ire1 = ire1->ire_next) {
26485 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26486 					continue;
26487 				if (ire1->ire_addr != ire->ire_addr)
26488 					continue;
26489 				if (ire1->ire_marks &
26490 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
26491 					continue;
26492 				/* No loopback here */
26493 				if (ire1->ire_stq == NULL)
26494 					continue;
26495 				/*
26496 				 * Ensure we do not exceed the MTU
26497 				 * of the next route.
26498 				 */
26499 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26500 					ip_multirt_bad_mtu(ire1, max_frag);
26501 					continue;
26502 				}
26503 
26504 				IRE_REFHOLD(ire1);
26505 				break;
26506 			}
26507 			IRB_REFRELE(irb);
26508 			if (ire1 != NULL) {
26509 				/*
26510 				 * We are in a multiple send case, need to
26511 				 * make a copy of the packet.
26512 				 */
26513 				next_mp = copymsg(ipsec_mp);
26514 				if (next_mp == NULL) {
26515 					ire_refrele(ire1);
26516 					ire1 = NULL;
26517 				}
26518 			}
26519 		}
26520 		/*
26521 		 * Everything is done. Send it out on the wire
26522 		 *
26523 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26524 		 * either send it on the wire or, in the case of
26525 		 * HW acceleration, call ipsec_hw_putnext.
26526 		 */
26527 		if (ire->ire_nce &&
26528 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26529 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26530 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26531 			/*
26532 			 * If ire's link-layer is unresolved (this
26533 			 * would only happen if the incomplete ire
26534 			 * was added to cachetable via forwarding path)
26535 			 * don't bother going to ip_xmit_v4. Just drop the
26536 			 * packet.
26537 			 * There is a slight risk here, in that, if we
26538 			 * have the forwarding path create an incomplete
26539 			 * IRE, then until the IRE is completed, any
26540 			 * transmitted IPSEC packets will be dropped
26541 			 * instead of being queued waiting for resolution.
26542 			 *
26543 			 * But the likelihood of a forwarding packet and a wput
26544 			 * packet sending to the same dst at the same time
26545 			 * and there not yet be an ARP entry for it is small.
26546 			 * Furthermore, if this actually happens, it might
26547 			 * be likely that wput would generate multiple
26548 			 * packets (and forwarding would also have a train
26549 			 * of packets) for that destination. If this is
26550 			 * the case, some of them would have been dropped
26551 			 * anyway, since ARP only queues a few packets while
26552 			 * waiting for resolution
26553 			 *
26554 			 * NOTE: We should really call ip_xmit_v4,
26555 			 * and let it queue the packet and send the
26556 			 * ARP query and have ARP come back thus:
26557 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26558 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26559 			 * hw accel work. But it's too complex to get
26560 			 * the IPsec hw  acceleration approach to fit
26561 			 * well with ip_xmit_v4 doing ARP without
26562 			 * doing IPSEC simplification. For now, we just
26563 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26564 			 * that we can continue with the send on the next
26565 			 * attempt.
26566 			 *
26567 			 * XXX THis should be revisited, when
26568 			 * the IPsec/IP interaction is cleaned up
26569 			 */
26570 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26571 			    " - dropping packet\n"));
26572 			freemsg(ipsec_mp);
26573 			/*
26574 			 * Call ip_xmit_v4() to trigger ARP query
26575 			 * in case the nce_state is ND_INITIAL
26576 			 */
26577 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
26578 			goto drop_pkt;
26579 		}
26580 
26581 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26582 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26583 		    mblk_t *, ipsec_mp);
26584 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26585 		    ipst->ips_ipv4firewall_physical_out,
26586 		    NULL, ire->ire_ipif->ipif_ill, ipha1, ipsec_mp, mp, ipst);
26587 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, ipsec_mp);
26588 		if (ipsec_mp == NULL)
26589 			goto drop_pkt;
26590 
26591 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26592 		pktxmit_state = ip_xmit_v4(mp, ire,
26593 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE);
26594 
26595 		if ((pktxmit_state ==  SEND_FAILED) ||
26596 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26597 
26598 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26599 drop_pkt:
26600 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26601 			    ipIfStatsOutDiscards);
26602 			if (ire_need_rele)
26603 				ire_refrele(ire);
26604 			if (ire1 != NULL) {
26605 				ire_refrele(ire1);
26606 				freemsg(next_mp);
26607 			}
26608 			goto done;
26609 		}
26610 
26611 		freeb(ipsec_mp);
26612 		if (ire_need_rele)
26613 			ire_refrele(ire);
26614 
26615 		if (ire1 != NULL) {
26616 			ire = ire1;
26617 			ire_need_rele = B_TRUE;
26618 			ASSERT(next_mp);
26619 			ipsec_mp = next_mp;
26620 			mp = ipsec_mp->b_cont;
26621 			ire1 = NULL;
26622 			next_mp = NULL;
26623 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26624 		} else {
26625 			multirt_send = B_FALSE;
26626 		}
26627 	} while (multirt_send);
26628 done:
26629 	if (ill != NULL && ill_need_rele)
26630 		ill_refrele(ill);
26631 	if (ipif != NULL)
26632 		ipif_refrele(ipif);
26633 }
26634 
26635 /*
26636  * Get the ill corresponding to the specified ire, and compare its
26637  * capabilities with the protocol and algorithms specified by the
26638  * the SA obtained from ipsec_out. If they match, annotate the
26639  * ipsec_out structure to indicate that the packet needs acceleration.
26640  *
26641  *
26642  * A packet is eligible for outbound hardware acceleration if the
26643  * following conditions are satisfied:
26644  *
26645  * 1. the packet will not be fragmented
26646  * 2. the provider supports the algorithm
26647  * 3. there is no pending control message being exchanged
26648  * 4. snoop is not attached
26649  * 5. the destination address is not a broadcast or multicast address.
26650  *
26651  * Rationale:
26652  *	- Hardware drivers do not support fragmentation with
26653  *	  the current interface.
26654  *	- snoop, multicast, and broadcast may result in exposure of
26655  *	  a cleartext datagram.
26656  * We check all five of these conditions here.
26657  *
26658  * XXX would like to nuke "ire_t *" parameter here; problem is that
26659  * IRE is only way to figure out if a v4 address is a broadcast and
26660  * thus ineligible for acceleration...
26661  */
26662 static void
26663 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26664 {
26665 	ipsec_out_t *io;
26666 	mblk_t *data_mp;
26667 	uint_t plen, overhead;
26668 	ip_stack_t	*ipst;
26669 
26670 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26671 		return;
26672 
26673 	if (ill == NULL)
26674 		return;
26675 	ipst = ill->ill_ipst;
26676 	/*
26677 	 * Destination address is a broadcast or multicast.  Punt.
26678 	 */
26679 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26680 	    IRE_LOCAL)))
26681 		return;
26682 
26683 	data_mp = ipsec_mp->b_cont;
26684 
26685 	if (ill->ill_isv6) {
26686 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26687 
26688 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26689 			return;
26690 
26691 		plen = ip6h->ip6_plen;
26692 	} else {
26693 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26694 
26695 		if (CLASSD(ipha->ipha_dst))
26696 			return;
26697 
26698 		plen = ipha->ipha_length;
26699 	}
26700 	/*
26701 	 * Is there a pending DLPI control message being exchanged
26702 	 * between IP/IPsec and the DLS Provider? If there is, it
26703 	 * could be a SADB update, and the state of the DLS Provider
26704 	 * SADB might not be in sync with the SADB maintained by
26705 	 * IPsec. To avoid dropping packets or using the wrong keying
26706 	 * material, we do not accelerate this packet.
26707 	 */
26708 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26709 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26710 		    "ill_dlpi_pending! don't accelerate packet\n"));
26711 		return;
26712 	}
26713 
26714 	/*
26715 	 * Is the Provider in promiscous mode? If it does, we don't
26716 	 * accelerate the packet since it will bounce back up to the
26717 	 * listeners in the clear.
26718 	 */
26719 	if (ill->ill_promisc_on_phys) {
26720 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26721 		    "ill in promiscous mode, don't accelerate packet\n"));
26722 		return;
26723 	}
26724 
26725 	/*
26726 	 * Will the packet require fragmentation?
26727 	 */
26728 
26729 	/*
26730 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26731 	 * as is used elsewhere.
26732 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26733 	 *	+ 2-byte trailer
26734 	 */
26735 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26736 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26737 
26738 	if ((plen + overhead) > ill->ill_max_mtu)
26739 		return;
26740 
26741 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26742 
26743 	/*
26744 	 * Can the ill accelerate this IPsec protocol and algorithm
26745 	 * specified by the SA?
26746 	 */
26747 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26748 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26749 		return;
26750 	}
26751 
26752 	/*
26753 	 * Tell AH or ESP that the outbound ill is capable of
26754 	 * accelerating this packet.
26755 	 */
26756 	io->ipsec_out_is_capab_ill = B_TRUE;
26757 }
26758 
26759 /*
26760  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26761  *
26762  * If this function returns B_TRUE, the requested SA's have been filled
26763  * into the ipsec_out_*_sa pointers.
26764  *
26765  * If the function returns B_FALSE, the packet has been "consumed", most
26766  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26767  *
26768  * The SA references created by the protocol-specific "select"
26769  * function will be released when the ipsec_mp is freed, thanks to the
26770  * ipsec_out_free destructor -- see spd.c.
26771  */
26772 static boolean_t
26773 ipsec_out_select_sa(mblk_t *ipsec_mp)
26774 {
26775 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26776 	ipsec_out_t *io;
26777 	ipsec_policy_t *pp;
26778 	ipsec_action_t *ap;
26779 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26780 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26781 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26782 
26783 	if (!io->ipsec_out_secure) {
26784 		/*
26785 		 * We came here by mistake.
26786 		 * Don't bother with ipsec processing
26787 		 * We should "discourage" this path in the future.
26788 		 */
26789 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26790 		return (B_FALSE);
26791 	}
26792 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26793 	ASSERT((io->ipsec_out_policy != NULL) ||
26794 	    (io->ipsec_out_act != NULL));
26795 
26796 	ASSERT(io->ipsec_out_failed == B_FALSE);
26797 
26798 	/*
26799 	 * IPSEC processing has started.
26800 	 */
26801 	io->ipsec_out_proc_begin = B_TRUE;
26802 	ap = io->ipsec_out_act;
26803 	if (ap == NULL) {
26804 		pp = io->ipsec_out_policy;
26805 		ASSERT(pp != NULL);
26806 		ap = pp->ipsp_act;
26807 		ASSERT(ap != NULL);
26808 	}
26809 
26810 	/*
26811 	 * We have an action.  now, let's select SA's.
26812 	 * (In the future, we can cache this in the conn_t..)
26813 	 */
26814 	if (ap->ipa_want_esp) {
26815 		if (io->ipsec_out_esp_sa == NULL) {
26816 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26817 			    IPPROTO_ESP);
26818 		}
26819 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26820 	}
26821 
26822 	if (ap->ipa_want_ah) {
26823 		if (io->ipsec_out_ah_sa == NULL) {
26824 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26825 			    IPPROTO_AH);
26826 		}
26827 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26828 		/*
26829 		 * The ESP and AH processing order needs to be preserved
26830 		 * when both protocols are required (ESP should be applied
26831 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26832 		 * when both ESP and AH are required, and an AH ACQUIRE
26833 		 * is needed.
26834 		 */
26835 		if (ap->ipa_want_esp && need_ah_acquire)
26836 			need_esp_acquire = B_TRUE;
26837 	}
26838 
26839 	/*
26840 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26841 	 * Release SAs that got referenced, but will not be used until we
26842 	 * acquire _all_ of the SAs we need.
26843 	 */
26844 	if (need_ah_acquire || need_esp_acquire) {
26845 		if (io->ipsec_out_ah_sa != NULL) {
26846 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26847 			io->ipsec_out_ah_sa = NULL;
26848 		}
26849 		if (io->ipsec_out_esp_sa != NULL) {
26850 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26851 			io->ipsec_out_esp_sa = NULL;
26852 		}
26853 
26854 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26855 		return (B_FALSE);
26856 	}
26857 
26858 	return (B_TRUE);
26859 }
26860 
26861 /*
26862  * Process an IPSEC_OUT message and see what you can
26863  * do with it.
26864  * IPQoS Notes:
26865  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26866  * IPSec.
26867  * XXX would like to nuke ire_t.
26868  * XXX ill_index better be "real"
26869  */
26870 void
26871 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26872 {
26873 	ipsec_out_t *io;
26874 	ipsec_policy_t *pp;
26875 	ipsec_action_t *ap;
26876 	ipha_t *ipha;
26877 	ip6_t *ip6h;
26878 	mblk_t *mp;
26879 	ill_t *ill;
26880 	zoneid_t zoneid;
26881 	ipsec_status_t ipsec_rc;
26882 	boolean_t ill_need_rele = B_FALSE;
26883 	ip_stack_t	*ipst;
26884 	ipsec_stack_t	*ipss;
26885 
26886 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26887 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26888 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26889 	ipst = io->ipsec_out_ns->netstack_ip;
26890 	mp = ipsec_mp->b_cont;
26891 
26892 	/*
26893 	 * Initiate IPPF processing. We do it here to account for packets
26894 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26895 	 * We can check for ipsec_out_proc_begin even for such packets, as
26896 	 * they will always be false (asserted below).
26897 	 */
26898 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26899 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26900 		    io->ipsec_out_ill_index : ill_index);
26901 		if (mp == NULL) {
26902 			ip2dbg(("ipsec_out_process: packet dropped "\
26903 			    "during IPPF processing\n"));
26904 			freeb(ipsec_mp);
26905 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26906 			return;
26907 		}
26908 	}
26909 
26910 	if (!io->ipsec_out_secure) {
26911 		/*
26912 		 * We came here by mistake.
26913 		 * Don't bother with ipsec processing
26914 		 * Should "discourage" this path in the future.
26915 		 */
26916 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26917 		goto done;
26918 	}
26919 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26920 	ASSERT((io->ipsec_out_policy != NULL) ||
26921 	    (io->ipsec_out_act != NULL));
26922 	ASSERT(io->ipsec_out_failed == B_FALSE);
26923 
26924 	ipss = ipst->ips_netstack->netstack_ipsec;
26925 	if (!ipsec_loaded(ipss)) {
26926 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26927 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26928 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26929 		} else {
26930 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26931 		}
26932 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26933 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26934 		    &ipss->ipsec_dropper);
26935 		return;
26936 	}
26937 
26938 	/*
26939 	 * IPSEC processing has started.
26940 	 */
26941 	io->ipsec_out_proc_begin = B_TRUE;
26942 	ap = io->ipsec_out_act;
26943 	if (ap == NULL) {
26944 		pp = io->ipsec_out_policy;
26945 		ASSERT(pp != NULL);
26946 		ap = pp->ipsp_act;
26947 		ASSERT(ap != NULL);
26948 	}
26949 
26950 	/*
26951 	 * Save the outbound ill index. When the packet comes back
26952 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26953 	 * before sending it the accelerated packet.
26954 	 */
26955 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26956 		int ifindex;
26957 		ill = ire_to_ill(ire);
26958 		ifindex = ill->ill_phyint->phyint_ifindex;
26959 		io->ipsec_out_capab_ill_index = ifindex;
26960 	}
26961 
26962 	/*
26963 	 * The order of processing is first insert a IP header if needed.
26964 	 * Then insert the ESP header and then the AH header.
26965 	 */
26966 	if ((io->ipsec_out_se_done == B_FALSE) &&
26967 	    (ap->ipa_want_se)) {
26968 		/*
26969 		 * First get the outer IP header before sending
26970 		 * it to ESP.
26971 		 */
26972 		ipha_t *oipha, *iipha;
26973 		mblk_t *outer_mp, *inner_mp;
26974 
26975 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26976 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26977 			    "ipsec_out_process: "
26978 			    "Self-Encapsulation failed: Out of memory\n");
26979 			freemsg(ipsec_mp);
26980 			if (ill != NULL) {
26981 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26982 			} else {
26983 				BUMP_MIB(&ipst->ips_ip_mib,
26984 				    ipIfStatsOutDiscards);
26985 			}
26986 			return;
26987 		}
26988 		inner_mp = ipsec_mp->b_cont;
26989 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26990 		oipha = (ipha_t *)outer_mp->b_rptr;
26991 		iipha = (ipha_t *)inner_mp->b_rptr;
26992 		*oipha = *iipha;
26993 		outer_mp->b_wptr += sizeof (ipha_t);
26994 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26995 		    sizeof (ipha_t));
26996 		oipha->ipha_protocol = IPPROTO_ENCAP;
26997 		oipha->ipha_version_and_hdr_length =
26998 		    IP_SIMPLE_HDR_VERSION;
26999 		oipha->ipha_hdr_checksum = 0;
27000 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
27001 		outer_mp->b_cont = inner_mp;
27002 		ipsec_mp->b_cont = outer_mp;
27003 
27004 		io->ipsec_out_se_done = B_TRUE;
27005 		io->ipsec_out_tunnel = B_TRUE;
27006 	}
27007 
27008 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
27009 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
27010 	    !ipsec_out_select_sa(ipsec_mp))
27011 		return;
27012 
27013 	/*
27014 	 * By now, we know what SA's to use.  Toss over to ESP & AH
27015 	 * to do the heavy lifting.
27016 	 */
27017 	zoneid = io->ipsec_out_zoneid;
27018 	ASSERT(zoneid != ALL_ZONES);
27019 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
27020 		ASSERT(io->ipsec_out_esp_sa != NULL);
27021 		io->ipsec_out_esp_done = B_TRUE;
27022 		/*
27023 		 * Note that since hw accel can only apply one transform,
27024 		 * not two, we skip hw accel for ESP if we also have AH
27025 		 * This is an design limitation of the interface
27026 		 * which should be revisited.
27027 		 */
27028 		ASSERT(ire != NULL);
27029 		if (io->ipsec_out_ah_sa == NULL) {
27030 			ill = (ill_t *)ire->ire_stq->q_ptr;
27031 			ipsec_out_is_accelerated(ipsec_mp,
27032 			    io->ipsec_out_esp_sa, ill, ire);
27033 		}
27034 
27035 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
27036 		switch (ipsec_rc) {
27037 		case IPSEC_STATUS_SUCCESS:
27038 			break;
27039 		case IPSEC_STATUS_FAILED:
27040 			if (ill != NULL) {
27041 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
27042 			} else {
27043 				BUMP_MIB(&ipst->ips_ip_mib,
27044 				    ipIfStatsOutDiscards);
27045 			}
27046 			/* FALLTHRU */
27047 		case IPSEC_STATUS_PENDING:
27048 			return;
27049 		}
27050 	}
27051 
27052 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
27053 		ASSERT(io->ipsec_out_ah_sa != NULL);
27054 		io->ipsec_out_ah_done = B_TRUE;
27055 		if (ire == NULL) {
27056 			int idx = io->ipsec_out_capab_ill_index;
27057 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
27058 			    NULL, NULL, NULL, NULL, ipst);
27059 			ill_need_rele = B_TRUE;
27060 		} else {
27061 			ill = (ill_t *)ire->ire_stq->q_ptr;
27062 		}
27063 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
27064 		    ire);
27065 
27066 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
27067 		switch (ipsec_rc) {
27068 		case IPSEC_STATUS_SUCCESS:
27069 			break;
27070 		case IPSEC_STATUS_FAILED:
27071 			if (ill != NULL) {
27072 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
27073 			} else {
27074 				BUMP_MIB(&ipst->ips_ip_mib,
27075 				    ipIfStatsOutDiscards);
27076 			}
27077 			/* FALLTHRU */
27078 		case IPSEC_STATUS_PENDING:
27079 			if (ill != NULL && ill_need_rele)
27080 				ill_refrele(ill);
27081 			return;
27082 		}
27083 	}
27084 	/*
27085 	 * We are done with IPSEC processing. Send it over
27086 	 * the wire.
27087 	 */
27088 done:
27089 	mp = ipsec_mp->b_cont;
27090 	ipha = (ipha_t *)mp->b_rptr;
27091 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
27092 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
27093 	} else {
27094 		ip6h = (ip6_t *)ipha;
27095 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
27096 	}
27097 	if (ill != NULL && ill_need_rele)
27098 		ill_refrele(ill);
27099 }
27100 
27101 /* ARGSUSED */
27102 void
27103 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
27104 {
27105 	opt_restart_t	*or;
27106 	int	err;
27107 	conn_t	*connp;
27108 
27109 	ASSERT(CONN_Q(q));
27110 	connp = Q_TO_CONN(q);
27111 
27112 	ASSERT(first_mp->b_datap->db_type == M_CTL);
27113 	or = (opt_restart_t *)first_mp->b_rptr;
27114 	/*
27115 	 * We don't need to pass any credentials here since this is just
27116 	 * a restart. The credentials are passed in when svr4_optcom_req
27117 	 * is called the first time (from ip_wput_nondata).
27118 	 */
27119 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
27120 		err = svr4_optcom_req(q, first_mp, NULL,
27121 		    &ip_opt_obj);
27122 	} else {
27123 		ASSERT(or->or_type == T_OPTMGMT_REQ);
27124 		err = tpi_optcom_req(q, first_mp, NULL,
27125 		    &ip_opt_obj);
27126 	}
27127 	if (err != EINPROGRESS) {
27128 		/* operation is done */
27129 		CONN_OPER_PENDING_DONE(connp);
27130 	}
27131 }
27132 
27133 /*
27134  * ioctls that go through a down/up sequence may need to wait for the down
27135  * to complete. This involves waiting for the ire and ipif refcnts to go down
27136  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
27137  */
27138 /* ARGSUSED */
27139 void
27140 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27141 {
27142 	struct iocblk *iocp;
27143 	mblk_t *mp1;
27144 	ip_ioctl_cmd_t *ipip;
27145 	int err;
27146 	sin_t	*sin;
27147 	struct lifreq *lifr;
27148 	struct ifreq *ifr;
27149 
27150 	iocp = (struct iocblk *)mp->b_rptr;
27151 	ASSERT(ipsq != NULL);
27152 	/* Existence of mp1 verified in ip_wput_nondata */
27153 	mp1 = mp->b_cont->b_cont;
27154 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27155 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
27156 		/*
27157 		 * Special case where ipsq_current_ipif is not set:
27158 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
27159 		 * ill could also have become part of a ipmp group in the
27160 		 * process, we are here as were not able to complete the
27161 		 * operation in ipif_set_values because we could not become
27162 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
27163 		 * will not be set so we need to set it.
27164 		 */
27165 		ill_t *ill = q->q_ptr;
27166 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
27167 	}
27168 	ASSERT(ipsq->ipsq_current_ipif != NULL);
27169 
27170 	if (ipip->ipi_cmd_type == IF_CMD) {
27171 		/* This a old style SIOC[GS]IF* command */
27172 		ifr = (struct ifreq *)mp1->b_rptr;
27173 		sin = (sin_t *)&ifr->ifr_addr;
27174 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
27175 		/* This a new style SIOC[GS]LIF* command */
27176 		lifr = (struct lifreq *)mp1->b_rptr;
27177 		sin = (sin_t *)&lifr->lifr_addr;
27178 	} else {
27179 		sin = NULL;
27180 	}
27181 
27182 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_current_ipif, sin, q, mp,
27183 	    ipip, mp1->b_rptr);
27184 
27185 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27186 }
27187 
27188 /*
27189  * ioctl processing
27190  *
27191  * ioctl processing starts with ip_sioctl_copyin_setup which looks up
27192  * the ioctl command in the ioctl tables and determines the copyin data size
27193  * from the ioctl property ipi_copyin_size, and does an mi_copyin() of that
27194  * size.
27195  *
27196  * ioctl processing then continues when the M_IOCDATA makes its way down.
27197  * Now the ioctl is looked up again in the ioctl table, and its properties are
27198  * extracted. The associated 'conn' is then refheld till the end of the ioctl
27199  * and the general ioctl processing function ip_process_ioctl is called.
27200  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
27201  * so goes thru the serialization primitive ipsq_try_enter. Then the
27202  * appropriate function to handle the ioctl is called based on the entry in
27203  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
27204  * which also refreleases the 'conn' that was refheld at the start of the
27205  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
27206  * ip_extract_lifreq_cmn extracts the interface name from the lifreq/ifreq
27207  * struct and looks up the ipif. ip_extract_tunreq handles the case of tunnel.
27208  *
27209  * Many exclusive ioctls go thru an internal down up sequence as part of
27210  * the operation. For example an attempt to change the IP address of an
27211  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
27212  * does all the cleanup such as deleting all ires that use this address.
27213  * Then we need to wait till all references to the interface go away.
27214  */
27215 void
27216 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
27217 {
27218 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
27219 	ip_ioctl_cmd_t *ipip = (ip_ioctl_cmd_t *)arg;
27220 	cmd_info_t ci;
27221 	int err;
27222 	boolean_t entered_ipsq = B_FALSE;
27223 
27224 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
27225 
27226 	if (ipip == NULL)
27227 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27228 
27229 	/*
27230 	 * SIOCLIFADDIF needs to go thru a special path since the
27231 	 * ill may not exist yet. This happens in the case of lo0
27232 	 * which is created using this ioctl.
27233 	 */
27234 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
27235 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
27236 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27237 		return;
27238 	}
27239 
27240 	ci.ci_ipif = NULL;
27241 	switch (ipip->ipi_cmd_type) {
27242 	case IF_CMD:
27243 	case LIF_CMD:
27244 		/*
27245 		 * ioctls that pass in a [l]ifreq appear here.
27246 		 * ip_extract_lifreq_cmn returns a refheld ipif in
27247 		 * ci.ci_ipif
27248 		 */
27249 		err = ip_extract_lifreq_cmn(q, mp, ipip->ipi_cmd_type,
27250 		    ipip->ipi_flags, &ci, ip_process_ioctl);
27251 		if (err != 0) {
27252 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27253 			return;
27254 		}
27255 		ASSERT(ci.ci_ipif != NULL);
27256 		break;
27257 
27258 	case TUN_CMD:
27259 		/*
27260 		 * SIOC[GS]TUNPARAM appear here. ip_extract_tunreq returns
27261 		 * a refheld ipif in ci.ci_ipif
27262 		 */
27263 		err = ip_extract_tunreq(q, mp, &ci.ci_ipif, ip_process_ioctl);
27264 		if (err != 0) {
27265 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27266 			return;
27267 		}
27268 		ASSERT(ci.ci_ipif != NULL);
27269 		break;
27270 
27271 	case MISC_CMD:
27272 		/*
27273 		 * ioctls that neither pass in [l]ifreq or iftun_req come here
27274 		 * For eg. SIOCGLIFCONF will appear here.
27275 		 */
27276 		switch (ipip->ipi_cmd) {
27277 		case IF_UNITSEL:
27278 			/* ioctl comes down the ill */
27279 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
27280 			ipif_refhold(ci.ci_ipif);
27281 			break;
27282 		case SIOCGMSFILTER:
27283 		case SIOCSMSFILTER:
27284 		case SIOCGIPMSFILTER:
27285 		case SIOCSIPMSFILTER:
27286 			err = ip_extract_msfilter(q, mp, &ci.ci_ipif,
27287 			    ip_process_ioctl);
27288 			if (err != 0) {
27289 				ip_ioctl_finish(q, mp, err, IPI2MODE(ipip),
27290 				    NULL);
27291 			}
27292 			break;
27293 		}
27294 		err = 0;
27295 		ci.ci_sin = NULL;
27296 		ci.ci_sin6 = NULL;
27297 		ci.ci_lifr = NULL;
27298 		break;
27299 	}
27300 
27301 	/*
27302 	 * If ipsq is non-null, we are already being called exclusively
27303 	 */
27304 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
27305 	if (!(ipip->ipi_flags & IPI_WR)) {
27306 		/*
27307 		 * A return value of EINPROGRESS means the ioctl is
27308 		 * either queued and waiting for some reason or has
27309 		 * already completed.
27310 		 */
27311 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
27312 		    ci.ci_lifr);
27313 		if (ci.ci_ipif != NULL)
27314 			ipif_refrele(ci.ci_ipif);
27315 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27316 		return;
27317 	}
27318 
27319 	ASSERT(ci.ci_ipif != NULL);
27320 
27321 	if (ipsq == NULL) {
27322 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
27323 		    ip_process_ioctl, NEW_OP, B_TRUE);
27324 		entered_ipsq = B_TRUE;
27325 	}
27326 	/*
27327 	 * Release the ipif so that ipif_down and friends that wait for
27328 	 * references to go away are not misled about the current ipif_refcnt
27329 	 * values. We are writer so we can access the ipif even after releasing
27330 	 * the ipif.
27331 	 */
27332 	ipif_refrele(ci.ci_ipif);
27333 	if (ipsq == NULL)
27334 		return;
27335 
27336 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
27337 
27338 	/*
27339 	 * For most set ioctls that come here, this serves as a single point
27340 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
27341 	 * be any new references to the ipif. This helps functions that go
27342 	 * through this path and end up trying to wait for the refcnts
27343 	 * associated with the ipif to go down to zero. Some exceptions are
27344 	 * Failover, Failback, and Groupname commands that operate on more than
27345 	 * just the ci.ci_ipif. These commands internally determine the
27346 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
27347 	 * flags on that set. Another exception is the Removeif command that
27348 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
27349 	 * ipif to operate on.
27350 	 */
27351 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
27352 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
27353 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
27354 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
27355 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
27356 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
27357 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
27358 
27359 	/*
27360 	 * A return value of EINPROGRESS means the ioctl is
27361 	 * either queued and waiting for some reason or has
27362 	 * already completed.
27363 	 */
27364 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
27365 
27366 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27367 
27368 	if (entered_ipsq)
27369 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
27370 }
27371 
27372 /*
27373  * Complete the ioctl. Typically ioctls use the mi package and need to
27374  * do mi_copyout/mi_copy_done.
27375  */
27376 void
27377 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
27378 {
27379 	conn_t	*connp = NULL;
27380 
27381 	if (err == EINPROGRESS)
27382 		return;
27383 
27384 	if (CONN_Q(q)) {
27385 		connp = Q_TO_CONN(q);
27386 		ASSERT(connp->conn_ref >= 2);
27387 	}
27388 
27389 	switch (mode) {
27390 	case COPYOUT:
27391 		if (err == 0)
27392 			mi_copyout(q, mp);
27393 		else
27394 			mi_copy_done(q, mp, err);
27395 		break;
27396 
27397 	case NO_COPYOUT:
27398 		mi_copy_done(q, mp, err);
27399 		break;
27400 
27401 	default:
27402 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
27403 		break;
27404 	}
27405 
27406 	/*
27407 	 * The refhold placed at the start of the ioctl is released here.
27408 	 */
27409 	if (connp != NULL)
27410 		CONN_OPER_PENDING_DONE(connp);
27411 
27412 	if (ipsq != NULL)
27413 		ipsq_current_finish(ipsq);
27414 }
27415 
27416 /*
27417  * This is called from ip_wput_nondata to resume a deferred TCP bind.
27418  */
27419 /* ARGSUSED */
27420 void
27421 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
27422 {
27423 	conn_t *connp = arg;
27424 	tcp_t	*tcp;
27425 
27426 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
27427 	tcp = connp->conn_tcp;
27428 
27429 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
27430 		freemsg(mp);
27431 	else
27432 		tcp_rput_other(tcp, mp);
27433 	CONN_OPER_PENDING_DONE(connp);
27434 }
27435 
27436 /* Called from ip_wput for all non data messages */
27437 /* ARGSUSED */
27438 void
27439 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27440 {
27441 	mblk_t		*mp1;
27442 	ire_t		*ire, *fake_ire;
27443 	ill_t		*ill;
27444 	struct iocblk	*iocp;
27445 	ip_ioctl_cmd_t	*ipip;
27446 	cred_t		*cr;
27447 	conn_t		*connp;
27448 	int		cmd, err;
27449 	nce_t		*nce;
27450 	ipif_t		*ipif;
27451 	ip_stack_t	*ipst;
27452 	char		*proto_str;
27453 
27454 	if (CONN_Q(q)) {
27455 		connp = Q_TO_CONN(q);
27456 		ipst = connp->conn_netstack->netstack_ip;
27457 	} else {
27458 		connp = NULL;
27459 		ipst = ILLQ_TO_IPST(q);
27460 	}
27461 
27462 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
27463 
27464 	/* Check if it is a queue to /dev/sctp. */
27465 	if (connp != NULL && connp->conn_ulp == IPPROTO_SCTP &&
27466 	    connp->conn_rq == NULL) {
27467 		sctp_wput(q, mp);
27468 		return;
27469 	}
27470 
27471 	switch (DB_TYPE(mp)) {
27472 	case M_IOCTL:
27473 		/*
27474 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
27475 		 * will arrange to copy in associated control structures.
27476 		 */
27477 		ip_sioctl_copyin_setup(q, mp);
27478 		return;
27479 	case M_IOCDATA:
27480 		/*
27481 		 * Ensure that this is associated with one of our trans-
27482 		 * parent ioctls.  If it's not ours, discard it if we're
27483 		 * running as a driver, or pass it on if we're a module.
27484 		 */
27485 		iocp = (struct iocblk *)mp->b_rptr;
27486 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27487 		if (ipip == NULL) {
27488 			if (q->q_next == NULL) {
27489 				goto nak;
27490 			} else {
27491 				putnext(q, mp);
27492 			}
27493 			return;
27494 		} else if ((q->q_next != NULL) &&
27495 		    !(ipip->ipi_flags & IPI_MODOK)) {
27496 			/*
27497 			 * the ioctl is one we recognise, but is not
27498 			 * consumed by IP as a module, pass M_IOCDATA
27499 			 * for processing downstream, but only for
27500 			 * common Streams ioctls.
27501 			 */
27502 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27503 				putnext(q, mp);
27504 				return;
27505 			} else {
27506 				goto nak;
27507 			}
27508 		}
27509 
27510 		/* IOCTL continuation following copyin or copyout. */
27511 		if (mi_copy_state(q, mp, NULL) == -1) {
27512 			/*
27513 			 * The copy operation failed.  mi_copy_state already
27514 			 * cleaned up, so we're out of here.
27515 			 */
27516 			return;
27517 		}
27518 		/*
27519 		 * If we just completed a copy in, we become writer and
27520 		 * continue processing in ip_sioctl_copyin_done.  If it
27521 		 * was a copy out, we call mi_copyout again.  If there is
27522 		 * nothing more to copy out, it will complete the IOCTL.
27523 		 */
27524 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27525 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27526 				mi_copy_done(q, mp, EPROTO);
27527 				return;
27528 			}
27529 			/*
27530 			 * Check for cases that need more copying.  A return
27531 			 * value of 0 means a second copyin has been started,
27532 			 * so we return; a return value of 1 means no more
27533 			 * copying is needed, so we continue.
27534 			 */
27535 			cmd = iocp->ioc_cmd;
27536 			if ((cmd == SIOCGMSFILTER || cmd == SIOCSMSFILTER ||
27537 			    cmd == SIOCGIPMSFILTER || cmd == SIOCSIPMSFILTER) &&
27538 			    MI_COPY_COUNT(mp) == 1) {
27539 				if (ip_copyin_msfilter(q, mp) == 0)
27540 					return;
27541 			}
27542 			/*
27543 			 * Refhold the conn, till the ioctl completes. This is
27544 			 * needed in case the ioctl ends up in the pending mp
27545 			 * list. Every mp in the ill_pending_mp list and
27546 			 * the ipsq_pending_mp must have a refhold on the conn
27547 			 * to resume processing. The refhold is released when
27548 			 * the ioctl completes. (normally or abnormally)
27549 			 * In all cases ip_ioctl_finish is called to finish
27550 			 * the ioctl.
27551 			 */
27552 			if (connp != NULL) {
27553 				/* This is not a reentry */
27554 				ASSERT(ipsq == NULL);
27555 				CONN_INC_REF(connp);
27556 			} else {
27557 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27558 					mi_copy_done(q, mp, EINVAL);
27559 					return;
27560 				}
27561 			}
27562 
27563 			ip_process_ioctl(ipsq, q, mp, ipip);
27564 
27565 		} else {
27566 			mi_copyout(q, mp);
27567 		}
27568 		return;
27569 nak:
27570 		iocp->ioc_error = EINVAL;
27571 		mp->b_datap->db_type = M_IOCNAK;
27572 		iocp->ioc_count = 0;
27573 		qreply(q, mp);
27574 		return;
27575 
27576 	case M_IOCNAK:
27577 		/*
27578 		 * The only way we could get here is if a resolver didn't like
27579 		 * an IOCTL we sent it.	 This shouldn't happen.
27580 		 */
27581 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27582 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27583 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27584 		freemsg(mp);
27585 		return;
27586 	case M_IOCACK:
27587 		/* /dev/ip shouldn't see this */
27588 		if (CONN_Q(q))
27589 			goto nak;
27590 
27591 		/* Finish socket ioctls passed through to ARP. */
27592 		ip_sioctl_iocack(q, mp);
27593 		return;
27594 	case M_FLUSH:
27595 		if (*mp->b_rptr & FLUSHW)
27596 			flushq(q, FLUSHALL);
27597 		if (q->q_next) {
27598 			putnext(q, mp);
27599 			return;
27600 		}
27601 		if (*mp->b_rptr & FLUSHR) {
27602 			*mp->b_rptr &= ~FLUSHW;
27603 			qreply(q, mp);
27604 			return;
27605 		}
27606 		freemsg(mp);
27607 		return;
27608 	case IRE_DB_REQ_TYPE:
27609 		if (connp == NULL) {
27610 			proto_str = "IRE_DB_REQ_TYPE";
27611 			goto protonak;
27612 		}
27613 		/* An Upper Level Protocol wants a copy of an IRE. */
27614 		ip_ire_req(q, mp);
27615 		return;
27616 	case M_CTL:
27617 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27618 			break;
27619 
27620 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27621 		    TUN_HELLO) {
27622 			ASSERT(connp != NULL);
27623 			connp->conn_flags |= IPCL_IPTUN;
27624 			freeb(mp);
27625 			return;
27626 		}
27627 
27628 		if (connp != NULL && *(uint32_t *)mp->b_rptr ==
27629 		    IP_ULP_OUT_LABELED) {
27630 			out_labeled_t *olp;
27631 
27632 			if (mp->b_wptr - mp->b_rptr != sizeof (*olp))
27633 				break;
27634 			olp = (out_labeled_t *)mp->b_rptr;
27635 			connp->conn_ulp_labeled = olp->out_qnext == q;
27636 			freemsg(mp);
27637 			return;
27638 		}
27639 
27640 		/* M_CTL messages are used by ARP to tell us things. */
27641 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27642 			break;
27643 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27644 		case AR_ENTRY_SQUERY:
27645 			ip_wput_ctl(q, mp);
27646 			return;
27647 		case AR_CLIENT_NOTIFY:
27648 			ip_arp_news(q, mp);
27649 			return;
27650 		case AR_DLPIOP_DONE:
27651 			ASSERT(q->q_next != NULL);
27652 			ill = (ill_t *)q->q_ptr;
27653 			/* qwriter_ip releases the refhold */
27654 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27655 			ill_refhold(ill);
27656 			qwriter_ip(ill, q, mp, ip_arp_done, CUR_OP, B_FALSE);
27657 			return;
27658 		case AR_ARP_CLOSING:
27659 			/*
27660 			 * ARP (above us) is closing. If no ARP bringup is
27661 			 * currently pending, ack the message so that ARP
27662 			 * can complete its close. Also mark ill_arp_closing
27663 			 * so that new ARP bringups will fail. If any
27664 			 * ARP bringup is currently in progress, we will
27665 			 * ack this when the current ARP bringup completes.
27666 			 */
27667 			ASSERT(q->q_next != NULL);
27668 			ill = (ill_t *)q->q_ptr;
27669 			mutex_enter(&ill->ill_lock);
27670 			ill->ill_arp_closing = 1;
27671 			if (!ill->ill_arp_bringup_pending) {
27672 				mutex_exit(&ill->ill_lock);
27673 				qreply(q, mp);
27674 			} else {
27675 				mutex_exit(&ill->ill_lock);
27676 				freemsg(mp);
27677 			}
27678 			return;
27679 		case AR_ARP_EXTEND:
27680 			/*
27681 			 * The ARP module above us is capable of duplicate
27682 			 * address detection.  Old ATM drivers will not send
27683 			 * this message.
27684 			 */
27685 			ASSERT(q->q_next != NULL);
27686 			ill = (ill_t *)q->q_ptr;
27687 			ill->ill_arp_extend = B_TRUE;
27688 			freemsg(mp);
27689 			return;
27690 		default:
27691 			break;
27692 		}
27693 		break;
27694 	case M_PROTO:
27695 	case M_PCPROTO:
27696 		/*
27697 		 * The only PROTO messages we expect are ULP binds and
27698 		 * copies of option negotiation acknowledgements.
27699 		 */
27700 		switch (((union T_primitives *)mp->b_rptr)->type) {
27701 		case O_T_BIND_REQ:
27702 		case T_BIND_REQ: {
27703 			/* Request can get queued in bind */
27704 			if (connp == NULL) {
27705 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27706 				goto protonak;
27707 			}
27708 			/*
27709 			 * Both TCP and UDP call ip_bind_{v4,v6}() directly
27710 			 * instead of going through this path.  We only get
27711 			 * here in the following cases:
27712 			 *
27713 			 * a. Bind retries, where ipsq is non-NULL.
27714 			 * b. T_BIND_REQ is issued from non TCP/UDP
27715 			 *    transport, e.g. icmp for raw socket,
27716 			 *    in which case ipsq will be NULL.
27717 			 */
27718 			ASSERT(ipsq != NULL ||
27719 			    (!IPCL_IS_TCP(connp) && !IPCL_IS_UDP(connp)));
27720 
27721 			/* Don't increment refcnt if this is a re-entry */
27722 			if (ipsq == NULL)
27723 				CONN_INC_REF(connp);
27724 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27725 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27726 			if (mp == NULL)
27727 				return;
27728 			if (IPCL_IS_TCP(connp)) {
27729 				/*
27730 				 * In the case of TCP endpoint we
27731 				 * come here only for bind retries
27732 				 */
27733 				ASSERT(ipsq != NULL);
27734 				CONN_INC_REF(connp);
27735 				squeue_fill(connp->conn_sqp, mp,
27736 				    ip_resume_tcp_bind, connp,
27737 				    SQTAG_BIND_RETRY);
27738 				return;
27739 			} else if (IPCL_IS_UDP(connp)) {
27740 				/*
27741 				 * In the case of UDP endpoint we
27742 				 * come here only for bind retries
27743 				 */
27744 				ASSERT(ipsq != NULL);
27745 				udp_resume_bind(connp, mp);
27746 				return;
27747 			}
27748 			qreply(q, mp);
27749 			CONN_OPER_PENDING_DONE(connp);
27750 			return;
27751 		}
27752 		case T_SVR4_OPTMGMT_REQ:
27753 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27754 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27755 
27756 			if (connp == NULL) {
27757 				proto_str = "T_SVR4_OPTMGMT_REQ";
27758 				goto protonak;
27759 			}
27760 
27761 			if (!snmpcom_req(q, mp, ip_snmp_set,
27762 			    ip_snmp_get, cr)) {
27763 				/*
27764 				 * Call svr4_optcom_req so that it can
27765 				 * generate the ack. We don't come here
27766 				 * if this operation is being restarted.
27767 				 * ip_restart_optmgmt will drop the conn ref.
27768 				 * In the case of ipsec option after the ipsec
27769 				 * load is complete conn_restart_ipsec_waiter
27770 				 * drops the conn ref.
27771 				 */
27772 				ASSERT(ipsq == NULL);
27773 				CONN_INC_REF(connp);
27774 				if (ip_check_for_ipsec_opt(q, mp))
27775 					return;
27776 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj);
27777 				if (err != EINPROGRESS) {
27778 					/* Operation is done */
27779 					CONN_OPER_PENDING_DONE(connp);
27780 				}
27781 			}
27782 			return;
27783 		case T_OPTMGMT_REQ:
27784 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27785 			/*
27786 			 * Note: No snmpcom_req support through new
27787 			 * T_OPTMGMT_REQ.
27788 			 * Call tpi_optcom_req so that it can
27789 			 * generate the ack.
27790 			 */
27791 			if (connp == NULL) {
27792 				proto_str = "T_OPTMGMT_REQ";
27793 				goto protonak;
27794 			}
27795 
27796 			ASSERT(ipsq == NULL);
27797 			/*
27798 			 * We don't come here for restart. ip_restart_optmgmt
27799 			 * will drop the conn ref. In the case of ipsec option
27800 			 * after the ipsec load is complete
27801 			 * conn_restart_ipsec_waiter drops the conn ref.
27802 			 */
27803 			CONN_INC_REF(connp);
27804 			if (ip_check_for_ipsec_opt(q, mp))
27805 				return;
27806 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj);
27807 			if (err != EINPROGRESS) {
27808 				/* Operation is done */
27809 				CONN_OPER_PENDING_DONE(connp);
27810 			}
27811 			return;
27812 		case T_UNBIND_REQ:
27813 			if (connp == NULL) {
27814 				proto_str = "T_UNBIND_REQ";
27815 				goto protonak;
27816 			}
27817 			mp = ip_unbind(q, mp);
27818 			qreply(q, mp);
27819 			return;
27820 		default:
27821 			/*
27822 			 * Have to drop any DLPI messages coming down from
27823 			 * arp (such as an info_req which would cause ip
27824 			 * to receive an extra info_ack if it was passed
27825 			 * through.
27826 			 */
27827 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27828 			    (int)*(uint_t *)mp->b_rptr));
27829 			freemsg(mp);
27830 			return;
27831 		}
27832 		/* NOTREACHED */
27833 	case IRE_DB_TYPE: {
27834 		nce_t		*nce;
27835 		ill_t		*ill;
27836 		in6_addr_t	gw_addr_v6;
27837 
27838 
27839 		/*
27840 		 * This is a response back from a resolver.  It
27841 		 * consists of a message chain containing:
27842 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27843 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27844 		 * The LL_HDR_MBLK is the DLPI header to use to get
27845 		 * the attached packet, and subsequent ones for the
27846 		 * same destination, transmitted.
27847 		 */
27848 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27849 			break;
27850 		/*
27851 		 * First, check to make sure the resolution succeeded.
27852 		 * If it failed, the second mblk will be empty.
27853 		 * If it is, free the chain, dropping the packet.
27854 		 * (We must ire_delete the ire; that frees the ire mblk)
27855 		 * We're doing this now to support PVCs for ATM; it's
27856 		 * a partial xresolv implementation. When we fully implement
27857 		 * xresolv interfaces, instead of freeing everything here
27858 		 * we'll initiate neighbor discovery.
27859 		 *
27860 		 * For v4 (ARP and other external resolvers) the resolver
27861 		 * frees the message, so no check is needed. This check
27862 		 * is required, though, for a full xresolve implementation.
27863 		 * Including this code here now both shows how external
27864 		 * resolvers can NACK a resolution request using an
27865 		 * existing design that has no specific provisions for NACKs,
27866 		 * and also takes into account that the current non-ARP
27867 		 * external resolver has been coded to use this method of
27868 		 * NACKing for all IPv6 (xresolv) cases,
27869 		 * whether our xresolv implementation is complete or not.
27870 		 *
27871 		 */
27872 		ire = (ire_t *)mp->b_rptr;
27873 		ill = ire_to_ill(ire);
27874 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27875 		if (mp1->b_rptr == mp1->b_wptr) {
27876 			if (ire->ire_ipversion == IPV6_VERSION) {
27877 				/*
27878 				 * XRESOLV interface.
27879 				 */
27880 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27881 				mutex_enter(&ire->ire_lock);
27882 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27883 				mutex_exit(&ire->ire_lock);
27884 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27885 					nce = ndp_lookup_v6(ill,
27886 					    &ire->ire_addr_v6, B_FALSE);
27887 				} else {
27888 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
27889 					    B_FALSE);
27890 				}
27891 				if (nce != NULL) {
27892 					nce_resolv_failed(nce);
27893 					ndp_delete(nce);
27894 					NCE_REFRELE(nce);
27895 				}
27896 			}
27897 			mp->b_cont = NULL;
27898 			freemsg(mp1);		/* frees the pkt as well */
27899 			ASSERT(ire->ire_nce == NULL);
27900 			ire_delete((ire_t *)mp->b_rptr);
27901 			return;
27902 		}
27903 
27904 		/*
27905 		 * Split them into IRE_MBLK and pkt and feed it into
27906 		 * ire_add_then_send. Then in ire_add_then_send
27907 		 * the IRE will be added, and then the packet will be
27908 		 * run back through ip_wput. This time it will make
27909 		 * it to the wire.
27910 		 */
27911 		mp->b_cont = NULL;
27912 		mp = mp1->b_cont;		/* now, mp points to pkt */
27913 		mp1->b_cont = NULL;
27914 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27915 		if (ire->ire_ipversion == IPV6_VERSION) {
27916 			/*
27917 			 * XRESOLV interface. Find the nce and put a copy
27918 			 * of the dl_unitdata_req in nce_res_mp
27919 			 */
27920 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27921 			mutex_enter(&ire->ire_lock);
27922 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27923 			mutex_exit(&ire->ire_lock);
27924 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27925 				nce = ndp_lookup_v6(ill, &ire->ire_addr_v6,
27926 				    B_FALSE);
27927 			} else {
27928 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
27929 			}
27930 			if (nce != NULL) {
27931 				/*
27932 				 * We have to protect nce_res_mp here
27933 				 * from being accessed by other threads
27934 				 * while we change the mblk pointer.
27935 				 * Other functions will also lock the nce when
27936 				 * accessing nce_res_mp.
27937 				 *
27938 				 * The reason we change the mblk pointer
27939 				 * here rather than copying the resolved address
27940 				 * into the template is that, unlike with
27941 				 * ethernet, we have no guarantee that the
27942 				 * resolved address length will be
27943 				 * smaller than or equal to the lla length
27944 				 * with which the template was allocated,
27945 				 * (for ethernet, they're equal)
27946 				 * so we have to use the actual resolved
27947 				 * address mblk - which holds the real
27948 				 * dl_unitdata_req with the resolved address.
27949 				 *
27950 				 * Doing this is the same behavior as was
27951 				 * previously used in the v4 ARP case.
27952 				 */
27953 				mutex_enter(&nce->nce_lock);
27954 				if (nce->nce_res_mp != NULL)
27955 					freemsg(nce->nce_res_mp);
27956 				nce->nce_res_mp = mp1;
27957 				mutex_exit(&nce->nce_lock);
27958 				/*
27959 				 * We do a fastpath probe here because
27960 				 * we have resolved the address without
27961 				 * using Neighbor Discovery.
27962 				 * In the non-XRESOLV v6 case, the fastpath
27963 				 * probe is done right after neighbor
27964 				 * discovery completes.
27965 				 */
27966 				if (nce->nce_res_mp != NULL) {
27967 					int res;
27968 					nce_fastpath_list_add(nce);
27969 					res = ill_fastpath_probe(ill,
27970 					    nce->nce_res_mp);
27971 					if (res != 0 && res != EAGAIN)
27972 						nce_fastpath_list_delete(nce);
27973 				}
27974 
27975 				ire_add_then_send(q, ire, mp);
27976 				/*
27977 				 * Now we have to clean out any packets
27978 				 * that may have been queued on the nce
27979 				 * while it was waiting for address resolution
27980 				 * to complete.
27981 				 */
27982 				mutex_enter(&nce->nce_lock);
27983 				mp1 = nce->nce_qd_mp;
27984 				nce->nce_qd_mp = NULL;
27985 				mutex_exit(&nce->nce_lock);
27986 				while (mp1 != NULL) {
27987 					mblk_t *nxt_mp;
27988 					queue_t *fwdq = NULL;
27989 					ill_t   *inbound_ill;
27990 					uint_t ifindex;
27991 
27992 					nxt_mp = mp1->b_next;
27993 					mp1->b_next = NULL;
27994 					/*
27995 					 * Retrieve ifindex stored in
27996 					 * ip_rput_data_v6()
27997 					 */
27998 					ifindex =
27999 					    (uint_t)(uintptr_t)mp1->b_prev;
28000 					inbound_ill =
28001 					    ill_lookup_on_ifindex(ifindex,
28002 					    B_TRUE, NULL, NULL, NULL,
28003 					    NULL, ipst);
28004 					mp1->b_prev = NULL;
28005 					if (inbound_ill != NULL)
28006 						fwdq = inbound_ill->ill_rq;
28007 
28008 					if (fwdq != NULL) {
28009 						put(fwdq, mp1);
28010 						ill_refrele(inbound_ill);
28011 					} else
28012 						put(WR(ill->ill_rq), mp1);
28013 					mp1 = nxt_mp;
28014 				}
28015 				NCE_REFRELE(nce);
28016 			} else {	/* nce is NULL; clean up */
28017 				ire_delete(ire);
28018 				freemsg(mp);
28019 				freemsg(mp1);
28020 				return;
28021 			}
28022 		} else {
28023 			nce_t *arpce;
28024 			/*
28025 			 * Link layer resolution succeeded. Recompute the
28026 			 * ire_nce.
28027 			 */
28028 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
28029 			if ((arpce = ndp_lookup_v4(ill,
28030 			    (ire->ire_gateway_addr != INADDR_ANY ?
28031 			    &ire->ire_gateway_addr : &ire->ire_addr),
28032 			    B_FALSE)) == NULL) {
28033 				freeb(ire->ire_mp);
28034 				freeb(mp1);
28035 				freemsg(mp);
28036 				return;
28037 			}
28038 			mutex_enter(&arpce->nce_lock);
28039 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
28040 			if (arpce->nce_state == ND_REACHABLE) {
28041 				/*
28042 				 * Someone resolved this before us;
28043 				 * cleanup the res_mp. Since ire has
28044 				 * not been added yet, the call to ire_add_v4
28045 				 * from ire_add_then_send (when a dup is
28046 				 * detected) will clean up the ire.
28047 				 */
28048 				freeb(mp1);
28049 			} else {
28050 				if (arpce->nce_res_mp != NULL)
28051 					freemsg(arpce->nce_res_mp);
28052 				arpce->nce_res_mp = mp1;
28053 				arpce->nce_state = ND_REACHABLE;
28054 			}
28055 			mutex_exit(&arpce->nce_lock);
28056 			if (ire->ire_marks & IRE_MARK_NOADD) {
28057 				/*
28058 				 * this ire will not be added to the ire
28059 				 * cache table, so we can set the ire_nce
28060 				 * here, as there are no atomicity constraints.
28061 				 */
28062 				ire->ire_nce = arpce;
28063 				/*
28064 				 * We are associating this nce with the ire
28065 				 * so change the nce ref taken in
28066 				 * ndp_lookup_v4() from
28067 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
28068 				 */
28069 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
28070 			} else {
28071 				NCE_REFRELE(arpce);
28072 			}
28073 			ire_add_then_send(q, ire, mp);
28074 		}
28075 		return;	/* All is well, the packet has been sent. */
28076 	}
28077 	case IRE_ARPRESOLVE_TYPE: {
28078 
28079 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
28080 			break;
28081 		mp1 = mp->b_cont;		/* dl_unitdata_req */
28082 		mp->b_cont = NULL;
28083 		/*
28084 		 * First, check to make sure the resolution succeeded.
28085 		 * If it failed, the second mblk will be empty.
28086 		 */
28087 		if (mp1->b_rptr == mp1->b_wptr) {
28088 			/* cleanup  the incomplete ire, free queued packets */
28089 			freemsg(mp); /* fake ire */
28090 			freeb(mp1);  /* dl_unitdata response */
28091 			return;
28092 		}
28093 
28094 		/*
28095 		 * update any incomplete nce_t found. we lookup the ctable
28096 		 * and find the nce from the ire->ire_nce because we need
28097 		 * to pass the ire to ip_xmit_v4 later, and can find both
28098 		 * ire and nce in one lookup from the ctable.
28099 		 */
28100 		fake_ire = (ire_t *)mp->b_rptr;
28101 		/*
28102 		 * By the time we come back here from ARP
28103 		 * the logical outgoing interface  of the incomplete ire
28104 		 * we added in ire_forward could have disappeared,
28105 		 * causing the incomplete ire to also have
28106 		 * dissapeared. So we need to retreive the
28107 		 * proper ipif for the ire  before looking
28108 		 * in ctable;  do the ctablelookup based on ire_ipif_seqid
28109 		 */
28110 		ill = q->q_ptr;
28111 
28112 		/* Get the outgoing ipif */
28113 		mutex_enter(&ill->ill_lock);
28114 		if (ill->ill_state_flags & ILL_CONDEMNED) {
28115 			mutex_exit(&ill->ill_lock);
28116 			freemsg(mp); /* fake ire */
28117 			freeb(mp1);  /* dl_unitdata response */
28118 			return;
28119 		}
28120 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
28121 
28122 		if (ipif == NULL) {
28123 			mutex_exit(&ill->ill_lock);
28124 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
28125 			freemsg(mp);
28126 			freeb(mp1);
28127 			return;
28128 		}
28129 		ipif_refhold_locked(ipif);
28130 		mutex_exit(&ill->ill_lock);
28131 		ire = ire_ctable_lookup(fake_ire->ire_addr,
28132 		    fake_ire->ire_gateway_addr, IRE_CACHE,
28133 		    ipif, fake_ire->ire_zoneid, NULL,
28134 		    (MATCH_IRE_GW|MATCH_IRE_IPIF|MATCH_IRE_ZONEONLY), ipst);
28135 		ipif_refrele(ipif);
28136 		if (ire == NULL) {
28137 			/*
28138 			 * no ire was found; check if there is an nce
28139 			 * for this lookup; if it has no ire's pointing at it
28140 			 * cleanup.
28141 			 */
28142 			if ((nce = ndp_lookup_v4(ill,
28143 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
28144 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
28145 			    B_FALSE)) != NULL) {
28146 				/*
28147 				 * cleanup:
28148 				 * We check for refcnt 2 (one for the nce
28149 				 * hash list + 1 for the ref taken by
28150 				 * ndp_lookup_v4) to check that there are
28151 				 * no ire's pointing at the nce.
28152 				 */
28153 				if (nce->nce_refcnt == 2)
28154 					ndp_delete(nce);
28155 				NCE_REFRELE(nce);
28156 			}
28157 			freeb(mp1);  /* dl_unitdata response */
28158 			freemsg(mp); /* fake ire */
28159 			return;
28160 		}
28161 		nce = ire->ire_nce;
28162 		DTRACE_PROBE2(ire__arpresolve__type,
28163 		    ire_t *, ire, nce_t *, nce);
28164 		ASSERT(nce->nce_state != ND_INITIAL);
28165 		mutex_enter(&nce->nce_lock);
28166 		nce->nce_last = TICK_TO_MSEC(lbolt64);
28167 		if (nce->nce_state == ND_REACHABLE) {
28168 			/*
28169 			 * Someone resolved this before us;
28170 			 * our response is not needed any more.
28171 			 */
28172 			mutex_exit(&nce->nce_lock);
28173 			freeb(mp1);  /* dl_unitdata response */
28174 		} else {
28175 			if (nce->nce_res_mp != NULL) {
28176 				freemsg(nce->nce_res_mp);
28177 				/* existing dl_unitdata template */
28178 			}
28179 			nce->nce_res_mp = mp1;
28180 			nce->nce_state = ND_REACHABLE;
28181 			mutex_exit(&nce->nce_lock);
28182 			nce_fastpath(nce);
28183 		}
28184 		/*
28185 		 * The cached nce_t has been updated to be reachable;
28186 		 * Set the IRE_MARK_UNCACHED flag and free the fake_ire.
28187 		 */
28188 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
28189 		freemsg(mp);
28190 		/*
28191 		 * send out queued packets.
28192 		 */
28193 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
28194 
28195 		IRE_REFRELE(ire);
28196 		return;
28197 	}
28198 	default:
28199 		break;
28200 	}
28201 	if (q->q_next) {
28202 		putnext(q, mp);
28203 	} else
28204 		freemsg(mp);
28205 	return;
28206 
28207 protonak:
28208 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
28209 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
28210 		qreply(q, mp);
28211 }
28212 
28213 /*
28214  * Process IP options in an outbound packet.  Modify the destination if there
28215  * is a source route option.
28216  * Returns non-zero if something fails in which case an ICMP error has been
28217  * sent and mp freed.
28218  */
28219 static int
28220 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
28221     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
28222 {
28223 	ipoptp_t	opts;
28224 	uchar_t		*opt;
28225 	uint8_t		optval;
28226 	uint8_t		optlen;
28227 	ipaddr_t	dst;
28228 	intptr_t	code = 0;
28229 	mblk_t		*mp;
28230 	ire_t		*ire = NULL;
28231 
28232 	ip2dbg(("ip_wput_options\n"));
28233 	mp = ipsec_mp;
28234 	if (mctl_present) {
28235 		mp = ipsec_mp->b_cont;
28236 	}
28237 
28238 	dst = ipha->ipha_dst;
28239 	for (optval = ipoptp_first(&opts, ipha);
28240 	    optval != IPOPT_EOL;
28241 	    optval = ipoptp_next(&opts)) {
28242 		opt = opts.ipoptp_cur;
28243 		optlen = opts.ipoptp_len;
28244 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
28245 		    optval, optlen));
28246 		switch (optval) {
28247 			uint32_t off;
28248 		case IPOPT_SSRR:
28249 		case IPOPT_LSRR:
28250 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28251 				ip1dbg((
28252 				    "ip_wput_options: bad option offset\n"));
28253 				code = (char *)&opt[IPOPT_OLEN] -
28254 				    (char *)ipha;
28255 				goto param_prob;
28256 			}
28257 			off = opt[IPOPT_OFFSET];
28258 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
28259 			    ntohl(dst)));
28260 			/*
28261 			 * For strict: verify that dst is directly
28262 			 * reachable.
28263 			 */
28264 			if (optval == IPOPT_SSRR) {
28265 				ire = ire_ftable_lookup(dst, 0, 0,
28266 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
28267 				    MBLK_GETLABEL(mp),
28268 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
28269 				if (ire == NULL) {
28270 					ip1dbg(("ip_wput_options: SSRR not"
28271 					    " directly reachable: 0x%x\n",
28272 					    ntohl(dst)));
28273 					goto bad_src_route;
28274 				}
28275 				ire_refrele(ire);
28276 			}
28277 			break;
28278 		case IPOPT_RR:
28279 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28280 				ip1dbg((
28281 				    "ip_wput_options: bad option offset\n"));
28282 				code = (char *)&opt[IPOPT_OLEN] -
28283 				    (char *)ipha;
28284 				goto param_prob;
28285 			}
28286 			break;
28287 		case IPOPT_TS:
28288 			/*
28289 			 * Verify that length >=5 and that there is either
28290 			 * room for another timestamp or that the overflow
28291 			 * counter is not maxed out.
28292 			 */
28293 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
28294 			if (optlen < IPOPT_MINLEN_IT) {
28295 				goto param_prob;
28296 			}
28297 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28298 				ip1dbg((
28299 				    "ip_wput_options: bad option offset\n"));
28300 				code = (char *)&opt[IPOPT_OFFSET] -
28301 				    (char *)ipha;
28302 				goto param_prob;
28303 			}
28304 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
28305 			case IPOPT_TS_TSONLY:
28306 				off = IPOPT_TS_TIMELEN;
28307 				break;
28308 			case IPOPT_TS_TSANDADDR:
28309 			case IPOPT_TS_PRESPEC:
28310 			case IPOPT_TS_PRESPEC_RFC791:
28311 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
28312 				break;
28313 			default:
28314 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
28315 				    (char *)ipha;
28316 				goto param_prob;
28317 			}
28318 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
28319 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
28320 				/*
28321 				 * No room and the overflow counter is 15
28322 				 * already.
28323 				 */
28324 				goto param_prob;
28325 			}
28326 			break;
28327 		}
28328 	}
28329 
28330 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
28331 		return (0);
28332 
28333 	ip1dbg(("ip_wput_options: error processing IP options."));
28334 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
28335 
28336 param_prob:
28337 	/*
28338 	 * Since ip_wput() isn't close to finished, we fill
28339 	 * in enough of the header for credible error reporting.
28340 	 */
28341 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28342 		/* Failed */
28343 		freemsg(ipsec_mp);
28344 		return (-1);
28345 	}
28346 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
28347 	return (-1);
28348 
28349 bad_src_route:
28350 	/*
28351 	 * Since ip_wput() isn't close to finished, we fill
28352 	 * in enough of the header for credible error reporting.
28353 	 */
28354 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28355 		/* Failed */
28356 		freemsg(ipsec_mp);
28357 		return (-1);
28358 	}
28359 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
28360 	return (-1);
28361 }
28362 
28363 /*
28364  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
28365  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
28366  * thru /etc/system.
28367  */
28368 #define	CONN_MAXDRAINCNT	64
28369 
28370 static void
28371 conn_drain_init(ip_stack_t *ipst)
28372 {
28373 	int i;
28374 
28375 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
28376 
28377 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
28378 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
28379 		/*
28380 		 * Default value of the number of drainers is the
28381 		 * number of cpus, subject to maximum of 8 drainers.
28382 		 */
28383 		if (boot_max_ncpus != -1)
28384 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
28385 		else
28386 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
28387 	}
28388 
28389 	ipst->ips_conn_drain_list = kmem_zalloc(ipst->ips_conn_drain_list_cnt *
28390 	    sizeof (idl_t), KM_SLEEP);
28391 
28392 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28393 		mutex_init(&ipst->ips_conn_drain_list[i].idl_lock, NULL,
28394 		    MUTEX_DEFAULT, NULL);
28395 	}
28396 }
28397 
28398 static void
28399 conn_drain_fini(ip_stack_t *ipst)
28400 {
28401 	int i;
28402 
28403 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++)
28404 		mutex_destroy(&ipst->ips_conn_drain_list[i].idl_lock);
28405 	kmem_free(ipst->ips_conn_drain_list,
28406 	    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
28407 	ipst->ips_conn_drain_list = NULL;
28408 }
28409 
28410 /*
28411  * Note: For an overview of how flowcontrol is handled in IP please see the
28412  * IP Flowcontrol notes at the top of this file.
28413  *
28414  * Flow control has blocked us from proceeding. Insert the given conn in one
28415  * of the conn drain lists. These conn wq's will be qenabled later on when
28416  * STREAMS flow control does a backenable. conn_walk_drain will enable
28417  * the first conn in each of these drain lists. Each of these qenabled conns
28418  * in turn enables the next in the list, after it runs, or when it closes,
28419  * thus sustaining the drain process.
28420  *
28421  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
28422  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
28423  * running at any time, on a given conn, since there can be only 1 service proc
28424  * running on a queue at any time.
28425  */
28426 void
28427 conn_drain_insert(conn_t *connp)
28428 {
28429 	idl_t	*idl;
28430 	uint_t	index;
28431 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28432 
28433 	mutex_enter(&connp->conn_lock);
28434 	if (connp->conn_state_flags & CONN_CLOSING) {
28435 		/*
28436 		 * The conn is closing as a result of which CONN_CLOSING
28437 		 * is set. Return.
28438 		 */
28439 		mutex_exit(&connp->conn_lock);
28440 		return;
28441 	} else if (connp->conn_idl == NULL) {
28442 		/*
28443 		 * Assign the next drain list round robin. We dont' use
28444 		 * a lock, and thus it may not be strictly round robin.
28445 		 * Atomicity of load/stores is enough to make sure that
28446 		 * conn_drain_list_index is always within bounds.
28447 		 */
28448 		index = ipst->ips_conn_drain_list_index;
28449 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
28450 		connp->conn_idl = &ipst->ips_conn_drain_list[index];
28451 		index++;
28452 		if (index == ipst->ips_conn_drain_list_cnt)
28453 			index = 0;
28454 		ipst->ips_conn_drain_list_index = index;
28455 	}
28456 	mutex_exit(&connp->conn_lock);
28457 
28458 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28459 	if ((connp->conn_drain_prev != NULL) ||
28460 	    (connp->conn_state_flags & CONN_CLOSING)) {
28461 		/*
28462 		 * The conn is already in the drain list, OR
28463 		 * the conn is closing. We need to check again for
28464 		 * the closing case again since close can happen
28465 		 * after we drop the conn_lock, and before we
28466 		 * acquire the CONN_DRAIN_LIST_LOCK.
28467 		 */
28468 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28469 		return;
28470 	} else {
28471 		idl = connp->conn_idl;
28472 	}
28473 
28474 	/*
28475 	 * The conn is not in the drain list. Insert it at the
28476 	 * tail of the drain list. The drain list is circular
28477 	 * and doubly linked. idl_conn points to the 1st element
28478 	 * in the list.
28479 	 */
28480 	if (idl->idl_conn == NULL) {
28481 		idl->idl_conn = connp;
28482 		connp->conn_drain_next = connp;
28483 		connp->conn_drain_prev = connp;
28484 	} else {
28485 		conn_t *head = idl->idl_conn;
28486 
28487 		connp->conn_drain_next = head;
28488 		connp->conn_drain_prev = head->conn_drain_prev;
28489 		head->conn_drain_prev->conn_drain_next = connp;
28490 		head->conn_drain_prev = connp;
28491 	}
28492 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28493 }
28494 
28495 /*
28496  * This conn is closing, and we are called from ip_close. OR
28497  * This conn has been serviced by ip_wsrv, and we need to do the tail
28498  * processing.
28499  * If this conn is part of the drain list, we may need to sustain the drain
28500  * process by qenabling the next conn in the drain list. We may also need to
28501  * remove this conn from the list, if it is done.
28502  */
28503 static void
28504 conn_drain_tail(conn_t *connp, boolean_t closing)
28505 {
28506 	idl_t *idl;
28507 
28508 	/*
28509 	 * connp->conn_idl is stable at this point, and no lock is needed
28510 	 * to check it. If we are called from ip_close, close has already
28511 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28512 	 * called us only because conn_idl is non-null. If we are called thru
28513 	 * service, conn_idl could be null, but it cannot change because
28514 	 * service is single-threaded per queue, and there cannot be another
28515 	 * instance of service trying to call conn_drain_insert on this conn
28516 	 * now.
28517 	 */
28518 	ASSERT(!closing || (connp->conn_idl != NULL));
28519 
28520 	/*
28521 	 * If connp->conn_idl is null, the conn has not been inserted into any
28522 	 * drain list even once since creation of the conn. Just return.
28523 	 */
28524 	if (connp->conn_idl == NULL)
28525 		return;
28526 
28527 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28528 
28529 	if (connp->conn_drain_prev == NULL) {
28530 		/* This conn is currently not in the drain list.  */
28531 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28532 		return;
28533 	}
28534 	idl = connp->conn_idl;
28535 	if (idl->idl_conn_draining == connp) {
28536 		/*
28537 		 * This conn is the current drainer. If this is the last conn
28538 		 * in the drain list, we need to do more checks, in the 'if'
28539 		 * below. Otherwwise we need to just qenable the next conn,
28540 		 * to sustain the draining, and is handled in the 'else'
28541 		 * below.
28542 		 */
28543 		if (connp->conn_drain_next == idl->idl_conn) {
28544 			/*
28545 			 * This conn is the last in this list. This round
28546 			 * of draining is complete. If idl_repeat is set,
28547 			 * it means another flow enabling has happened from
28548 			 * the driver/streams and we need to another round
28549 			 * of draining.
28550 			 * If there are more than 2 conns in the drain list,
28551 			 * do a left rotate by 1, so that all conns except the
28552 			 * conn at the head move towards the head by 1, and the
28553 			 * the conn at the head goes to the tail. This attempts
28554 			 * a more even share for all queues that are being
28555 			 * drained.
28556 			 */
28557 			if ((connp->conn_drain_next != connp) &&
28558 			    (idl->idl_conn->conn_drain_next != connp)) {
28559 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28560 			}
28561 			if (idl->idl_repeat) {
28562 				qenable(idl->idl_conn->conn_wq);
28563 				idl->idl_conn_draining = idl->idl_conn;
28564 				idl->idl_repeat = 0;
28565 			} else {
28566 				idl->idl_conn_draining = NULL;
28567 			}
28568 		} else {
28569 			/*
28570 			 * If the next queue that we are now qenable'ing,
28571 			 * is closing, it will remove itself from this list
28572 			 * and qenable the subsequent queue in ip_close().
28573 			 * Serialization is acheived thru idl_lock.
28574 			 */
28575 			qenable(connp->conn_drain_next->conn_wq);
28576 			idl->idl_conn_draining = connp->conn_drain_next;
28577 		}
28578 	}
28579 	if (!connp->conn_did_putbq || closing) {
28580 		/*
28581 		 * Remove ourself from the drain list, if we did not do
28582 		 * a putbq, or if the conn is closing.
28583 		 * Note: It is possible that q->q_first is non-null. It means
28584 		 * that these messages landed after we did a enableok() in
28585 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28586 		 * service them.
28587 		 */
28588 		if (connp->conn_drain_next == connp) {
28589 			/* Singleton in the list */
28590 			ASSERT(connp->conn_drain_prev == connp);
28591 			idl->idl_conn = NULL;
28592 			idl->idl_conn_draining = NULL;
28593 		} else {
28594 			connp->conn_drain_prev->conn_drain_next =
28595 			    connp->conn_drain_next;
28596 			connp->conn_drain_next->conn_drain_prev =
28597 			    connp->conn_drain_prev;
28598 			if (idl->idl_conn == connp)
28599 				idl->idl_conn = connp->conn_drain_next;
28600 			ASSERT(idl->idl_conn_draining != connp);
28601 
28602 		}
28603 		connp->conn_drain_next = NULL;
28604 		connp->conn_drain_prev = NULL;
28605 	}
28606 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28607 }
28608 
28609 /*
28610  * Write service routine. Shared perimeter entry point.
28611  * ip_wsrv can be called in any of the following ways.
28612  * 1. The device queue's messages has fallen below the low water mark
28613  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28614  *    the drain lists and backenable the first conn in each list.
28615  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28616  *    qenabled non-tcp upper layers. We start dequeing messages and call
28617  *    ip_wput for each message.
28618  */
28619 
28620 void
28621 ip_wsrv(queue_t *q)
28622 {
28623 	conn_t	*connp;
28624 	ill_t	*ill;
28625 	mblk_t	*mp;
28626 
28627 	if (q->q_next) {
28628 		ill = (ill_t *)q->q_ptr;
28629 		if (ill->ill_state_flags == 0) {
28630 			/*
28631 			 * The device flow control has opened up.
28632 			 * Walk through conn drain lists and qenable the
28633 			 * first conn in each list. This makes sense only
28634 			 * if the stream is fully plumbed and setup.
28635 			 * Hence the if check above.
28636 			 */
28637 			ip1dbg(("ip_wsrv: walking\n"));
28638 			conn_walk_drain(ill->ill_ipst);
28639 		}
28640 		return;
28641 	}
28642 
28643 	connp = Q_TO_CONN(q);
28644 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28645 
28646 	/*
28647 	 * 1. Set conn_draining flag to signal that service is active.
28648 	 *
28649 	 * 2. ip_output determines whether it has been called from service,
28650 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28651 	 *    has been called from service.
28652 	 *
28653 	 * 3. Message ordering is preserved by the following logic.
28654 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28655 	 *    the message at the tail, if conn_draining is set (i.e. service
28656 	 *    is running) or if q->q_first is non-null.
28657 	 *
28658 	 *    ii. If ip_output is called from service, and if ip_output cannot
28659 	 *    putnext due to flow control, it does a putbq.
28660 	 *
28661 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28662 	 *    (causing an infinite loop).
28663 	 */
28664 	ASSERT(!connp->conn_did_putbq);
28665 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28666 		connp->conn_draining = 1;
28667 		noenable(q);
28668 		while ((mp = getq(q)) != NULL) {
28669 			ASSERT(CONN_Q(q));
28670 
28671 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28672 			if (connp->conn_did_putbq) {
28673 				/* ip_wput did a putbq */
28674 				break;
28675 			}
28676 		}
28677 		/*
28678 		 * At this point, a thread coming down from top, calling
28679 		 * ip_wput, may end up queueing the message. We have not yet
28680 		 * enabled the queue, so ip_wsrv won't be called again.
28681 		 * To avoid this race, check q->q_first again (in the loop)
28682 		 * If the other thread queued the message before we call
28683 		 * enableok(), we will catch it in the q->q_first check.
28684 		 * If the other thread queues the message after we call
28685 		 * enableok(), ip_wsrv will be called again by STREAMS.
28686 		 */
28687 		connp->conn_draining = 0;
28688 		enableok(q);
28689 	}
28690 
28691 	/* Enable the next conn for draining */
28692 	conn_drain_tail(connp, B_FALSE);
28693 
28694 	connp->conn_did_putbq = 0;
28695 }
28696 
28697 /*
28698  * Walk the list of all conn's calling the function provided with the
28699  * specified argument for each.	 Note that this only walks conn's that
28700  * have been bound.
28701  * Applies to both IPv4 and IPv6.
28702  */
28703 static void
28704 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid, ip_stack_t *ipst)
28705 {
28706 	conn_walk_fanout_table(ipst->ips_ipcl_udp_fanout,
28707 	    ipst->ips_ipcl_udp_fanout_size,
28708 	    func, arg, zoneid);
28709 	conn_walk_fanout_table(ipst->ips_ipcl_conn_fanout,
28710 	    ipst->ips_ipcl_conn_fanout_size,
28711 	    func, arg, zoneid);
28712 	conn_walk_fanout_table(ipst->ips_ipcl_bind_fanout,
28713 	    ipst->ips_ipcl_bind_fanout_size,
28714 	    func, arg, zoneid);
28715 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout,
28716 	    IPPROTO_MAX, func, arg, zoneid);
28717 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout_v6,
28718 	    IPPROTO_MAX, func, arg, zoneid);
28719 }
28720 
28721 /*
28722  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28723  * of conns that need to be drained, check if drain is already in progress.
28724  * If so set the idl_repeat bit, indicating that the last conn in the list
28725  * needs to reinitiate the drain once again, for the list. If drain is not
28726  * in progress for the list, initiate the draining, by qenabling the 1st
28727  * conn in the list. The drain is self-sustaining, each qenabled conn will
28728  * in turn qenable the next conn, when it is done/blocked/closing.
28729  */
28730 static void
28731 conn_walk_drain(ip_stack_t *ipst)
28732 {
28733 	int i;
28734 	idl_t *idl;
28735 
28736 	IP_STAT(ipst, ip_conn_walk_drain);
28737 
28738 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28739 		idl = &ipst->ips_conn_drain_list[i];
28740 		mutex_enter(&idl->idl_lock);
28741 		if (idl->idl_conn == NULL) {
28742 			mutex_exit(&idl->idl_lock);
28743 			continue;
28744 		}
28745 		/*
28746 		 * If this list is not being drained currently by
28747 		 * an ip_wsrv thread, start the process.
28748 		 */
28749 		if (idl->idl_conn_draining == NULL) {
28750 			ASSERT(idl->idl_repeat == 0);
28751 			qenable(idl->idl_conn->conn_wq);
28752 			idl->idl_conn_draining = idl->idl_conn;
28753 		} else {
28754 			idl->idl_repeat = 1;
28755 		}
28756 		mutex_exit(&idl->idl_lock);
28757 	}
28758 }
28759 
28760 /*
28761  * Walk an conn hash table of `count' buckets, calling func for each entry.
28762  */
28763 static void
28764 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
28765     zoneid_t zoneid)
28766 {
28767 	conn_t	*connp;
28768 
28769 	while (count-- > 0) {
28770 		mutex_enter(&connfp->connf_lock);
28771 		for (connp = connfp->connf_head; connp != NULL;
28772 		    connp = connp->conn_next) {
28773 			if (zoneid == GLOBAL_ZONEID ||
28774 			    zoneid == connp->conn_zoneid) {
28775 				CONN_INC_REF(connp);
28776 				mutex_exit(&connfp->connf_lock);
28777 				(*func)(connp, arg);
28778 				mutex_enter(&connfp->connf_lock);
28779 				CONN_DEC_REF(connp);
28780 			}
28781 		}
28782 		mutex_exit(&connfp->connf_lock);
28783 		connfp++;
28784 	}
28785 }
28786 
28787 /* ipcl_walk routine invoked for ip_conn_report for each conn. */
28788 static void
28789 conn_report1(conn_t *connp, void *mp)
28790 {
28791 	char	buf1[INET6_ADDRSTRLEN];
28792 	char	buf2[INET6_ADDRSTRLEN];
28793 	uint_t	print_len, buf_len;
28794 
28795 	ASSERT(connp != NULL);
28796 
28797 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
28798 	if (buf_len <= 0)
28799 		return;
28800 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1));
28801 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2));
28802 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
28803 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
28804 	    "%5d %s/%05d %s/%05d\n",
28805 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
28806 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
28807 	    buf1, connp->conn_lport,
28808 	    buf2, connp->conn_fport);
28809 	if (print_len < buf_len) {
28810 		((mblk_t *)mp)->b_wptr += print_len;
28811 	} else {
28812 		((mblk_t *)mp)->b_wptr += buf_len;
28813 	}
28814 }
28815 
28816 /*
28817  * Named Dispatch routine to produce a formatted report on all conns
28818  * that are listed in one of the fanout tables.
28819  * This report is accessed by using the ndd utility to "get" ND variable
28820  * "ip_conn_status".
28821  */
28822 /* ARGSUSED */
28823 static int
28824 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
28825 {
28826 	conn_t *connp = Q_TO_CONN(q);
28827 
28828 	(void) mi_mpprintf(mp,
28829 	    "CONN      " MI_COL_HDRPAD_STR
28830 	    "rfq      " MI_COL_HDRPAD_STR
28831 	    "stq      " MI_COL_HDRPAD_STR
28832 	    " zone local                 remote");
28833 
28834 	/*
28835 	 * Because of the ndd constraint, at most we can have 64K buffer
28836 	 * to put in all conn info.  So to be more efficient, just
28837 	 * allocate a 64K buffer here, assuming we need that large buffer.
28838 	 * This should be OK as only privileged processes can do ndd /dev/ip.
28839 	 */
28840 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
28841 		/* The following may work even if we cannot get a large buf. */
28842 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
28843 		return (0);
28844 	}
28845 
28846 	conn_walk_fanout(conn_report1, mp->b_cont, connp->conn_zoneid,
28847 	    connp->conn_netstack->netstack_ip);
28848 	return (0);
28849 }
28850 
28851 /*
28852  * Determine if the ill and multicast aspects of that packets
28853  * "matches" the conn.
28854  */
28855 boolean_t
28856 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28857     zoneid_t zoneid)
28858 {
28859 	ill_t *in_ill;
28860 	boolean_t found;
28861 	ipif_t *ipif;
28862 	ire_t *ire;
28863 	ipaddr_t dst, src;
28864 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28865 
28866 	dst = ipha->ipha_dst;
28867 	src = ipha->ipha_src;
28868 
28869 	/*
28870 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28871 	 * unicast, broadcast and multicast reception to
28872 	 * conn_incoming_ill. conn_wantpacket itself is called
28873 	 * only for BROADCAST and multicast.
28874 	 *
28875 	 * 1) ip_rput supresses duplicate broadcasts if the ill
28876 	 *    is part of a group. Hence, we should be receiving
28877 	 *    just one copy of broadcast for the whole group.
28878 	 *    Thus, if it is part of the group the packet could
28879 	 *    come on any ill of the group and hence we need a
28880 	 *    match on the group. Otherwise, match on ill should
28881 	 *    be sufficient.
28882 	 *
28883 	 * 2) ip_rput does not suppress duplicate multicast packets.
28884 	 *    If there are two interfaces in a ill group and we have
28885 	 *    2 applications (conns) joined a multicast group G on
28886 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
28887 	 *    will give us two packets because we join G on both the
28888 	 *    interfaces rather than nominating just one interface
28889 	 *    for receiving multicast like broadcast above. So,
28890 	 *    we have to call ilg_lookup_ill to filter out duplicate
28891 	 *    copies, if ill is part of a group.
28892 	 */
28893 	in_ill = connp->conn_incoming_ill;
28894 	if (in_ill != NULL) {
28895 		if (in_ill->ill_group == NULL) {
28896 			if (in_ill != ill)
28897 				return (B_FALSE);
28898 		} else if (in_ill->ill_group != ill->ill_group) {
28899 			return (B_FALSE);
28900 		}
28901 	}
28902 
28903 	if (!CLASSD(dst)) {
28904 		if (IPCL_ZONE_MATCH(connp, zoneid))
28905 			return (B_TRUE);
28906 		/*
28907 		 * The conn is in a different zone; we need to check that this
28908 		 * broadcast address is configured in the application's zone and
28909 		 * on one ill in the group.
28910 		 */
28911 		ipif = ipif_get_next_ipif(NULL, ill);
28912 		if (ipif == NULL)
28913 			return (B_FALSE);
28914 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28915 		    connp->conn_zoneid, NULL,
28916 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
28917 		ipif_refrele(ipif);
28918 		if (ire != NULL) {
28919 			ire_refrele(ire);
28920 			return (B_TRUE);
28921 		} else {
28922 			return (B_FALSE);
28923 		}
28924 	}
28925 
28926 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28927 	    connp->conn_zoneid == zoneid) {
28928 		/*
28929 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28930 		 * disabled, therefore we don't dispatch the multicast packet to
28931 		 * the sending zone.
28932 		 */
28933 		return (B_FALSE);
28934 	}
28935 
28936 	if (IS_LOOPBACK(ill) && connp->conn_zoneid != zoneid) {
28937 		/*
28938 		 * Multicast packet on the loopback interface: we only match
28939 		 * conns who joined the group in the specified zone.
28940 		 */
28941 		return (B_FALSE);
28942 	}
28943 
28944 	if (connp->conn_multi_router) {
28945 		/* multicast packet and multicast router socket: send up */
28946 		return (B_TRUE);
28947 	}
28948 
28949 	mutex_enter(&connp->conn_lock);
28950 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28951 	mutex_exit(&connp->conn_lock);
28952 	return (found);
28953 }
28954 
28955 /*
28956  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28957  */
28958 /* ARGSUSED */
28959 static void
28960 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28961 {
28962 	ill_t *ill = (ill_t *)q->q_ptr;
28963 	mblk_t	*mp1, *mp2;
28964 	ipif_t  *ipif;
28965 	int err = 0;
28966 	conn_t *connp = NULL;
28967 	ipsq_t	*ipsq;
28968 	arc_t	*arc;
28969 
28970 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28971 
28972 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28973 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28974 
28975 	ASSERT(IAM_WRITER_ILL(ill));
28976 	mp2 = mp->b_cont;
28977 	mp->b_cont = NULL;
28978 
28979 	/*
28980 	 * We have now received the arp bringup completion message
28981 	 * from ARP. Mark the arp bringup as done. Also if the arp
28982 	 * stream has already started closing, send up the AR_ARP_CLOSING
28983 	 * ack now since ARP is waiting in close for this ack.
28984 	 */
28985 	mutex_enter(&ill->ill_lock);
28986 	ill->ill_arp_bringup_pending = 0;
28987 	if (ill->ill_arp_closing) {
28988 		mutex_exit(&ill->ill_lock);
28989 		/* Let's reuse the mp for sending the ack */
28990 		arc = (arc_t *)mp->b_rptr;
28991 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28992 		arc->arc_cmd = AR_ARP_CLOSING;
28993 		qreply(q, mp);
28994 	} else {
28995 		mutex_exit(&ill->ill_lock);
28996 		freeb(mp);
28997 	}
28998 
28999 	ipsq = ill->ill_phyint->phyint_ipsq;
29000 	ipif = ipsq->ipsq_pending_ipif;
29001 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
29002 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
29003 	if (mp1 == NULL) {
29004 		/* bringup was aborted by the user */
29005 		freemsg(mp2);
29006 		return;
29007 	}
29008 
29009 	/*
29010 	 * If an IOCTL is waiting on this (ipsq_current_ioctl != 0), then we
29011 	 * must have an associated conn_t.  Otherwise, we're bringing this
29012 	 * interface back up as part of handling an asynchronous event (e.g.,
29013 	 * physical address change).
29014 	 */
29015 	if (ipsq->ipsq_current_ioctl != 0) {
29016 		ASSERT(connp != NULL);
29017 		q = CONNP_TO_WQ(connp);
29018 	} else {
29019 		ASSERT(connp == NULL);
29020 		q = ill->ill_rq;
29021 	}
29022 
29023 	/*
29024 	 * If the DL_BIND_REQ fails, it is noted
29025 	 * in arc_name_offset.
29026 	 */
29027 	err = *((int *)mp2->b_rptr);
29028 	if (err == 0) {
29029 		if (ipif->ipif_isv6) {
29030 			if ((err = ipif_up_done_v6(ipif)) != 0)
29031 				ip0dbg(("ip_arp_done: init failed\n"));
29032 		} else {
29033 			if ((err = ipif_up_done(ipif)) != 0)
29034 				ip0dbg(("ip_arp_done: init failed\n"));
29035 		}
29036 	} else {
29037 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
29038 	}
29039 
29040 	freemsg(mp2);
29041 
29042 	if ((err == 0) && (ill->ill_up_ipifs)) {
29043 		err = ill_up_ipifs(ill, q, mp1);
29044 		if (err == EINPROGRESS)
29045 			return;
29046 	}
29047 
29048 	if (ill->ill_up_ipifs)
29049 		ill_group_cleanup(ill);
29050 
29051 	/*
29052 	 * The operation must complete without EINPROGRESS since
29053 	 * ipsq_pending_mp_get() has removed the mblk from ipsq_pending_mp.
29054 	 * Otherwise, the operation will be stuck forever in the ipsq.
29055 	 */
29056 	ASSERT(err != EINPROGRESS);
29057 	if (ipsq->ipsq_current_ioctl != 0)
29058 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
29059 	else
29060 		ipsq_current_finish(ipsq);
29061 }
29062 
29063 /* Allocate the private structure */
29064 static int
29065 ip_priv_alloc(void **bufp)
29066 {
29067 	void	*buf;
29068 
29069 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
29070 		return (ENOMEM);
29071 
29072 	*bufp = buf;
29073 	return (0);
29074 }
29075 
29076 /* Function to delete the private structure */
29077 void
29078 ip_priv_free(void *buf)
29079 {
29080 	ASSERT(buf != NULL);
29081 	kmem_free(buf, sizeof (ip_priv_t));
29082 }
29083 
29084 /*
29085  * The entry point for IPPF processing.
29086  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
29087  * routine just returns.
29088  *
29089  * When called, ip_process generates an ipp_packet_t structure
29090  * which holds the state information for this packet and invokes the
29091  * the classifier (via ipp_packet_process). The classification, depending on
29092  * configured filters, results in a list of actions for this packet. Invoking
29093  * an action may cause the packet to be dropped, in which case the resulting
29094  * mblk (*mpp) is NULL. proc indicates the callout position for
29095  * this packet and ill_index is the interface this packet on or will leave
29096  * on (inbound and outbound resp.).
29097  */
29098 void
29099 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
29100 {
29101 	mblk_t		*mp;
29102 	ip_priv_t	*priv;
29103 	ipp_action_id_t	aid;
29104 	int		rc = 0;
29105 	ipp_packet_t	*pp;
29106 #define	IP_CLASS	"ip"
29107 
29108 	/* If the classifier is not loaded, return  */
29109 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
29110 		return;
29111 	}
29112 
29113 	mp = *mpp;
29114 	ASSERT(mp != NULL);
29115 
29116 	/* Allocate the packet structure */
29117 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
29118 	if (rc != 0) {
29119 		*mpp = NULL;
29120 		freemsg(mp);
29121 		return;
29122 	}
29123 
29124 	/* Allocate the private structure */
29125 	rc = ip_priv_alloc((void **)&priv);
29126 	if (rc != 0) {
29127 		*mpp = NULL;
29128 		freemsg(mp);
29129 		ipp_packet_free(pp);
29130 		return;
29131 	}
29132 	priv->proc = proc;
29133 	priv->ill_index = ill_index;
29134 	ipp_packet_set_private(pp, priv, ip_priv_free);
29135 	ipp_packet_set_data(pp, mp);
29136 
29137 	/* Invoke the classifier */
29138 	rc = ipp_packet_process(&pp);
29139 	if (pp != NULL) {
29140 		mp = ipp_packet_get_data(pp);
29141 		ipp_packet_free(pp);
29142 		if (rc != 0) {
29143 			freemsg(mp);
29144 			*mpp = NULL;
29145 		}
29146 	} else {
29147 		*mpp = NULL;
29148 	}
29149 #undef	IP_CLASS
29150 }
29151 
29152 /*
29153  * Propagate a multicast group membership operation (add/drop) on
29154  * all the interfaces crossed by the related multirt routes.
29155  * The call is considered successful if the operation succeeds
29156  * on at least one interface.
29157  */
29158 static int
29159 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
29160     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
29161     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
29162     mblk_t *first_mp)
29163 {
29164 	ire_t		*ire_gw;
29165 	irb_t		*irb;
29166 	int		error = 0;
29167 	opt_restart_t	*or;
29168 	ip_stack_t	*ipst = ire->ire_ipst;
29169 
29170 	irb = ire->ire_bucket;
29171 	ASSERT(irb != NULL);
29172 
29173 	ASSERT(DB_TYPE(first_mp) == M_CTL);
29174 
29175 	or = (opt_restart_t *)first_mp->b_rptr;
29176 	IRB_REFHOLD(irb);
29177 	for (; ire != NULL; ire = ire->ire_next) {
29178 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
29179 			continue;
29180 		if (ire->ire_addr != group)
29181 			continue;
29182 
29183 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
29184 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
29185 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
29186 		/* No resolver exists for the gateway; skip this ire. */
29187 		if (ire_gw == NULL)
29188 			continue;
29189 
29190 		/*
29191 		 * This function can return EINPROGRESS. If so the operation
29192 		 * will be restarted from ip_restart_optmgmt which will
29193 		 * call ip_opt_set and option processing will restart for
29194 		 * this option. So we may end up calling 'fn' more than once.
29195 		 * This requires that 'fn' is idempotent except for the
29196 		 * return value. The operation is considered a success if
29197 		 * it succeeds at least once on any one interface.
29198 		 */
29199 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
29200 		    NULL, fmode, src, first_mp);
29201 		if (error == 0)
29202 			or->or_private = CGTP_MCAST_SUCCESS;
29203 
29204 		if (ip_debug > 0) {
29205 			ulong_t	off;
29206 			char	*ksym;
29207 			ksym = kobj_getsymname((uintptr_t)fn, &off);
29208 			ip2dbg(("ip_multirt_apply_membership: "
29209 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
29210 			    "error %d [success %u]\n",
29211 			    ksym ? ksym : "?",
29212 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
29213 			    error, or->or_private));
29214 		}
29215 
29216 		ire_refrele(ire_gw);
29217 		if (error == EINPROGRESS) {
29218 			IRB_REFRELE(irb);
29219 			return (error);
29220 		}
29221 	}
29222 	IRB_REFRELE(irb);
29223 	/*
29224 	 * Consider the call as successful if we succeeded on at least
29225 	 * one interface. Otherwise, return the last encountered error.
29226 	 */
29227 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
29228 }
29229 
29230 
29231 /*
29232  * Issue a warning regarding a route crossing an interface with an
29233  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
29234  * amount of time is logged.
29235  */
29236 static void
29237 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
29238 {
29239 	hrtime_t	current = gethrtime();
29240 	char		buf[INET_ADDRSTRLEN];
29241 	ip_stack_t	*ipst = ire->ire_ipst;
29242 
29243 	/* Convert interval in ms to hrtime in ns */
29244 	if (ipst->ips_multirt_bad_mtu_last_time +
29245 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
29246 	    current) {
29247 		cmn_err(CE_WARN, "ip: ignoring multiroute "
29248 		    "to %s, incorrect MTU %u (expected %u)\n",
29249 		    ip_dot_addr(ire->ire_addr, buf),
29250 		    ire->ire_max_frag, max_frag);
29251 
29252 		ipst->ips_multirt_bad_mtu_last_time = current;
29253 	}
29254 }
29255 
29256 
29257 /*
29258  * Get the CGTP (multirouting) filtering status.
29259  * If 0, the CGTP hooks are transparent.
29260  */
29261 /* ARGSUSED */
29262 static int
29263 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
29264 {
29265 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
29266 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29267 
29268 	/*
29269 	 * Only applies to the shared stack since the filter_ops
29270 	 * do not carry an ip_stack_t or zoneid.
29271 	 */
29272 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
29273 		return (ENOTSUP);
29274 
29275 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
29276 	return (0);
29277 }
29278 
29279 
29280 /*
29281  * Set the CGTP (multirouting) filtering status.
29282  * If the status is changed from active to transparent
29283  * or from transparent to active, forward the new status
29284  * to the filtering module (if loaded).
29285  */
29286 /* ARGSUSED */
29287 static int
29288 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
29289     cred_t *ioc_cr)
29290 {
29291 	long		new_value;
29292 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
29293 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29294 
29295 	if (secpolicy_net_config(ioc_cr, B_FALSE) != 0)
29296 		return (EPERM);
29297 
29298 	/*
29299 	 * Only applies to the shared stack since the filter_ops
29300 	 * do not carry an ip_stack_t or zoneid.
29301 	 */
29302 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
29303 		return (ENOTSUP);
29304 
29305 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
29306 	    new_value < 0 || new_value > 1) {
29307 		return (EINVAL);
29308 	}
29309 
29310 	/*
29311 	 * Do not enable CGTP filtering - thus preventing the hooks
29312 	 * from being invoked - if the version number of the
29313 	 * filtering module hooks does not match.
29314 	 */
29315 	if ((ip_cgtp_filter_ops != NULL) &&
29316 	    (ip_cgtp_filter_ops->cfo_filter_rev != CGTP_FILTER_REV)) {
29317 		cmn_err(CE_WARN, "IP: CGTP filtering version mismatch "
29318 		    "(module hooks version %d, expecting %d)\n",
29319 		    ip_cgtp_filter_ops->cfo_filter_rev,
29320 		    CGTP_FILTER_REV);
29321 		return (ENOTSUP);
29322 	}
29323 
29324 	if ((!*ip_cgtp_filter_value) && new_value) {
29325 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
29326 		    ip_cgtp_filter_ops == NULL ?
29327 		    " (module not loaded)" : "");
29328 	}
29329 	if (*ip_cgtp_filter_value && (!new_value)) {
29330 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
29331 		    ip_cgtp_filter_ops == NULL ?
29332 		    " (module not loaded)" : "");
29333 	}
29334 
29335 	if (ip_cgtp_filter_ops != NULL) {
29336 		int	res;
29337 
29338 		res = ip_cgtp_filter_ops->cfo_change_state(new_value);
29339 		if (res)
29340 			return (res);
29341 	}
29342 
29343 	*ip_cgtp_filter_value = (boolean_t)new_value;
29344 
29345 	return (0);
29346 }
29347 
29348 
29349 /*
29350  * Return the expected CGTP hooks version number.
29351  */
29352 int
29353 ip_cgtp_filter_supported(void)
29354 {
29355 	ip_stack_t *ipst;
29356 	int ret;
29357 
29358 	ipst = netstack_find_by_stackid(GLOBAL_NETSTACKID)->netstack_ip;
29359 	if (ipst == NULL)
29360 		return (-1);
29361 	ret = ip_cgtp_filter_rev;
29362 	netstack_rele(ipst->ips_netstack);
29363 	return (ret);
29364 }
29365 
29366 
29367 /*
29368  * CGTP hooks can be registered by directly touching ip_cgtp_filter_ops
29369  * or by invoking this function. In the first case, the version number
29370  * of the registered structure is checked at hooks activation time
29371  * in ip_cgtp_filter_set().
29372  *
29373  * Only applies to the shared stack since the filter_ops
29374  * do not carry an ip_stack_t or zoneid.
29375  */
29376 int
29377 ip_cgtp_filter_register(cgtp_filter_ops_t *ops)
29378 {
29379 	ip_stack_t *ipst;
29380 
29381 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
29382 		return (ENOTSUP);
29383 
29384 	ipst = netstack_find_by_stackid(GLOBAL_NETSTACKID)->netstack_ip;
29385 	if (ipst == NULL)
29386 		return (EINVAL);
29387 
29388 	ip_cgtp_filter_ops = ops;
29389 	netstack_rele(ipst->ips_netstack);
29390 	return (0);
29391 }
29392 
29393 static squeue_func_t
29394 ip_squeue_switch(int val)
29395 {
29396 	squeue_func_t rval = squeue_fill;
29397 
29398 	switch (val) {
29399 	case IP_SQUEUE_ENTER_NODRAIN:
29400 		rval = squeue_enter_nodrain;
29401 		break;
29402 	case IP_SQUEUE_ENTER:
29403 		rval = squeue_enter;
29404 		break;
29405 	default:
29406 		break;
29407 	}
29408 	return (rval);
29409 }
29410 
29411 /* ARGSUSED */
29412 static int
29413 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
29414     caddr_t addr, cred_t *cr)
29415 {
29416 	int *v = (int *)addr;
29417 	long new_value;
29418 
29419 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29420 		return (EPERM);
29421 
29422 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29423 		return (EINVAL);
29424 
29425 	ip_input_proc = ip_squeue_switch(new_value);
29426 	*v = new_value;
29427 	return (0);
29428 }
29429 
29430 /* ARGSUSED */
29431 static int
29432 ip_int_set(queue_t *q, mblk_t *mp, char *value,
29433     caddr_t addr, cred_t *cr)
29434 {
29435 	int *v = (int *)addr;
29436 	long new_value;
29437 
29438 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29439 		return (EPERM);
29440 
29441 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29442 		return (EINVAL);
29443 
29444 	*v = new_value;
29445 	return (0);
29446 }
29447 
29448 /*
29449  * Handle changes to ipmp_hook_emulation ndd variable.
29450  * Need to update phyint_hook_ifindex.
29451  * Also generate a nic plumb event should a new ifidex be assigned to a group.
29452  */
29453 static void
29454 ipmp_hook_emulation_changed(ip_stack_t *ipst)
29455 {
29456 	phyint_t *phyi;
29457 	phyint_t *phyi_tmp;
29458 	char *groupname;
29459 	int namelen;
29460 	ill_t	*ill;
29461 	boolean_t new_group;
29462 
29463 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29464 	/*
29465 	 * Group indicies are stored in the phyint - a common structure
29466 	 * to both IPv4 and IPv6.
29467 	 */
29468 	phyi = avl_first(&ipst->ips_phyint_g_list->phyint_list_avl_by_index);
29469 	for (; phyi != NULL;
29470 	    phyi = avl_walk(&ipst->ips_phyint_g_list->phyint_list_avl_by_index,
29471 	    phyi, AVL_AFTER)) {
29472 		/* Ignore the ones that do not have a group */
29473 		if (phyi->phyint_groupname_len == 0)
29474 			continue;
29475 
29476 		/*
29477 		 * Look for other phyint in group.
29478 		 * Clear name/namelen so the lookup doesn't find ourselves.
29479 		 */
29480 		namelen = phyi->phyint_groupname_len;
29481 		groupname = phyi->phyint_groupname;
29482 		phyi->phyint_groupname_len = 0;
29483 		phyi->phyint_groupname = NULL;
29484 
29485 		phyi_tmp = phyint_lookup_group(groupname, B_FALSE, ipst);
29486 		/* Restore */
29487 		phyi->phyint_groupname_len = namelen;
29488 		phyi->phyint_groupname = groupname;
29489 
29490 		new_group = B_FALSE;
29491 		if (ipst->ips_ipmp_hook_emulation) {
29492 			/*
29493 			 * If the group already exists and has already
29494 			 * been assigned a group ifindex, we use the existing
29495 			 * group_ifindex, otherwise we pick a new group_ifindex
29496 			 * here.
29497 			 */
29498 			if (phyi_tmp != NULL &&
29499 			    phyi_tmp->phyint_group_ifindex != 0) {
29500 				phyi->phyint_group_ifindex =
29501 				    phyi_tmp->phyint_group_ifindex;
29502 			} else {
29503 				/* XXX We need a recovery strategy here. */
29504 				if (!ip_assign_ifindex(
29505 				    &phyi->phyint_group_ifindex, ipst))
29506 					cmn_err(CE_PANIC,
29507 					    "ip_assign_ifindex() failed");
29508 				new_group = B_TRUE;
29509 			}
29510 		} else {
29511 			phyi->phyint_group_ifindex = 0;
29512 		}
29513 		if (ipst->ips_ipmp_hook_emulation)
29514 			phyi->phyint_hook_ifindex = phyi->phyint_group_ifindex;
29515 		else
29516 			phyi->phyint_hook_ifindex = phyi->phyint_ifindex;
29517 
29518 		/*
29519 		 * For IP Filter to find out the relationship between
29520 		 * names and interface indicies, we need to generate
29521 		 * a NE_PLUMB event when a new group can appear.
29522 		 * We always generate events when a new interface appears
29523 		 * (even when ipmp_hook_emulation is set) so there
29524 		 * is no need to generate NE_PLUMB events when
29525 		 * ipmp_hook_emulation is turned off.
29526 		 * And since it isn't critical for IP Filter to get
29527 		 * the NE_UNPLUMB events we skip those here.
29528 		 */
29529 		if (new_group) {
29530 			/*
29531 			 * First phyint in group - generate group PLUMB event.
29532 			 * Since we are not running inside the ipsq we do
29533 			 * the dispatch immediately.
29534 			 */
29535 			if (phyi->phyint_illv4 != NULL)
29536 				ill = phyi->phyint_illv4;
29537 			else
29538 				ill = phyi->phyint_illv6;
29539 
29540 			if (ill != NULL) {
29541 				mutex_enter(&ill->ill_lock);
29542 				ill_nic_info_plumb(ill, B_TRUE);
29543 				ill_nic_info_dispatch(ill);
29544 				mutex_exit(&ill->ill_lock);
29545 			}
29546 		}
29547 	}
29548 	rw_exit(&ipst->ips_ill_g_lock);
29549 }
29550 
29551 /* ARGSUSED */
29552 static int
29553 ipmp_hook_emulation_set(queue_t *q, mblk_t *mp, char *value,
29554     caddr_t addr, cred_t *cr)
29555 {
29556 	int *v = (int *)addr;
29557 	long new_value;
29558 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29559 
29560 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29561 		return (EINVAL);
29562 
29563 	if (*v != new_value) {
29564 		*v = new_value;
29565 		ipmp_hook_emulation_changed(ipst);
29566 	}
29567 	return (0);
29568 }
29569 
29570 static void *
29571 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
29572 {
29573 	kstat_t *ksp;
29574 
29575 	ip_stat_t template = {
29576 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
29577 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
29578 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
29579 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
29580 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
29581 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
29582 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
29583 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
29584 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
29585 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
29586 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
29587 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
29588 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
29589 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
29590 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
29591 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
29592 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
29593 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
29594 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
29595 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
29596 		{ "ip_opt",			KSTAT_DATA_UINT64 },
29597 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
29598 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
29599 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29600 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29601 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29602 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29603 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29604 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29605 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29606 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29607 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29608 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29609 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29610 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29611 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29612 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29613 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29614 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29615 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29616 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29617 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29618 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29619 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29620 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29621 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29622 	};
29623 
29624 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29625 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29626 	    KSTAT_FLAG_VIRTUAL, stackid);
29627 
29628 	if (ksp == NULL)
29629 		return (NULL);
29630 
29631 	bcopy(&template, ip_statisticsp, sizeof (template));
29632 	ksp->ks_data = (void *)ip_statisticsp;
29633 	ksp->ks_private = (void *)(uintptr_t)stackid;
29634 
29635 	kstat_install(ksp);
29636 	return (ksp);
29637 }
29638 
29639 static void
29640 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29641 {
29642 	if (ksp != NULL) {
29643 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29644 		kstat_delete_netstack(ksp, stackid);
29645 	}
29646 }
29647 
29648 static void *
29649 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29650 {
29651 	kstat_t	*ksp;
29652 
29653 	ip_named_kstat_t template = {
29654 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29655 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29656 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29657 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29658 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29659 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29660 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29661 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29662 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29663 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29664 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29665 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29666 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29667 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29668 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29669 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29670 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29671 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29672 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29673 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29674 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29675 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29676 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29677 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29678 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29679 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29680 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29681 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29682 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29683 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29684 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29685 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29686 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29687 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29688 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29689 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29690 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29691 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29692 	};
29693 
29694 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29695 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
29696 	if (ksp == NULL || ksp->ks_data == NULL)
29697 		return (NULL);
29698 
29699 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29700 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29701 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29702 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29703 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29704 
29705 	template.netToMediaEntrySize.value.i32 =
29706 	    sizeof (mib2_ipNetToMediaEntry_t);
29707 
29708 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29709 
29710 	bcopy(&template, ksp->ks_data, sizeof (template));
29711 	ksp->ks_update = ip_kstat_update;
29712 	ksp->ks_private = (void *)(uintptr_t)stackid;
29713 
29714 	kstat_install(ksp);
29715 	return (ksp);
29716 }
29717 
29718 static void
29719 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29720 {
29721 	if (ksp != NULL) {
29722 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29723 		kstat_delete_netstack(ksp, stackid);
29724 	}
29725 }
29726 
29727 static int
29728 ip_kstat_update(kstat_t *kp, int rw)
29729 {
29730 	ip_named_kstat_t *ipkp;
29731 	mib2_ipIfStatsEntry_t ipmib;
29732 	ill_walk_context_t ctx;
29733 	ill_t *ill;
29734 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29735 	netstack_t	*ns;
29736 	ip_stack_t	*ipst;
29737 
29738 	if (kp == NULL || kp->ks_data == NULL)
29739 		return (EIO);
29740 
29741 	if (rw == KSTAT_WRITE)
29742 		return (EACCES);
29743 
29744 	ns = netstack_find_by_stackid(stackid);
29745 	if (ns == NULL)
29746 		return (-1);
29747 	ipst = ns->netstack_ip;
29748 	if (ipst == NULL) {
29749 		netstack_rele(ns);
29750 		return (-1);
29751 	}
29752 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29753 
29754 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29755 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29756 	ill = ILL_START_WALK_V4(&ctx, ipst);
29757 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29758 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29759 	rw_exit(&ipst->ips_ill_g_lock);
29760 
29761 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29762 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29763 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29764 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29765 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29766 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29767 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29768 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29769 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29770 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29771 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29772 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29773 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29774 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29775 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29776 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29777 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29778 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29779 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29780 
29781 	ipkp->routingDiscards.value.ui32 =	0;
29782 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29783 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29784 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29785 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29786 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29787 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29788 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29789 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29790 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29791 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29792 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29793 
29794 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29795 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29796 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29797 
29798 	netstack_rele(ns);
29799 
29800 	return (0);
29801 }
29802 
29803 static void *
29804 icmp_kstat_init(netstackid_t stackid)
29805 {
29806 	kstat_t	*ksp;
29807 
29808 	icmp_named_kstat_t template = {
29809 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29810 		{ "inErrors",		KSTAT_DATA_UINT32 },
29811 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29812 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29813 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29814 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29815 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29816 		{ "inEchos",		KSTAT_DATA_UINT32 },
29817 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29818 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29819 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29820 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29821 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29822 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29823 		{ "outErrors",		KSTAT_DATA_UINT32 },
29824 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29825 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29826 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29827 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29828 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29829 		{ "outEchos",		KSTAT_DATA_UINT32 },
29830 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29831 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29832 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29833 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29834 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29835 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29836 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29837 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29838 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29839 		{ "outDrops",		KSTAT_DATA_UINT32 },
29840 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29841 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29842 	};
29843 
29844 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29845 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
29846 	if (ksp == NULL || ksp->ks_data == NULL)
29847 		return (NULL);
29848 
29849 	bcopy(&template, ksp->ks_data, sizeof (template));
29850 
29851 	ksp->ks_update = icmp_kstat_update;
29852 	ksp->ks_private = (void *)(uintptr_t)stackid;
29853 
29854 	kstat_install(ksp);
29855 	return (ksp);
29856 }
29857 
29858 static void
29859 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29860 {
29861 	if (ksp != NULL) {
29862 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29863 		kstat_delete_netstack(ksp, stackid);
29864 	}
29865 }
29866 
29867 static int
29868 icmp_kstat_update(kstat_t *kp, int rw)
29869 {
29870 	icmp_named_kstat_t *icmpkp;
29871 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29872 	netstack_t	*ns;
29873 	ip_stack_t	*ipst;
29874 
29875 	if ((kp == NULL) || (kp->ks_data == NULL))
29876 		return (EIO);
29877 
29878 	if (rw == KSTAT_WRITE)
29879 		return (EACCES);
29880 
29881 	ns = netstack_find_by_stackid(stackid);
29882 	if (ns == NULL)
29883 		return (-1);
29884 	ipst = ns->netstack_ip;
29885 	if (ipst == NULL) {
29886 		netstack_rele(ns);
29887 		return (-1);
29888 	}
29889 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29890 
29891 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29892 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29893 	icmpkp->inDestUnreachs.value.ui32 =
29894 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29895 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29896 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29897 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29898 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29899 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29900 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29901 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29902 	icmpkp->inTimestampReps.value.ui32 =
29903 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29904 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29905 	icmpkp->inAddrMaskReps.value.ui32 =
29906 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29907 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29908 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29909 	icmpkp->outDestUnreachs.value.ui32 =
29910 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29911 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29912 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29913 	icmpkp->outSrcQuenchs.value.ui32 =
29914 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29915 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29916 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29917 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29918 	icmpkp->outTimestamps.value.ui32 =
29919 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29920 	icmpkp->outTimestampReps.value.ui32 =
29921 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29922 	icmpkp->outAddrMasks.value.ui32 =
29923 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29924 	icmpkp->outAddrMaskReps.value.ui32 =
29925 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29926 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29927 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29928 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29929 	icmpkp->outFragNeeded.value.ui32 =
29930 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29931 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29932 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29933 	icmpkp->inBadRedirects.value.ui32 =
29934 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29935 
29936 	netstack_rele(ns);
29937 	return (0);
29938 }
29939 
29940 /*
29941  * This is the fanout function for raw socket opened for SCTP.  Note
29942  * that it is called after SCTP checks that there is no socket which
29943  * wants a packet.  Then before SCTP handles this out of the blue packet,
29944  * this function is called to see if there is any raw socket for SCTP.
29945  * If there is and it is bound to the correct address, the packet will
29946  * be sent to that socket.  Note that only one raw socket can be bound to
29947  * a port.  This is assured in ipcl_sctp_hash_insert();
29948  */
29949 void
29950 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29951     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29952     zoneid_t zoneid)
29953 {
29954 	conn_t		*connp;
29955 	queue_t		*rq;
29956 	mblk_t		*first_mp;
29957 	boolean_t	secure;
29958 	ip6_t		*ip6h;
29959 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29960 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29961 
29962 	first_mp = mp;
29963 	if (mctl_present) {
29964 		mp = first_mp->b_cont;
29965 		secure = ipsec_in_is_secure(first_mp);
29966 		ASSERT(mp != NULL);
29967 	} else {
29968 		secure = B_FALSE;
29969 	}
29970 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29971 
29972 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29973 	if (connp == NULL) {
29974 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29975 		return;
29976 	}
29977 	rq = connp->conn_rq;
29978 	if (!canputnext(rq)) {
29979 		CONN_DEC_REF(connp);
29980 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29981 		freemsg(first_mp);
29982 		return;
29983 	}
29984 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29985 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29986 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29987 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29988 		if (first_mp == NULL) {
29989 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29990 			CONN_DEC_REF(connp);
29991 			return;
29992 		}
29993 	}
29994 	/*
29995 	 * We probably should not send M_CTL message up to
29996 	 * raw socket.
29997 	 */
29998 	if (mctl_present)
29999 		freeb(first_mp);
30000 
30001 	/* Initiate IPPF processing here if needed. */
30002 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
30003 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
30004 		ip_process(IPP_LOCAL_IN, &mp,
30005 		    recv_ill->ill_phyint->phyint_ifindex);
30006 		if (mp == NULL) {
30007 			CONN_DEC_REF(connp);
30008 			return;
30009 		}
30010 	}
30011 
30012 	if (connp->conn_recvif || connp->conn_recvslla ||
30013 	    ((connp->conn_ip_recvpktinfo ||
30014 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
30015 	    (flags & IP_FF_IPINFO))) {
30016 		int in_flags = 0;
30017 
30018 		/*
30019 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
30020 		 * IPF_RECVIF.
30021 		 */
30022 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
30023 			in_flags = IPF_RECVIF;
30024 		}
30025 		if (connp->conn_recvslla) {
30026 			in_flags |= IPF_RECVSLLA;
30027 		}
30028 		if (isv4) {
30029 			mp = ip_add_info(mp, recv_ill, in_flags,
30030 			    IPCL_ZONEID(connp), ipst);
30031 		} else {
30032 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
30033 			if (mp == NULL) {
30034 				BUMP_MIB(recv_ill->ill_ip_mib,
30035 				    ipIfStatsInDiscards);
30036 				CONN_DEC_REF(connp);
30037 				return;
30038 			}
30039 		}
30040 	}
30041 
30042 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
30043 	/*
30044 	 * We are sending the IPSEC_IN message also up. Refer
30045 	 * to comments above this function.
30046 	 */
30047 	putnext(rq, mp);
30048 	CONN_DEC_REF(connp);
30049 }
30050 
30051 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
30052 {									\
30053 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
30054 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
30055 }
30056 /*
30057  * This function should be called only if all packet processing
30058  * including fragmentation is complete. Callers of this function
30059  * must set mp->b_prev to one of these values:
30060  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
30061  * prior to handing over the mp as first argument to this function.
30062  *
30063  * If the ire passed by caller is incomplete, this function
30064  * queues the packet and if necessary, sends ARP request and bails.
30065  * If the ire passed is fully resolved, we simply prepend
30066  * the link-layer header to the packet, do ipsec hw acceleration
30067  * work if necessary, and send the packet out on the wire.
30068  *
30069  * NOTE: IPSEC will only call this function with fully resolved
30070  * ires if hw acceleration is involved.
30071  * TODO list :
30072  * 	a Handle M_MULTIDATA so that
30073  *	  tcp_multisend->tcp_multisend_data can
30074  *	  call ip_xmit_v4 directly
30075  *	b Handle post-ARP work for fragments so that
30076  *	  ip_wput_frag can call this function.
30077  */
30078 ipxmit_state_t
30079 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io, boolean_t flow_ctl_enabled)
30080 {
30081 	nce_t		*arpce;
30082 	queue_t		*q;
30083 	int		ill_index;
30084 	mblk_t		*nxt_mp, *first_mp;
30085 	boolean_t	xmit_drop = B_FALSE;
30086 	ip_proc_t	proc;
30087 	ill_t		*out_ill;
30088 	int		pkt_len;
30089 
30090 	arpce = ire->ire_nce;
30091 	ASSERT(arpce != NULL);
30092 
30093 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
30094 
30095 	mutex_enter(&arpce->nce_lock);
30096 	switch (arpce->nce_state) {
30097 	case ND_REACHABLE:
30098 		/* If there are other queued packets, queue this packet */
30099 		if (arpce->nce_qd_mp != NULL) {
30100 			if (mp != NULL)
30101 				nce_queue_mp_common(arpce, mp, B_FALSE);
30102 			mp = arpce->nce_qd_mp;
30103 		}
30104 		arpce->nce_qd_mp = NULL;
30105 		mutex_exit(&arpce->nce_lock);
30106 
30107 		/*
30108 		 * Flush the queue.  In the common case, where the
30109 		 * ARP is already resolved,  it will go through the
30110 		 * while loop only once.
30111 		 */
30112 		while (mp != NULL) {
30113 
30114 			nxt_mp = mp->b_next;
30115 			mp->b_next = NULL;
30116 			ASSERT(mp->b_datap->db_type != M_CTL);
30117 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
30118 			/*
30119 			 * This info is needed for IPQOS to do COS marking
30120 			 * in ip_wput_attach_llhdr->ip_process.
30121 			 */
30122 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
30123 			mp->b_prev = NULL;
30124 
30125 			/* set up ill index for outbound qos processing */
30126 			out_ill = ire->ire_ipif->ipif_ill;
30127 			ill_index = out_ill->ill_phyint->phyint_ifindex;
30128 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
30129 			    ill_index);
30130 			if (first_mp == NULL) {
30131 				xmit_drop = B_TRUE;
30132 				BUMP_MIB(out_ill->ill_ip_mib,
30133 				    ipIfStatsOutDiscards);
30134 				goto next_mp;
30135 			}
30136 			/* non-ipsec hw accel case */
30137 			if (io == NULL || !io->ipsec_out_accelerated) {
30138 				/* send it */
30139 				q = ire->ire_stq;
30140 				if (proc == IPP_FWD_OUT) {
30141 					UPDATE_IB_PKT_COUNT(ire);
30142 				} else {
30143 					UPDATE_OB_PKT_COUNT(ire);
30144 				}
30145 				ire->ire_last_used_time = lbolt;
30146 
30147 				if (flow_ctl_enabled || canputnext(q)) {
30148 					if (proc == IPP_FWD_OUT) {
30149 
30150 					BUMP_MIB(out_ill->ill_ip_mib,
30151 					    ipIfStatsHCOutForwDatagrams);
30152 
30153 					}
30154 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
30155 					    pkt_len);
30156 
30157 					putnext(q, first_mp);
30158 				} else {
30159 					BUMP_MIB(out_ill->ill_ip_mib,
30160 					    ipIfStatsOutDiscards);
30161 					xmit_drop = B_TRUE;
30162 					freemsg(first_mp);
30163 				}
30164 			} else {
30165 				/*
30166 				 * Safety Pup says: make sure this
30167 				 *  is going to the right interface!
30168 				 */
30169 				ill_t *ill1 =
30170 				    (ill_t *)ire->ire_stq->q_ptr;
30171 				int ifindex =
30172 				    ill1->ill_phyint->phyint_ifindex;
30173 				if (ifindex !=
30174 				    io->ipsec_out_capab_ill_index) {
30175 					xmit_drop = B_TRUE;
30176 					freemsg(mp);
30177 				} else {
30178 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
30179 					    pkt_len);
30180 					ipsec_hw_putnext(ire->ire_stq, mp);
30181 				}
30182 			}
30183 next_mp:
30184 			mp = nxt_mp;
30185 		} /* while (mp != NULL) */
30186 		if (xmit_drop)
30187 			return (SEND_FAILED);
30188 		else
30189 			return (SEND_PASSED);
30190 
30191 	case ND_INITIAL:
30192 	case ND_INCOMPLETE:
30193 
30194 		/*
30195 		 * While we do send off packets to dests that
30196 		 * use fully-resolved CGTP routes, we do not
30197 		 * handle unresolved CGTP routes.
30198 		 */
30199 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
30200 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
30201 
30202 		if (mp != NULL) {
30203 			/* queue the packet */
30204 			nce_queue_mp_common(arpce, mp, B_FALSE);
30205 		}
30206 
30207 		if (arpce->nce_state == ND_INCOMPLETE) {
30208 			mutex_exit(&arpce->nce_lock);
30209 			DTRACE_PROBE3(ip__xmit__incomplete,
30210 			    (ire_t *), ire, (mblk_t *), mp,
30211 			    (ipsec_out_t *), io);
30212 			return (LOOKUP_IN_PROGRESS);
30213 		}
30214 
30215 		arpce->nce_state = ND_INCOMPLETE;
30216 		mutex_exit(&arpce->nce_lock);
30217 		/*
30218 		 * Note that ire_add() (called from ire_forward())
30219 		 * holds a ref on the ire until ARP is completed.
30220 		 */
30221 
30222 		ire_arpresolve(ire, ire_to_ill(ire));
30223 		return (LOOKUP_IN_PROGRESS);
30224 	default:
30225 		ASSERT(0);
30226 		mutex_exit(&arpce->nce_lock);
30227 		return (LLHDR_RESLV_FAILED);
30228 	}
30229 }
30230 
30231 #undef	UPDATE_IP_MIB_OB_COUNTERS
30232 
30233 /*
30234  * Return B_TRUE if the buffers differ in length or content.
30235  * This is used for comparing extension header buffers.
30236  * Note that an extension header would be declared different
30237  * even if all that changed was the next header value in that header i.e.
30238  * what really changed is the next extension header.
30239  */
30240 boolean_t
30241 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
30242     uint_t blen)
30243 {
30244 	if (!b_valid)
30245 		blen = 0;
30246 
30247 	if (alen != blen)
30248 		return (B_TRUE);
30249 	if (alen == 0)
30250 		return (B_FALSE);	/* Both zero length */
30251 	return (bcmp(abuf, bbuf, alen));
30252 }
30253 
30254 /*
30255  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
30256  * Return B_FALSE if memory allocation fails - don't change any state!
30257  */
30258 boolean_t
30259 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
30260     const void *src, uint_t srclen)
30261 {
30262 	void *dst;
30263 
30264 	if (!src_valid)
30265 		srclen = 0;
30266 
30267 	ASSERT(*dstlenp == 0);
30268 	if (src != NULL && srclen != 0) {
30269 		dst = mi_alloc(srclen, BPRI_MED);
30270 		if (dst == NULL)
30271 			return (B_FALSE);
30272 	} else {
30273 		dst = NULL;
30274 	}
30275 	if (*dstp != NULL)
30276 		mi_free(*dstp);
30277 	*dstp = dst;
30278 	*dstlenp = dst == NULL ? 0 : srclen;
30279 	return (B_TRUE);
30280 }
30281 
30282 /*
30283  * Replace what is in *dst, *dstlen with the source.
30284  * Assumes ip_allocbuf has already been called.
30285  */
30286 void
30287 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
30288     const void *src, uint_t srclen)
30289 {
30290 	if (!src_valid)
30291 		srclen = 0;
30292 
30293 	ASSERT(*dstlenp == srclen);
30294 	if (src != NULL && srclen != 0)
30295 		bcopy(src, *dstp, srclen);
30296 }
30297 
30298 /*
30299  * Free the storage pointed to by the members of an ip6_pkt_t.
30300  */
30301 void
30302 ip6_pkt_free(ip6_pkt_t *ipp)
30303 {
30304 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
30305 
30306 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
30307 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
30308 		ipp->ipp_hopopts = NULL;
30309 		ipp->ipp_hopoptslen = 0;
30310 	}
30311 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
30312 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
30313 		ipp->ipp_rtdstopts = NULL;
30314 		ipp->ipp_rtdstoptslen = 0;
30315 	}
30316 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
30317 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
30318 		ipp->ipp_dstopts = NULL;
30319 		ipp->ipp_dstoptslen = 0;
30320 	}
30321 	if (ipp->ipp_fields & IPPF_RTHDR) {
30322 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
30323 		ipp->ipp_rthdr = NULL;
30324 		ipp->ipp_rthdrlen = 0;
30325 	}
30326 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
30327 	    IPPF_RTHDR);
30328 }
30329