xref: /illumos-gate/usr/src/uts/common/inet/ip/ip.c (revision c2aa8c918a0c67f7fd93724a31efac84968fc12c)
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 	if (mp2ctl == NULL)
18487 		return (NULL);
18488 
18489 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18490 }
18491 
18492 /* Global IPv4 ICMP statistics */
18493 static mblk_t *
18494 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18495 {
18496 	struct opthdr		*optp;
18497 	mblk_t			*mp2ctl;
18498 
18499 	/*
18500 	 * Make a copy of the original message
18501 	 */
18502 	mp2ctl = copymsg(mpctl);
18503 
18504 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18505 	optp->level = MIB2_ICMP;
18506 	optp->name = 0;
18507 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18508 	    (int)sizeof (ipst->ips_icmp_mib))) {
18509 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18510 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18511 	}
18512 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18513 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18514 	    (int)optp->level, (int)optp->name, (int)optp->len));
18515 	qreply(q, mpctl);
18516 	return (mp2ctl);
18517 }
18518 
18519 /* Global IPv4 IGMP statistics */
18520 static mblk_t *
18521 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18522 {
18523 	struct opthdr		*optp;
18524 	mblk_t			*mp2ctl;
18525 
18526 	/*
18527 	 * make a copy of the original message
18528 	 */
18529 	mp2ctl = copymsg(mpctl);
18530 
18531 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18532 	optp->level = EXPER_IGMP;
18533 	optp->name = 0;
18534 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18535 	    (int)sizeof (ipst->ips_igmpstat))) {
18536 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18537 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18538 	}
18539 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18540 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18541 	    (int)optp->level, (int)optp->name, (int)optp->len));
18542 	qreply(q, mpctl);
18543 	return (mp2ctl);
18544 }
18545 
18546 /* Global IPv4 Multicast Routing statistics */
18547 static mblk_t *
18548 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18549 {
18550 	struct opthdr		*optp;
18551 	mblk_t			*mp2ctl;
18552 
18553 	/*
18554 	 * make a copy of the original message
18555 	 */
18556 	mp2ctl = copymsg(mpctl);
18557 
18558 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18559 	optp->level = EXPER_DVMRP;
18560 	optp->name = 0;
18561 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18562 		ip0dbg(("ip_mroute_stats: failed\n"));
18563 	}
18564 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18565 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18566 	    (int)optp->level, (int)optp->name, (int)optp->len));
18567 	qreply(q, mpctl);
18568 	return (mp2ctl);
18569 }
18570 
18571 /* IPv4 address information */
18572 static mblk_t *
18573 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18574 {
18575 	struct opthdr		*optp;
18576 	mblk_t			*mp2ctl;
18577 	mblk_t			*mp_tail = NULL;
18578 	ill_t			*ill;
18579 	ipif_t			*ipif;
18580 	uint_t			bitval;
18581 	mib2_ipAddrEntry_t	mae;
18582 	zoneid_t		zoneid;
18583 	ill_walk_context_t ctx;
18584 
18585 	/*
18586 	 * make a copy of the original message
18587 	 */
18588 	mp2ctl = copymsg(mpctl);
18589 
18590 	/* ipAddrEntryTable */
18591 
18592 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18593 	optp->level = MIB2_IP;
18594 	optp->name = MIB2_IP_ADDR;
18595 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18596 
18597 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18598 	ill = ILL_START_WALK_V4(&ctx, ipst);
18599 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18600 		for (ipif = ill->ill_ipif; ipif != NULL;
18601 		    ipif = ipif->ipif_next) {
18602 			if (ipif->ipif_zoneid != zoneid &&
18603 			    ipif->ipif_zoneid != ALL_ZONES)
18604 				continue;
18605 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18606 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18607 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18608 
18609 			(void) ipif_get_name(ipif,
18610 			    mae.ipAdEntIfIndex.o_bytes,
18611 			    OCTET_LENGTH);
18612 			mae.ipAdEntIfIndex.o_length =
18613 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18614 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18615 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18616 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18617 			mae.ipAdEntInfo.ae_subnet_len =
18618 			    ip_mask_to_plen(ipif->ipif_net_mask);
18619 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18620 			for (bitval = 1;
18621 			    bitval &&
18622 			    !(bitval & ipif->ipif_brd_addr);
18623 			    bitval <<= 1)
18624 				noop;
18625 			mae.ipAdEntBcastAddr = bitval;
18626 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18627 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18628 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18629 			mae.ipAdEntInfo.ae_broadcast_addr =
18630 			    ipif->ipif_brd_addr;
18631 			mae.ipAdEntInfo.ae_pp_dst_addr =
18632 			    ipif->ipif_pp_dst_addr;
18633 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18634 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18635 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18636 
18637 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18638 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18639 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18640 				    "allocate %u bytes\n",
18641 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18642 			}
18643 		}
18644 	}
18645 	rw_exit(&ipst->ips_ill_g_lock);
18646 
18647 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18648 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18649 	    (int)optp->level, (int)optp->name, (int)optp->len));
18650 	qreply(q, mpctl);
18651 	return (mp2ctl);
18652 }
18653 
18654 /* IPv6 address information */
18655 static mblk_t *
18656 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18657 {
18658 	struct opthdr		*optp;
18659 	mblk_t			*mp2ctl;
18660 	mblk_t			*mp_tail = NULL;
18661 	ill_t			*ill;
18662 	ipif_t			*ipif;
18663 	mib2_ipv6AddrEntry_t	mae6;
18664 	zoneid_t		zoneid;
18665 	ill_walk_context_t	ctx;
18666 
18667 	/*
18668 	 * make a copy of the original message
18669 	 */
18670 	mp2ctl = copymsg(mpctl);
18671 
18672 	/* ipv6AddrEntryTable */
18673 
18674 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18675 	optp->level = MIB2_IP6;
18676 	optp->name = MIB2_IP6_ADDR;
18677 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18678 
18679 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18680 	ill = ILL_START_WALK_V6(&ctx, ipst);
18681 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18682 		for (ipif = ill->ill_ipif; ipif != NULL;
18683 		    ipif = ipif->ipif_next) {
18684 			if (ipif->ipif_zoneid != zoneid &&
18685 			    ipif->ipif_zoneid != ALL_ZONES)
18686 				continue;
18687 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18688 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18689 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18690 
18691 			(void) ipif_get_name(ipif,
18692 			    mae6.ipv6AddrIfIndex.o_bytes,
18693 			    OCTET_LENGTH);
18694 			mae6.ipv6AddrIfIndex.o_length =
18695 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18696 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18697 			mae6.ipv6AddrPfxLength =
18698 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18699 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18700 			mae6.ipv6AddrInfo.ae_subnet_len =
18701 			    mae6.ipv6AddrPfxLength;
18702 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18703 
18704 			/* Type: stateless(1), stateful(2), unknown(3) */
18705 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18706 				mae6.ipv6AddrType = 1;
18707 			else
18708 				mae6.ipv6AddrType = 2;
18709 			/* Anycast: true(1), false(2) */
18710 			if (ipif->ipif_flags & IPIF_ANYCAST)
18711 				mae6.ipv6AddrAnycastFlag = 1;
18712 			else
18713 				mae6.ipv6AddrAnycastFlag = 2;
18714 
18715 			/*
18716 			 * Address status: preferred(1), deprecated(2),
18717 			 * invalid(3), inaccessible(4), unknown(5)
18718 			 */
18719 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18720 				mae6.ipv6AddrStatus = 3;
18721 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18722 				mae6.ipv6AddrStatus = 2;
18723 			else
18724 				mae6.ipv6AddrStatus = 1;
18725 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18726 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18727 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18728 			    ipif->ipif_v6pp_dst_addr;
18729 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18730 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18731 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18732 			mae6.ipv6AddrIdentifier = ill->ill_token;
18733 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18734 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18735 			mae6.ipv6AddrRetransmitTime =
18736 			    ill->ill_reachable_retrans_time;
18737 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18738 			    (char *)&mae6,
18739 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
18740 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18741 				    "allocate %u bytes\n",
18742 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18743 			}
18744 		}
18745 	}
18746 	rw_exit(&ipst->ips_ill_g_lock);
18747 
18748 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18749 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18750 	    (int)optp->level, (int)optp->name, (int)optp->len));
18751 	qreply(q, mpctl);
18752 	return (mp2ctl);
18753 }
18754 
18755 /* IPv4 multicast group membership. */
18756 static mblk_t *
18757 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18758 {
18759 	struct opthdr		*optp;
18760 	mblk_t			*mp2ctl;
18761 	ill_t			*ill;
18762 	ipif_t			*ipif;
18763 	ilm_t			*ilm;
18764 	ip_member_t		ipm;
18765 	mblk_t			*mp_tail = NULL;
18766 	ill_walk_context_t	ctx;
18767 	zoneid_t		zoneid;
18768 
18769 	/*
18770 	 * make a copy of the original message
18771 	 */
18772 	mp2ctl = copymsg(mpctl);
18773 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18774 
18775 	/* ipGroupMember table */
18776 	optp = (struct opthdr *)&mpctl->b_rptr[
18777 	    sizeof (struct T_optmgmt_ack)];
18778 	optp->level = MIB2_IP;
18779 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18780 
18781 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18782 	ill = ILL_START_WALK_V4(&ctx, ipst);
18783 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18784 		ILM_WALKER_HOLD(ill);
18785 		for (ipif = ill->ill_ipif; ipif != NULL;
18786 		    ipif = ipif->ipif_next) {
18787 			if (ipif->ipif_zoneid != zoneid &&
18788 			    ipif->ipif_zoneid != ALL_ZONES)
18789 				continue;	/* not this zone */
18790 			(void) ipif_get_name(ipif,
18791 			    ipm.ipGroupMemberIfIndex.o_bytes,
18792 			    OCTET_LENGTH);
18793 			ipm.ipGroupMemberIfIndex.o_length =
18794 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18795 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18796 				ASSERT(ilm->ilm_ipif != NULL);
18797 				ASSERT(ilm->ilm_ill == NULL);
18798 				if (ilm->ilm_ipif != ipif)
18799 					continue;
18800 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18801 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18802 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18803 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18804 				    (char *)&ipm, (int)sizeof (ipm))) {
18805 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18806 					    "failed to allocate %u bytes\n",
18807 					    (uint_t)sizeof (ipm)));
18808 				}
18809 			}
18810 		}
18811 		ILM_WALKER_RELE(ill);
18812 	}
18813 	rw_exit(&ipst->ips_ill_g_lock);
18814 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18815 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18816 	    (int)optp->level, (int)optp->name, (int)optp->len));
18817 	qreply(q, mpctl);
18818 	return (mp2ctl);
18819 }
18820 
18821 /* IPv6 multicast group membership. */
18822 static mblk_t *
18823 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18824 {
18825 	struct opthdr		*optp;
18826 	mblk_t			*mp2ctl;
18827 	ill_t			*ill;
18828 	ilm_t			*ilm;
18829 	ipv6_member_t		ipm6;
18830 	mblk_t			*mp_tail = NULL;
18831 	ill_walk_context_t	ctx;
18832 	zoneid_t		zoneid;
18833 
18834 	/*
18835 	 * make a copy of the original message
18836 	 */
18837 	mp2ctl = copymsg(mpctl);
18838 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18839 
18840 	/* ip6GroupMember table */
18841 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18842 	optp->level = MIB2_IP6;
18843 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18844 
18845 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18846 	ill = ILL_START_WALK_V6(&ctx, ipst);
18847 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18848 		ILM_WALKER_HOLD(ill);
18849 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18850 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18851 			ASSERT(ilm->ilm_ipif == NULL);
18852 			ASSERT(ilm->ilm_ill != NULL);
18853 			if (ilm->ilm_zoneid != zoneid)
18854 				continue;	/* not this zone */
18855 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18856 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18857 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18858 			if (!snmp_append_data2(mpctl->b_cont,
18859 			    &mp_tail,
18860 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18861 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18862 				    "failed to allocate %u bytes\n",
18863 				    (uint_t)sizeof (ipm6)));
18864 			}
18865 		}
18866 		ILM_WALKER_RELE(ill);
18867 	}
18868 	rw_exit(&ipst->ips_ill_g_lock);
18869 
18870 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18871 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18872 	    (int)optp->level, (int)optp->name, (int)optp->len));
18873 	qreply(q, mpctl);
18874 	return (mp2ctl);
18875 }
18876 
18877 /* IP multicast filtered sources */
18878 static mblk_t *
18879 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18880 {
18881 	struct opthdr		*optp;
18882 	mblk_t			*mp2ctl;
18883 	ill_t			*ill;
18884 	ipif_t			*ipif;
18885 	ilm_t			*ilm;
18886 	ip_grpsrc_t		ips;
18887 	mblk_t			*mp_tail = NULL;
18888 	ill_walk_context_t	ctx;
18889 	zoneid_t		zoneid;
18890 	int			i;
18891 	slist_t			*sl;
18892 
18893 	/*
18894 	 * make a copy of the original message
18895 	 */
18896 	mp2ctl = copymsg(mpctl);
18897 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18898 
18899 	/* ipGroupSource table */
18900 	optp = (struct opthdr *)&mpctl->b_rptr[
18901 	    sizeof (struct T_optmgmt_ack)];
18902 	optp->level = MIB2_IP;
18903 	optp->name = EXPER_IP_GROUP_SOURCES;
18904 
18905 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18906 	ill = ILL_START_WALK_V4(&ctx, ipst);
18907 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18908 		ILM_WALKER_HOLD(ill);
18909 		for (ipif = ill->ill_ipif; ipif != NULL;
18910 		    ipif = ipif->ipif_next) {
18911 			if (ipif->ipif_zoneid != zoneid)
18912 				continue;	/* not this zone */
18913 			(void) ipif_get_name(ipif,
18914 			    ips.ipGroupSourceIfIndex.o_bytes,
18915 			    OCTET_LENGTH);
18916 			ips.ipGroupSourceIfIndex.o_length =
18917 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18918 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18919 				ASSERT(ilm->ilm_ipif != NULL);
18920 				ASSERT(ilm->ilm_ill == NULL);
18921 				sl = ilm->ilm_filter;
18922 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18923 					continue;
18924 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18925 				for (i = 0; i < sl->sl_numsrc; i++) {
18926 					if (!IN6_IS_ADDR_V4MAPPED(
18927 					    &sl->sl_addr[i]))
18928 						continue;
18929 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18930 					    ips.ipGroupSourceAddress);
18931 					if (snmp_append_data2(mpctl->b_cont,
18932 					    &mp_tail, (char *)&ips,
18933 					    (int)sizeof (ips)) == 0) {
18934 						ip1dbg(("ip_snmp_get_mib2_"
18935 						    "ip_group_src: failed to "
18936 						    "allocate %u bytes\n",
18937 						    (uint_t)sizeof (ips)));
18938 					}
18939 				}
18940 			}
18941 		}
18942 		ILM_WALKER_RELE(ill);
18943 	}
18944 	rw_exit(&ipst->ips_ill_g_lock);
18945 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18946 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18947 	    (int)optp->level, (int)optp->name, (int)optp->len));
18948 	qreply(q, mpctl);
18949 	return (mp2ctl);
18950 }
18951 
18952 /* IPv6 multicast filtered sources. */
18953 static mblk_t *
18954 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18955 {
18956 	struct opthdr		*optp;
18957 	mblk_t			*mp2ctl;
18958 	ill_t			*ill;
18959 	ilm_t			*ilm;
18960 	ipv6_grpsrc_t		ips6;
18961 	mblk_t			*mp_tail = NULL;
18962 	ill_walk_context_t	ctx;
18963 	zoneid_t		zoneid;
18964 	int			i;
18965 	slist_t			*sl;
18966 
18967 	/*
18968 	 * make a copy of the original message
18969 	 */
18970 	mp2ctl = copymsg(mpctl);
18971 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18972 
18973 	/* ip6GroupMember table */
18974 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18975 	optp->level = MIB2_IP6;
18976 	optp->name = EXPER_IP6_GROUP_SOURCES;
18977 
18978 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18979 	ill = ILL_START_WALK_V6(&ctx, ipst);
18980 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18981 		ILM_WALKER_HOLD(ill);
18982 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18983 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18984 			ASSERT(ilm->ilm_ipif == NULL);
18985 			ASSERT(ilm->ilm_ill != NULL);
18986 			sl = ilm->ilm_filter;
18987 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
18988 				continue;
18989 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
18990 			for (i = 0; i < sl->sl_numsrc; i++) {
18991 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
18992 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18993 				    (char *)&ips6, (int)sizeof (ips6))) {
18994 					ip1dbg(("ip_snmp_get_mib2_ip6_"
18995 					    "group_src: failed to allocate "
18996 					    "%u bytes\n",
18997 					    (uint_t)sizeof (ips6)));
18998 				}
18999 			}
19000 		}
19001 		ILM_WALKER_RELE(ill);
19002 	}
19003 	rw_exit(&ipst->ips_ill_g_lock);
19004 
19005 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19006 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19007 	    (int)optp->level, (int)optp->name, (int)optp->len));
19008 	qreply(q, mpctl);
19009 	return (mp2ctl);
19010 }
19011 
19012 /* Multicast routing virtual interface table. */
19013 static mblk_t *
19014 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19015 {
19016 	struct opthdr		*optp;
19017 	mblk_t			*mp2ctl;
19018 
19019 	/*
19020 	 * make a copy of the original message
19021 	 */
19022 	mp2ctl = copymsg(mpctl);
19023 
19024 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19025 	optp->level = EXPER_DVMRP;
19026 	optp->name = EXPER_DVMRP_VIF;
19027 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
19028 		ip0dbg(("ip_mroute_vif: failed\n"));
19029 	}
19030 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19031 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
19032 	    (int)optp->level, (int)optp->name, (int)optp->len));
19033 	qreply(q, mpctl);
19034 	return (mp2ctl);
19035 }
19036 
19037 /* Multicast routing table. */
19038 static mblk_t *
19039 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19040 {
19041 	struct opthdr		*optp;
19042 	mblk_t			*mp2ctl;
19043 
19044 	/*
19045 	 * make a copy of the original message
19046 	 */
19047 	mp2ctl = copymsg(mpctl);
19048 
19049 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19050 	optp->level = EXPER_DVMRP;
19051 	optp->name = EXPER_DVMRP_MRT;
19052 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
19053 		ip0dbg(("ip_mroute_mrt: failed\n"));
19054 	}
19055 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19056 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
19057 	    (int)optp->level, (int)optp->name, (int)optp->len));
19058 	qreply(q, mpctl);
19059 	return (mp2ctl);
19060 }
19061 
19062 /*
19063  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
19064  * in one IRE walk.
19065  */
19066 static mblk_t *
19067 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19068 {
19069 	struct opthdr	*optp;
19070 	mblk_t		*mp2ctl;	/* Returned */
19071 	mblk_t		*mp3ctl;	/* nettomedia */
19072 	mblk_t		*mp4ctl;	/* routeattrs */
19073 	iproutedata_t	ird;
19074 	zoneid_t	zoneid;
19075 
19076 	/*
19077 	 * make copies of the original message
19078 	 *	- mp2ctl is returned unchanged to the caller for his use
19079 	 *	- mpctl is sent upstream as ipRouteEntryTable
19080 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
19081 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
19082 	 */
19083 	mp2ctl = copymsg(mpctl);
19084 	mp3ctl = copymsg(mpctl);
19085 	mp4ctl = copymsg(mpctl);
19086 	if (mp3ctl == NULL || mp4ctl == NULL) {
19087 		freemsg(mp4ctl);
19088 		freemsg(mp3ctl);
19089 		freemsg(mp2ctl);
19090 		freemsg(mpctl);
19091 		return (NULL);
19092 	}
19093 
19094 	bzero(&ird, sizeof (ird));
19095 
19096 	ird.ird_route.lp_head = mpctl->b_cont;
19097 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19098 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19099 
19100 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19101 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
19102 	if (zoneid == GLOBAL_ZONEID) {
19103 		/*
19104 		 * Those IREs are used by Mobile-IP; since mipagent(1M)
19105 		 * requires the sys_net_config or sys_ip_config privilege,
19106 		 * it can only run in the global zone or an exclusive-IP zone,
19107 		 * and both those have a conn_zoneid == GLOBAL_ZONEID.
19108 		 */
19109 		ire_walk_srcif_table_v4(ip_snmp_get2_v4, &ird, ipst);
19110 		ire_walk_ill_mrtun(0, 0, ip_snmp_get2_v4, &ird, NULL, ipst);
19111 	}
19112 
19113 	/* ipRouteEntryTable in mpctl */
19114 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19115 	optp->level = MIB2_IP;
19116 	optp->name = MIB2_IP_ROUTE;
19117 	optp->len = msgdsize(ird.ird_route.lp_head);
19118 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19119 	    (int)optp->level, (int)optp->name, (int)optp->len));
19120 	qreply(q, mpctl);
19121 
19122 	/* ipNetToMediaEntryTable in mp3ctl */
19123 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19124 	optp->level = MIB2_IP;
19125 	optp->name = MIB2_IP_MEDIA;
19126 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19127 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19128 	    (int)optp->level, (int)optp->name, (int)optp->len));
19129 	qreply(q, mp3ctl);
19130 
19131 	/* ipRouteAttributeTable in mp4ctl */
19132 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19133 	optp->level = MIB2_IP;
19134 	optp->name = EXPER_IP_RTATTR;
19135 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19136 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19137 	    (int)optp->level, (int)optp->name, (int)optp->len));
19138 	if (optp->len == 0)
19139 		freemsg(mp4ctl);
19140 	else
19141 		qreply(q, mp4ctl);
19142 
19143 	return (mp2ctl);
19144 }
19145 
19146 /*
19147  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
19148  * ipv6NetToMediaEntryTable in an NDP walk.
19149  */
19150 static mblk_t *
19151 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19152 {
19153 	struct opthdr	*optp;
19154 	mblk_t		*mp2ctl;	/* Returned */
19155 	mblk_t		*mp3ctl;	/* nettomedia */
19156 	mblk_t		*mp4ctl;	/* routeattrs */
19157 	iproutedata_t	ird;
19158 	zoneid_t	zoneid;
19159 
19160 	/*
19161 	 * make copies of the original message
19162 	 *	- mp2ctl is returned unchanged to the caller for his use
19163 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
19164 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
19165 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
19166 	 */
19167 	mp2ctl = copymsg(mpctl);
19168 	mp3ctl = copymsg(mpctl);
19169 	mp4ctl = copymsg(mpctl);
19170 	if (mp3ctl == NULL || mp4ctl == NULL) {
19171 		freemsg(mp4ctl);
19172 		freemsg(mp3ctl);
19173 		freemsg(mp2ctl);
19174 		freemsg(mpctl);
19175 		return (NULL);
19176 	}
19177 
19178 	bzero(&ird, sizeof (ird));
19179 
19180 	ird.ird_route.lp_head = mpctl->b_cont;
19181 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19182 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19183 
19184 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19185 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
19186 
19187 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19188 	optp->level = MIB2_IP6;
19189 	optp->name = MIB2_IP6_ROUTE;
19190 	optp->len = msgdsize(ird.ird_route.lp_head);
19191 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19192 	    (int)optp->level, (int)optp->name, (int)optp->len));
19193 	qreply(q, mpctl);
19194 
19195 	/* ipv6NetToMediaEntryTable in mp3ctl */
19196 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
19197 
19198 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19199 	optp->level = MIB2_IP6;
19200 	optp->name = MIB2_IP6_MEDIA;
19201 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19202 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19203 	    (int)optp->level, (int)optp->name, (int)optp->len));
19204 	qreply(q, mp3ctl);
19205 
19206 	/* ipv6RouteAttributeTable in mp4ctl */
19207 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19208 	optp->level = MIB2_IP6;
19209 	optp->name = EXPER_IP_RTATTR;
19210 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19211 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19212 	    (int)optp->level, (int)optp->name, (int)optp->len));
19213 	if (optp->len == 0)
19214 		freemsg(mp4ctl);
19215 	else
19216 		qreply(q, mp4ctl);
19217 
19218 	return (mp2ctl);
19219 }
19220 
19221 /*
19222  * IPv6 mib: One per ill
19223  */
19224 static mblk_t *
19225 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19226 {
19227 	struct opthdr		*optp;
19228 	mblk_t			*mp2ctl;
19229 	ill_t			*ill;
19230 	ill_walk_context_t	ctx;
19231 	mblk_t			*mp_tail = NULL;
19232 
19233 	/*
19234 	 * Make a copy of the original message
19235 	 */
19236 	mp2ctl = copymsg(mpctl);
19237 
19238 	/* fixed length IPv6 structure ... */
19239 
19240 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19241 	optp->level = MIB2_IP6;
19242 	optp->name = 0;
19243 	/* Include "unknown interface" ip6_mib */
19244 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
19245 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
19246 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
19247 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
19248 	    ipst->ips_ipv6_forward ? 1 : 2);
19249 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
19250 	    ipst->ips_ipv6_def_hops);
19251 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
19252 	    sizeof (mib2_ipIfStatsEntry_t));
19253 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
19254 	    sizeof (mib2_ipv6AddrEntry_t));
19255 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
19256 	    sizeof (mib2_ipv6RouteEntry_t));
19257 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
19258 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19259 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
19260 	    sizeof (ipv6_member_t));
19261 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
19262 	    sizeof (ipv6_grpsrc_t));
19263 
19264 	/*
19265 	 * Synchronize 64- and 32-bit counters
19266 	 */
19267 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
19268 	    ipIfStatsHCInReceives);
19269 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
19270 	    ipIfStatsHCInDelivers);
19271 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
19272 	    ipIfStatsHCOutRequests);
19273 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
19274 	    ipIfStatsHCOutForwDatagrams);
19275 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
19276 	    ipIfStatsHCOutMcastPkts);
19277 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19278 	    ipIfStatsHCInMcastPkts);
19279 
19280 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19281 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19282 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19283 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19284 	}
19285 
19286 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19287 	ill = ILL_START_WALK_V6(&ctx, ipst);
19288 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19289 		ill->ill_ip_mib->ipIfStatsIfIndex =
19290 		    ill->ill_phyint->phyint_ifindex;
19291 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19292 		    ipst->ips_ipv6_forward ? 1 : 2);
19293 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19294 		    ill->ill_max_hops);
19295 
19296 		/*
19297 		 * Synchronize 64- and 32-bit counters
19298 		 */
19299 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19300 		    ipIfStatsHCInReceives);
19301 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19302 		    ipIfStatsHCInDelivers);
19303 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19304 		    ipIfStatsHCOutRequests);
19305 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19306 		    ipIfStatsHCOutForwDatagrams);
19307 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19308 		    ipIfStatsHCOutMcastPkts);
19309 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19310 		    ipIfStatsHCInMcastPkts);
19311 
19312 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19313 		    (char *)ill->ill_ip_mib,
19314 		    (int)sizeof (*ill->ill_ip_mib))) {
19315 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19316 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
19317 		}
19318 	}
19319 	rw_exit(&ipst->ips_ill_g_lock);
19320 
19321 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19322 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19323 	    (int)optp->level, (int)optp->name, (int)optp->len));
19324 	qreply(q, mpctl);
19325 	return (mp2ctl);
19326 }
19327 
19328 /*
19329  * ICMPv6 mib: One per ill
19330  */
19331 static mblk_t *
19332 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19333 {
19334 	struct opthdr		*optp;
19335 	mblk_t			*mp2ctl;
19336 	ill_t			*ill;
19337 	ill_walk_context_t	ctx;
19338 	mblk_t			*mp_tail = NULL;
19339 	/*
19340 	 * Make a copy of the original message
19341 	 */
19342 	mp2ctl = copymsg(mpctl);
19343 
19344 	/* fixed length ICMPv6 structure ... */
19345 
19346 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19347 	optp->level = MIB2_ICMP6;
19348 	optp->name = 0;
19349 	/* Include "unknown interface" icmp6_mib */
19350 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19351 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19352 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19353 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19354 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19355 	    (char *)&ipst->ips_icmp6_mib,
19356 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19357 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19358 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19359 	}
19360 
19361 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19362 	ill = ILL_START_WALK_V6(&ctx, ipst);
19363 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19364 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19365 		    ill->ill_phyint->phyint_ifindex;
19366 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19367 		    (char *)ill->ill_icmp6_mib,
19368 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19369 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19370 			    "%u bytes\n",
19371 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19372 		}
19373 	}
19374 	rw_exit(&ipst->ips_ill_g_lock);
19375 
19376 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19377 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19378 	    (int)optp->level, (int)optp->name, (int)optp->len));
19379 	qreply(q, mpctl);
19380 	return (mp2ctl);
19381 }
19382 
19383 /*
19384  * ire_walk routine to create both ipRouteEntryTable and
19385  * ipRouteAttributeTable in one IRE walk
19386  */
19387 static void
19388 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19389 {
19390 	ill_t				*ill;
19391 	ipif_t				*ipif;
19392 	mib2_ipRouteEntry_t		*re;
19393 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19394 	ipaddr_t			gw_addr;
19395 	tsol_ire_gw_secattr_t		*attrp;
19396 	tsol_gc_t			*gc = NULL;
19397 	tsol_gcgrp_t			*gcgrp = NULL;
19398 	uint_t				sacnt = 0;
19399 	int				i;
19400 
19401 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19402 
19403 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19404 		return;
19405 
19406 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19407 		mutex_enter(&attrp->igsa_lock);
19408 		if ((gc = attrp->igsa_gc) != NULL) {
19409 			gcgrp = gc->gc_grp;
19410 			ASSERT(gcgrp != NULL);
19411 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19412 			sacnt = 1;
19413 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19414 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19415 			gc = gcgrp->gcgrp_head;
19416 			sacnt = gcgrp->gcgrp_count;
19417 		}
19418 		mutex_exit(&attrp->igsa_lock);
19419 
19420 		/* do nothing if there's no gc to report */
19421 		if (gc == NULL) {
19422 			ASSERT(sacnt == 0);
19423 			if (gcgrp != NULL) {
19424 				/* we might as well drop the lock now */
19425 				rw_exit(&gcgrp->gcgrp_rwlock);
19426 				gcgrp = NULL;
19427 			}
19428 			attrp = NULL;
19429 		}
19430 
19431 		ASSERT(gc == NULL || (gcgrp != NULL &&
19432 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19433 	}
19434 	ASSERT(sacnt == 0 || gc != NULL);
19435 
19436 	if (sacnt != 0 &&
19437 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19438 		kmem_free(re, sizeof (*re));
19439 		rw_exit(&gcgrp->gcgrp_rwlock);
19440 		return;
19441 	}
19442 
19443 	/*
19444 	 * Return all IRE types for route table... let caller pick and choose
19445 	 */
19446 	re->ipRouteDest = ire->ire_addr;
19447 	ipif = ire->ire_ipif;
19448 	re->ipRouteIfIndex.o_length = 0;
19449 	if (ire->ire_type == IRE_CACHE) {
19450 		ill = (ill_t *)ire->ire_stq->q_ptr;
19451 		re->ipRouteIfIndex.o_length =
19452 		    ill->ill_name_length == 0 ? 0 :
19453 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19454 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19455 		    re->ipRouteIfIndex.o_length);
19456 	} else if (ipif != NULL) {
19457 		(void) ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes,
19458 		    OCTET_LENGTH);
19459 		re->ipRouteIfIndex.o_length =
19460 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19461 	}
19462 	re->ipRouteMetric1 = -1;
19463 	re->ipRouteMetric2 = -1;
19464 	re->ipRouteMetric3 = -1;
19465 	re->ipRouteMetric4 = -1;
19466 
19467 	gw_addr = ire->ire_gateway_addr;
19468 
19469 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19470 		re->ipRouteNextHop = ire->ire_src_addr;
19471 	else
19472 		re->ipRouteNextHop = gw_addr;
19473 	/* indirect(4), direct(3), or invalid(2) */
19474 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19475 		re->ipRouteType = 2;
19476 	else
19477 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19478 	re->ipRouteProto = -1;
19479 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19480 	re->ipRouteMask = ire->ire_mask;
19481 	re->ipRouteMetric5 = -1;
19482 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19483 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19484 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19485 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19486 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19487 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19488 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19489 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19490 	re->ipRouteInfo.re_in_ill.o_length = 0;
19491 
19492 	if (ire->ire_flags & RTF_DYNAMIC) {
19493 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19494 	} else {
19495 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19496 	}
19497 
19498 	if (ire->ire_in_ill != NULL) {
19499 		re->ipRouteInfo.re_in_ill.o_length =
19500 		    ire->ire_in_ill->ill_name_length == 0 ? 0 :
19501 		    MIN(OCTET_LENGTH, ire->ire_in_ill->ill_name_length - 1);
19502 		bcopy(ire->ire_in_ill->ill_name,
19503 		    re->ipRouteInfo.re_in_ill.o_bytes,
19504 		    re->ipRouteInfo.re_in_ill.o_length);
19505 	}
19506 	re->ipRouteInfo.re_in_src_addr = ire->ire_in_src_addr;
19507 
19508 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19509 	    (char *)re, (int)sizeof (*re))) {
19510 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19511 		    (uint_t)sizeof (*re)));
19512 	}
19513 
19514 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19515 		iaeptr->iae_routeidx = ird->ird_idx;
19516 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19517 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19518 	}
19519 
19520 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19521 	    (char *)iae, sacnt * sizeof (*iae))) {
19522 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19523 		    (unsigned)(sacnt * sizeof (*iae))));
19524 	}
19525 
19526 	/* bump route index for next pass */
19527 	ird->ird_idx++;
19528 
19529 	kmem_free(re, sizeof (*re));
19530 	if (sacnt != 0)
19531 		kmem_free(iae, sacnt * sizeof (*iae));
19532 
19533 	if (gcgrp != NULL)
19534 		rw_exit(&gcgrp->gcgrp_rwlock);
19535 }
19536 
19537 /*
19538  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19539  */
19540 static void
19541 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19542 {
19543 	ill_t				*ill;
19544 	ipif_t				*ipif;
19545 	mib2_ipv6RouteEntry_t		*re;
19546 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19547 	in6_addr_t			gw_addr_v6;
19548 	tsol_ire_gw_secattr_t		*attrp;
19549 	tsol_gc_t			*gc = NULL;
19550 	tsol_gcgrp_t			*gcgrp = NULL;
19551 	uint_t				sacnt = 0;
19552 	int				i;
19553 
19554 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19555 
19556 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19557 		return;
19558 
19559 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19560 		mutex_enter(&attrp->igsa_lock);
19561 		if ((gc = attrp->igsa_gc) != NULL) {
19562 			gcgrp = gc->gc_grp;
19563 			ASSERT(gcgrp != NULL);
19564 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19565 			sacnt = 1;
19566 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19567 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19568 			gc = gcgrp->gcgrp_head;
19569 			sacnt = gcgrp->gcgrp_count;
19570 		}
19571 		mutex_exit(&attrp->igsa_lock);
19572 
19573 		/* do nothing if there's no gc to report */
19574 		if (gc == NULL) {
19575 			ASSERT(sacnt == 0);
19576 			if (gcgrp != NULL) {
19577 				/* we might as well drop the lock now */
19578 				rw_exit(&gcgrp->gcgrp_rwlock);
19579 				gcgrp = NULL;
19580 			}
19581 			attrp = NULL;
19582 		}
19583 
19584 		ASSERT(gc == NULL || (gcgrp != NULL &&
19585 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19586 	}
19587 	ASSERT(sacnt == 0 || gc != NULL);
19588 
19589 	if (sacnt != 0 &&
19590 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19591 		kmem_free(re, sizeof (*re));
19592 		rw_exit(&gcgrp->gcgrp_rwlock);
19593 		return;
19594 	}
19595 
19596 	/*
19597 	 * Return all IRE types for route table... let caller pick and choose
19598 	 */
19599 	re->ipv6RouteDest = ire->ire_addr_v6;
19600 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19601 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19602 	re->ipv6RouteIfIndex.o_length = 0;
19603 	ipif = ire->ire_ipif;
19604 	if (ire->ire_type == IRE_CACHE) {
19605 		ill = (ill_t *)ire->ire_stq->q_ptr;
19606 		re->ipv6RouteIfIndex.o_length =
19607 		    ill->ill_name_length == 0 ? 0 :
19608 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19609 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19610 		    re->ipv6RouteIfIndex.o_length);
19611 	} else if (ipif != NULL) {
19612 		(void) ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes,
19613 		    OCTET_LENGTH);
19614 		re->ipv6RouteIfIndex.o_length =
19615 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19616 	}
19617 
19618 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19619 
19620 	mutex_enter(&ire->ire_lock);
19621 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19622 	mutex_exit(&ire->ire_lock);
19623 
19624 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19625 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19626 	else
19627 		re->ipv6RouteNextHop = gw_addr_v6;
19628 
19629 	/* remote(4), local(3), or discard(2) */
19630 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19631 		re->ipv6RouteType = 2;
19632 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19633 		re->ipv6RouteType = 3;
19634 	else
19635 		re->ipv6RouteType = 4;
19636 
19637 	re->ipv6RouteProtocol	= -1;
19638 	re->ipv6RoutePolicy	= 0;
19639 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19640 	re->ipv6RouteNextHopRDI	= 0;
19641 	re->ipv6RouteWeight	= 0;
19642 	re->ipv6RouteMetric	= 0;
19643 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19644 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19645 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19646 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19647 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19648 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19649 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19650 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19651 
19652 	if (ire->ire_flags & RTF_DYNAMIC) {
19653 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19654 	} else {
19655 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19656 	}
19657 
19658 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19659 	    (char *)re, (int)sizeof (*re))) {
19660 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19661 		    (uint_t)sizeof (*re)));
19662 	}
19663 
19664 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19665 		iaeptr->iae_routeidx = ird->ird_idx;
19666 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19667 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19668 	}
19669 
19670 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19671 	    (char *)iae, sacnt * sizeof (*iae))) {
19672 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19673 		    (unsigned)(sacnt * sizeof (*iae))));
19674 	}
19675 
19676 	/* bump route index for next pass */
19677 	ird->ird_idx++;
19678 
19679 	kmem_free(re, sizeof (*re));
19680 	if (sacnt != 0)
19681 		kmem_free(iae, sacnt * sizeof (*iae));
19682 
19683 	if (gcgrp != NULL)
19684 		rw_exit(&gcgrp->gcgrp_rwlock);
19685 }
19686 
19687 /*
19688  * ndp_walk routine to create ipv6NetToMediaEntryTable
19689  */
19690 static int
19691 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19692 {
19693 	ill_t				*ill;
19694 	mib2_ipv6NetToMediaEntry_t	ntme;
19695 	dl_unitdata_req_t		*dl;
19696 
19697 	ill = nce->nce_ill;
19698 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19699 		return (0);
19700 
19701 	/*
19702 	 * Neighbor cache entry attached to IRE with on-link
19703 	 * destination.
19704 	 */
19705 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19706 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19707 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19708 	    (nce->nce_res_mp != NULL)) {
19709 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19710 		ntme.ipv6NetToMediaPhysAddress.o_length =
19711 		    dl->dl_dest_addr_length;
19712 	} else {
19713 		ntme.ipv6NetToMediaPhysAddress.o_length =
19714 		    ill->ill_phys_addr_length;
19715 	}
19716 	if (nce->nce_res_mp != NULL) {
19717 		bcopy((char *)nce->nce_res_mp->b_rptr +
19718 		    NCE_LL_ADDR_OFFSET(ill),
19719 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19720 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19721 	} else {
19722 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19723 		    ill->ill_phys_addr_length);
19724 	}
19725 	/*
19726 	 * Note: Returns ND_* states. Should be:
19727 	 * reachable(1), stale(2), delay(3), probe(4),
19728 	 * invalid(5), unknown(6)
19729 	 */
19730 	ntme.ipv6NetToMediaState = nce->nce_state;
19731 	ntme.ipv6NetToMediaLastUpdated = 0;
19732 
19733 	/* other(1), dynamic(2), static(3), local(4) */
19734 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19735 		ntme.ipv6NetToMediaType = 4;
19736 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19737 		ntme.ipv6NetToMediaType = 1;
19738 	} else {
19739 		ntme.ipv6NetToMediaType = 2;
19740 	}
19741 
19742 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19743 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19744 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19745 		    (uint_t)sizeof (ntme)));
19746 	}
19747 	return (0);
19748 }
19749 
19750 /*
19751  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19752  */
19753 /* ARGSUSED */
19754 int
19755 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19756 {
19757 	switch (level) {
19758 	case MIB2_IP:
19759 	case MIB2_ICMP:
19760 		switch (name) {
19761 		default:
19762 			break;
19763 		}
19764 		return (1);
19765 	default:
19766 		return (1);
19767 	}
19768 }
19769 
19770 /*
19771  * When there exists both a 64- and 32-bit counter of a particular type
19772  * (i.e., InReceives), only the 64-bit counters are added.
19773  */
19774 void
19775 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19776 {
19777 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19778 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19779 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19780 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19781 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19782 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19783 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19784 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19785 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19786 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19787 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19788 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19789 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19790 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19791 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
19792 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
19793 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
19794 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
19795 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
19796 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
19797 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
19798 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
19799 	    o2->ipIfStatsInWrongIPVersion);
19800 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
19801 	    o2->ipIfStatsInWrongIPVersion);
19802 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
19803 	    o2->ipIfStatsOutSwitchIPVersion);
19804 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
19805 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
19806 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
19807 	    o2->ipIfStatsHCInForwDatagrams);
19808 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
19809 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
19810 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
19811 	    o2->ipIfStatsHCOutForwDatagrams);
19812 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
19813 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
19814 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
19815 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
19816 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
19817 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
19818 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
19819 	    o2->ipIfStatsHCOutMcastOctets);
19820 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
19821 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
19822 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
19823 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
19824 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
19825 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
19826 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
19827 }
19828 
19829 void
19830 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
19831 {
19832 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
19833 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
19834 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
19835 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
19836 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
19837 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
19838 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
19839 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
19840 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
19841 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
19842 	    o2->ipv6IfIcmpInRouterSolicits);
19843 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
19844 	    o2->ipv6IfIcmpInRouterAdvertisements);
19845 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
19846 	    o2->ipv6IfIcmpInNeighborSolicits);
19847 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
19848 	    o2->ipv6IfIcmpInNeighborAdvertisements);
19849 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
19850 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
19851 	    o2->ipv6IfIcmpInGroupMembQueries);
19852 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
19853 	    o2->ipv6IfIcmpInGroupMembResponses);
19854 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
19855 	    o2->ipv6IfIcmpInGroupMembReductions);
19856 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
19857 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
19858 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
19859 	    o2->ipv6IfIcmpOutDestUnreachs);
19860 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
19861 	    o2->ipv6IfIcmpOutAdminProhibs);
19862 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
19863 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
19864 	    o2->ipv6IfIcmpOutParmProblems);
19865 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
19866 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
19867 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
19868 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
19869 	    o2->ipv6IfIcmpOutRouterSolicits);
19870 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
19871 	    o2->ipv6IfIcmpOutRouterAdvertisements);
19872 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
19873 	    o2->ipv6IfIcmpOutNeighborSolicits);
19874 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
19875 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
19876 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
19877 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
19878 	    o2->ipv6IfIcmpOutGroupMembQueries);
19879 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
19880 	    o2->ipv6IfIcmpOutGroupMembResponses);
19881 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
19882 	    o2->ipv6IfIcmpOutGroupMembReductions);
19883 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
19884 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
19885 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
19886 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
19887 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
19888 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
19889 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
19890 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
19891 	    o2->ipv6IfIcmpInGroupMembTotal);
19892 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
19893 	    o2->ipv6IfIcmpInGroupMembBadQueries);
19894 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
19895 	    o2->ipv6IfIcmpInGroupMembBadReports);
19896 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
19897 	    o2->ipv6IfIcmpInGroupMembOurReports);
19898 }
19899 
19900 /*
19901  * Called before the options are updated to check if this packet will
19902  * be source routed from here.
19903  * This routine assumes that the options are well formed i.e. that they
19904  * have already been checked.
19905  */
19906 static boolean_t
19907 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
19908 {
19909 	ipoptp_t	opts;
19910 	uchar_t		*opt;
19911 	uint8_t		optval;
19912 	uint8_t		optlen;
19913 	ipaddr_t	dst;
19914 	ire_t		*ire;
19915 
19916 	if (IS_SIMPLE_IPH(ipha)) {
19917 		ip2dbg(("not source routed\n"));
19918 		return (B_FALSE);
19919 	}
19920 	dst = ipha->ipha_dst;
19921 	for (optval = ipoptp_first(&opts, ipha);
19922 	    optval != IPOPT_EOL;
19923 	    optval = ipoptp_next(&opts)) {
19924 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19925 		opt = opts.ipoptp_cur;
19926 		optlen = opts.ipoptp_len;
19927 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19928 		    optval, optlen));
19929 		switch (optval) {
19930 			uint32_t off;
19931 		case IPOPT_SSRR:
19932 		case IPOPT_LSRR:
19933 			/*
19934 			 * If dst is one of our addresses and there are some
19935 			 * entries left in the source route return (true).
19936 			 */
19937 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19938 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
19939 			if (ire == NULL) {
19940 				ip2dbg(("ip_source_routed: not next"
19941 				    " source route 0x%x\n",
19942 				    ntohl(dst)));
19943 				return (B_FALSE);
19944 			}
19945 			ire_refrele(ire);
19946 			off = opt[IPOPT_OFFSET];
19947 			off--;
19948 			if (optlen < IP_ADDR_LEN ||
19949 			    off > optlen - IP_ADDR_LEN) {
19950 				/* End of source route */
19951 				ip1dbg(("ip_source_routed: end of SR\n"));
19952 				return (B_FALSE);
19953 			}
19954 			return (B_TRUE);
19955 		}
19956 	}
19957 	ip2dbg(("not source routed\n"));
19958 	return (B_FALSE);
19959 }
19960 
19961 /*
19962  * Check if the packet contains any source route.
19963  */
19964 static boolean_t
19965 ip_source_route_included(ipha_t *ipha)
19966 {
19967 	ipoptp_t	opts;
19968 	uint8_t		optval;
19969 
19970 	if (IS_SIMPLE_IPH(ipha))
19971 		return (B_FALSE);
19972 	for (optval = ipoptp_first(&opts, ipha);
19973 	    optval != IPOPT_EOL;
19974 	    optval = ipoptp_next(&opts)) {
19975 		switch (optval) {
19976 		case IPOPT_SSRR:
19977 		case IPOPT_LSRR:
19978 			return (B_TRUE);
19979 		}
19980 	}
19981 	return (B_FALSE);
19982 }
19983 
19984 /*
19985  * Called when the IRE expiration timer fires.
19986  */
19987 void
19988 ip_trash_timer_expire(void *args)
19989 {
19990 	int			flush_flag = 0;
19991 	ire_expire_arg_t	iea;
19992 	ip_stack_t		*ipst = (ip_stack_t *)args;
19993 
19994 	iea.iea_ipst = ipst;	/* No netstack_hold */
19995 
19996 	/*
19997 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
19998 	 * This lock makes sure that a new invocation of this function
19999 	 * that occurs due to an almost immediate timer firing will not
20000 	 * progress beyond this point until the current invocation is done
20001 	 */
20002 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20003 	ipst->ips_ip_ire_expire_id = 0;
20004 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20005 
20006 	/* Periodic timer */
20007 	if (ipst->ips_ip_ire_arp_time_elapsed >=
20008 	    ipst->ips_ip_ire_arp_interval) {
20009 		/*
20010 		 * Remove all IRE_CACHE entries since they might
20011 		 * contain arp information.
20012 		 */
20013 		flush_flag |= FLUSH_ARP_TIME;
20014 		ipst->ips_ip_ire_arp_time_elapsed = 0;
20015 		IP_STAT(ipst, ip_ire_arp_timer_expired);
20016 	}
20017 	if (ipst->ips_ip_ire_rd_time_elapsed >=
20018 	    ipst->ips_ip_ire_redir_interval) {
20019 		/* Remove all redirects */
20020 		flush_flag |= FLUSH_REDIRECT_TIME;
20021 		ipst->ips_ip_ire_rd_time_elapsed = 0;
20022 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
20023 	}
20024 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
20025 	    ipst->ips_ip_ire_pathmtu_interval) {
20026 		/* Increase path mtu */
20027 		flush_flag |= FLUSH_MTU_TIME;
20028 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
20029 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
20030 	}
20031 
20032 	/*
20033 	 * Optimize for the case when there are no redirects in the
20034 	 * ftable, that is, no need to walk the ftable in that case.
20035 	 */
20036 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
20037 		iea.iea_flush_flag = flush_flag;
20038 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
20039 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
20040 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
20041 		    NULL, ALL_ZONES, ipst);
20042 	}
20043 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
20044 	    ipst->ips_ip_redirect_cnt > 0) {
20045 		iea.iea_flush_flag = flush_flag;
20046 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
20047 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
20048 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
20049 	}
20050 	if (flush_flag & FLUSH_MTU_TIME) {
20051 		/*
20052 		 * Walk all IPv6 IRE's and update them
20053 		 * Note that ARP and redirect timers are not
20054 		 * needed since NUD handles stale entries.
20055 		 */
20056 		flush_flag = FLUSH_MTU_TIME;
20057 		iea.iea_flush_flag = flush_flag;
20058 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
20059 		    ALL_ZONES, ipst);
20060 	}
20061 
20062 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
20063 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
20064 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
20065 
20066 	/*
20067 	 * Hold the lock to serialize timeout calls and prevent
20068 	 * stale values in ip_ire_expire_id. Otherwise it is possible
20069 	 * for the timer to fire and a new invocation of this function
20070 	 * to start before the return value of timeout has been stored
20071 	 * in ip_ire_expire_id by the current invocation.
20072 	 */
20073 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20074 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
20075 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
20076 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20077 }
20078 
20079 /*
20080  * Called by the memory allocator subsystem directly, when the system
20081  * is running low on memory.
20082  */
20083 /* ARGSUSED */
20084 void
20085 ip_trash_ire_reclaim(void *args)
20086 {
20087 	netstack_handle_t nh;
20088 	netstack_t *ns;
20089 
20090 	netstack_next_init(&nh);
20091 	while ((ns = netstack_next(&nh)) != NULL) {
20092 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
20093 		netstack_rele(ns);
20094 	}
20095 	netstack_next_fini(&nh);
20096 }
20097 
20098 static void
20099 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
20100 {
20101 	ire_cache_count_t icc;
20102 	ire_cache_reclaim_t icr;
20103 	ncc_cache_count_t ncc;
20104 	nce_cache_reclaim_t ncr;
20105 	uint_t delete_cnt;
20106 	/*
20107 	 * Memory reclaim call back.
20108 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
20109 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
20110 	 * entries, determine what fraction to free for
20111 	 * each category of IRE_CACHE entries giving absolute priority
20112 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
20113 	 * entry will be freed unless all offlink entries are freed).
20114 	 */
20115 	icc.icc_total = 0;
20116 	icc.icc_unused = 0;
20117 	icc.icc_offlink = 0;
20118 	icc.icc_pmtu = 0;
20119 	icc.icc_onlink = 0;
20120 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20121 
20122 	/*
20123 	 * Free NCEs for IPv6 like the onlink ires.
20124 	 */
20125 	ncc.ncc_total = 0;
20126 	ncc.ncc_host = 0;
20127 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
20128 
20129 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
20130 	    icc.icc_pmtu + icc.icc_onlink);
20131 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
20132 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
20133 	if (delete_cnt == 0)
20134 		return;
20135 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
20136 	/* Always delete all unused offlink entries */
20137 	icr.icr_ipst = ipst;
20138 	icr.icr_unused = 1;
20139 	if (delete_cnt <= icc.icc_unused) {
20140 		/*
20141 		 * Only need to free unused entries.  In other words,
20142 		 * there are enough unused entries to free to meet our
20143 		 * target number of freed ire cache entries.
20144 		 */
20145 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
20146 		ncr.ncr_host = 0;
20147 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
20148 		/*
20149 		 * Only need to free unused entries, plus a fraction of offlink
20150 		 * entries.  It follows from the first if statement that
20151 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
20152 		 */
20153 		delete_cnt -= icc.icc_unused;
20154 		/* Round up # deleted by truncating fraction */
20155 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
20156 		icr.icr_pmtu = icr.icr_onlink = 0;
20157 		ncr.ncr_host = 0;
20158 	} else if (delete_cnt <=
20159 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
20160 		/*
20161 		 * Free all unused and offlink entries, plus a fraction of
20162 		 * pmtu entries.  It follows from the previous if statement
20163 		 * that icc_pmtu is non-zero, and that
20164 		 * delete_cnt != icc_unused + icc_offlink.
20165 		 */
20166 		icr.icr_offlink = 1;
20167 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
20168 		/* Round up # deleted by truncating fraction */
20169 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
20170 		icr.icr_onlink = 0;
20171 		ncr.ncr_host = 0;
20172 	} else {
20173 		/*
20174 		 * Free all unused, offlink, and pmtu entries, plus a fraction
20175 		 * of onlink entries.  If we're here, then we know that
20176 		 * icc_onlink is non-zero, and that
20177 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
20178 		 */
20179 		icr.icr_offlink = icr.icr_pmtu = 1;
20180 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
20181 		    icc.icc_pmtu;
20182 		/* Round up # deleted by truncating fraction */
20183 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
20184 		/* Using the same delete fraction as for onlink IREs */
20185 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
20186 	}
20187 #ifdef DEBUG
20188 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
20189 	    "fractions %d/%d/%d/%d\n",
20190 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
20191 	    icc.icc_unused, icc.icc_offlink,
20192 	    icc.icc_pmtu, icc.icc_onlink,
20193 	    icr.icr_unused, icr.icr_offlink,
20194 	    icr.icr_pmtu, icr.icr_onlink));
20195 #endif
20196 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
20197 	if (ncr.ncr_host != 0)
20198 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
20199 		    (uchar_t *)&ncr, ipst);
20200 #ifdef DEBUG
20201 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
20202 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
20203 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20204 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
20205 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
20206 	    icc.icc_pmtu, icc.icc_onlink));
20207 #endif
20208 }
20209 
20210 /*
20211  * ip_unbind is called when a copy of an unbind request is received from the
20212  * upper level protocol.  We remove this conn from any fanout hash list it is
20213  * on, and zero out the bind information.  No reply is expected up above.
20214  */
20215 mblk_t *
20216 ip_unbind(queue_t *q, mblk_t *mp)
20217 {
20218 	conn_t	*connp = Q_TO_CONN(q);
20219 
20220 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
20221 
20222 	if (is_system_labeled() && connp->conn_anon_port) {
20223 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
20224 		    connp->conn_mlp_type, connp->conn_ulp,
20225 		    ntohs(connp->conn_lport), B_FALSE);
20226 		connp->conn_anon_port = 0;
20227 	}
20228 	connp->conn_mlp_type = mlptSingle;
20229 
20230 	ipcl_hash_remove(connp);
20231 
20232 	ASSERT(mp->b_cont == NULL);
20233 	/*
20234 	 * Convert mp into a T_OK_ACK
20235 	 */
20236 	mp = mi_tpi_ok_ack_alloc(mp);
20237 
20238 	/*
20239 	 * should not happen in practice... T_OK_ACK is smaller than the
20240 	 * original message.
20241 	 */
20242 	if (mp == NULL)
20243 		return (NULL);
20244 
20245 	/*
20246 	 * Don't bzero the ports if its TCP since TCP still needs the
20247 	 * lport to remove it from its own bind hash. TCP will do the
20248 	 * cleanup.
20249 	 */
20250 	if (!IPCL_IS_TCP(connp))
20251 		bzero(&connp->u_port, sizeof (connp->u_port));
20252 
20253 	return (mp);
20254 }
20255 
20256 /*
20257  * Write side put procedure.  Outbound data, IOCTLs, responses from
20258  * resolvers, etc, come down through here.
20259  *
20260  * arg2 is always a queue_t *.
20261  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
20262  * the zoneid.
20263  * When that queue is not an ill_t, then arg must be a conn_t pointer.
20264  */
20265 void
20266 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
20267 {
20268 	ip_output_options(arg, mp, arg2, caller, &zero_info);
20269 }
20270 
20271 void
20272 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20273     ip_opt_info_t *infop)
20274 {
20275 	conn_t		*connp = NULL;
20276 	queue_t		*q = (queue_t *)arg2;
20277 	ipha_t		*ipha;
20278 #define	rptr	((uchar_t *)ipha)
20279 	ire_t		*ire = NULL;
20280 	ire_t		*sctp_ire = NULL;
20281 	uint32_t	v_hlen_tos_len;
20282 	ipaddr_t	dst;
20283 	mblk_t		*first_mp = NULL;
20284 	boolean_t	mctl_present;
20285 	ipsec_out_t	*io;
20286 	int		match_flags;
20287 	ill_t		*attach_ill = NULL;
20288 					/* Bind to IPIF_NOFAILOVER ill etc. */
20289 	ill_t		*xmit_ill = NULL;	/* IP_XMIT_IF etc. */
20290 	ipif_t		*dst_ipif;
20291 	boolean_t	multirt_need_resolve = B_FALSE;
20292 	mblk_t		*copy_mp = NULL;
20293 	int		err;
20294 	zoneid_t	zoneid;
20295 	int	adjust;
20296 	uint16_t iplen;
20297 	boolean_t	need_decref = B_FALSE;
20298 	boolean_t	ignore_dontroute = B_FALSE;
20299 	boolean_t	ignore_nexthop = B_FALSE;
20300 	boolean_t	ip_nexthop = B_FALSE;
20301 	ipaddr_t	nexthop_addr;
20302 	ip_stack_t	*ipst;
20303 
20304 #ifdef	_BIG_ENDIAN
20305 #define	V_HLEN	(v_hlen_tos_len >> 24)
20306 #else
20307 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20308 #endif
20309 
20310 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20311 	    "ip_wput_start: q %p", q);
20312 
20313 	/*
20314 	 * ip_wput fast path
20315 	 */
20316 
20317 	/* is packet from ARP ? */
20318 	if (q->q_next != NULL) {
20319 		zoneid = (zoneid_t)(uintptr_t)arg;
20320 		goto qnext;
20321 	}
20322 
20323 	connp = (conn_t *)arg;
20324 	ASSERT(connp != NULL);
20325 	zoneid = connp->conn_zoneid;
20326 	ipst = connp->conn_netstack->netstack_ip;
20327 
20328 	/* is queue flow controlled? */
20329 	if ((q->q_first != NULL || connp->conn_draining) &&
20330 	    (caller == IP_WPUT)) {
20331 		ASSERT(!need_decref);
20332 		(void) putq(q, mp);
20333 		return;
20334 	}
20335 
20336 	/* Multidata transmit? */
20337 	if (DB_TYPE(mp) == M_MULTIDATA) {
20338 		/*
20339 		 * We should never get here, since all Multidata messages
20340 		 * originating from tcp should have been directed over to
20341 		 * tcp_multisend() in the first place.
20342 		 */
20343 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20344 		freemsg(mp);
20345 		return;
20346 	} else if (DB_TYPE(mp) != M_DATA)
20347 		goto notdata;
20348 
20349 	if (mp->b_flag & MSGHASREF) {
20350 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20351 		mp->b_flag &= ~MSGHASREF;
20352 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20353 		need_decref = B_TRUE;
20354 	}
20355 	ipha = (ipha_t *)mp->b_rptr;
20356 
20357 	/* is IP header non-aligned or mblk smaller than basic IP header */
20358 #ifndef SAFETY_BEFORE_SPEED
20359 	if (!OK_32PTR(rptr) ||
20360 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20361 		goto hdrtoosmall;
20362 #endif
20363 
20364 	ASSERT(OK_32PTR(ipha));
20365 
20366 	/*
20367 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20368 	 * wrong version, we'll catch it again in ip_output_v6.
20369 	 *
20370 	 * Note that this is *only* locally-generated output here, and never
20371 	 * forwarded data, and that we need to deal only with transports that
20372 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20373 	 * label.)
20374 	 */
20375 	if (is_system_labeled() &&
20376 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20377 	    !connp->conn_ulp_labeled) {
20378 		err = tsol_check_label(BEST_CRED(mp, connp), &mp, &adjust,
20379 		    connp->conn_mac_exempt, ipst);
20380 		ipha = (ipha_t *)mp->b_rptr;
20381 		if (err != 0) {
20382 			first_mp = mp;
20383 			if (err == EINVAL)
20384 				goto icmp_parameter_problem;
20385 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20386 			goto discard_pkt;
20387 		}
20388 		iplen = ntohs(ipha->ipha_length) + adjust;
20389 		ipha->ipha_length = htons(iplen);
20390 	}
20391 
20392 	ASSERT(infop != NULL);
20393 
20394 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20395 		/*
20396 		 * IP_PKTINFO ancillary option is present.
20397 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20398 		 * allows using address of any zone as the source address.
20399 		 */
20400 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20401 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20402 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20403 		if (ire == NULL)
20404 			goto drop_pkt;
20405 		ire_refrele(ire);
20406 		ire = NULL;
20407 	}
20408 
20409 	/*
20410 	 * IP_DONTFAILOVER_IF and IP_XMIT_IF have precedence over
20411 	 * ill index passed in IP_PKTINFO.
20412 	 */
20413 	if (infop->ip_opt_ill_index != 0 &&
20414 	    connp->conn_xmit_if_ill == NULL &&
20415 	    connp->conn_nofailover_ill == NULL) {
20416 
20417 		xmit_ill = ill_lookup_on_ifindex(
20418 		    infop->ip_opt_ill_index, B_FALSE, NULL, NULL, NULL, NULL,
20419 		    ipst);
20420 
20421 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20422 			goto drop_pkt;
20423 		/*
20424 		 * check that there is an ipif belonging
20425 		 * to our zone. IPCL_ZONEID is not used because
20426 		 * IP_ALLZONES option is valid only when the ill is
20427 		 * accessible from all zones i.e has a valid ipif in
20428 		 * all zones.
20429 		 */
20430 		if (!ipif_lookup_zoneid_group(xmit_ill, zoneid, 0, NULL)) {
20431 			goto drop_pkt;
20432 		}
20433 	}
20434 
20435 	/*
20436 	 * If there is a policy, try to attach an ipsec_out in
20437 	 * the front. At the end, first_mp either points to a
20438 	 * M_DATA message or IPSEC_OUT message linked to a
20439 	 * M_DATA message. We have to do it now as we might
20440 	 * lose the "conn" if we go through ip_newroute.
20441 	 */
20442 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20443 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
20444 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20445 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20446 			if (need_decref)
20447 				CONN_DEC_REF(connp);
20448 			return;
20449 		} else {
20450 			ASSERT(mp->b_datap->db_type == M_CTL);
20451 			first_mp = mp;
20452 			mp = mp->b_cont;
20453 			mctl_present = B_TRUE;
20454 		}
20455 	} else {
20456 		first_mp = mp;
20457 		mctl_present = B_FALSE;
20458 	}
20459 
20460 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20461 
20462 	/* is wrong version or IP options present */
20463 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20464 		goto version_hdrlen_check;
20465 	dst = ipha->ipha_dst;
20466 
20467 	if (connp->conn_nofailover_ill != NULL) {
20468 		attach_ill = conn_get_held_ill(connp,
20469 		    &connp->conn_nofailover_ill, &err);
20470 		if (err == ILL_LOOKUP_FAILED) {
20471 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20472 			if (need_decref)
20473 				CONN_DEC_REF(connp);
20474 			freemsg(first_mp);
20475 			return;
20476 		}
20477 	}
20478 
20479 
20480 	/* is packet multicast? */
20481 	if (CLASSD(dst))
20482 		goto multicast;
20483 
20484 	/*
20485 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20486 	 * takes precedence over conn_dontroute and conn_nexthop_set
20487 	 */
20488 	if (xmit_ill != NULL) {
20489 		goto send_from_ill;
20490 	}
20491 
20492 	if ((connp->conn_dontroute) || (connp->conn_xmit_if_ill != NULL) ||
20493 	    (connp->conn_nexthop_set)) {
20494 		/*
20495 		 * If the destination is a broadcast or a loopback
20496 		 * address, SO_DONTROUTE, IP_XMIT_IF and IP_NEXTHOP go
20497 		 * through the standard path. But in the case of local
20498 		 * destination only SO_DONTROUTE and IP_NEXTHOP go through
20499 		 * the standard path not IP_XMIT_IF.
20500 		 */
20501 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20502 		if ((ire == NULL) || ((ire->ire_type != IRE_BROADCAST) &&
20503 		    (ire->ire_type != IRE_LOOPBACK))) {
20504 			if ((connp->conn_dontroute ||
20505 			    connp->conn_nexthop_set) && (ire != NULL) &&
20506 			    (ire->ire_type == IRE_LOCAL))
20507 				goto standard_path;
20508 
20509 			if (ire != NULL) {
20510 				ire_refrele(ire);
20511 				/* No more access to ire */
20512 				ire = NULL;
20513 			}
20514 			/*
20515 			 * bypass routing checks and go directly to
20516 			 * interface.
20517 			 */
20518 			if (connp->conn_dontroute) {
20519 				goto dontroute;
20520 			} else if (connp->conn_nexthop_set) {
20521 				ip_nexthop = B_TRUE;
20522 				nexthop_addr = connp->conn_nexthop_v4;
20523 				goto send_from_ill;
20524 			}
20525 
20526 			/*
20527 			 * If IP_XMIT_IF socket option is set,
20528 			 * then we allow unicast and multicast
20529 			 * packets to go through the ill. It is
20530 			 * quite possible that the destination
20531 			 * is not in the ire cache table and we
20532 			 * do not want to go to ip_newroute()
20533 			 * instead we call ip_newroute_ipif.
20534 			 */
20535 			xmit_ill = conn_get_held_ill(connp,
20536 			    &connp->conn_xmit_if_ill, &err);
20537 			if (err == ILL_LOOKUP_FAILED) {
20538 				BUMP_MIB(&ipst->ips_ip_mib,
20539 				    ipIfStatsOutDiscards);
20540 				if (attach_ill != NULL)
20541 					ill_refrele(attach_ill);
20542 				if (need_decref)
20543 					CONN_DEC_REF(connp);
20544 				freemsg(first_mp);
20545 				return;
20546 			}
20547 			goto send_from_ill;
20548 		}
20549 standard_path:
20550 		/* Must be a broadcast, a loopback or a local ire */
20551 		if (ire != NULL) {
20552 			ire_refrele(ire);
20553 			/* No more access to ire */
20554 			ire = NULL;
20555 		}
20556 	}
20557 
20558 	if (attach_ill != NULL)
20559 		goto send_from_ill;
20560 
20561 	/*
20562 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20563 	 * this for the tcp global queue and listen end point
20564 	 * as it does not really have a real destination to
20565 	 * talk to.  This is also true for SCTP.
20566 	 */
20567 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20568 	    !connp->conn_fully_bound) {
20569 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20570 		if (ire == NULL)
20571 			goto noirefound;
20572 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20573 		    "ip_wput_end: q %p (%S)", q, "end");
20574 
20575 		/*
20576 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20577 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20578 		 */
20579 		if (ire->ire_flags & RTF_MULTIRT) {
20580 
20581 			/*
20582 			 * Force the TTL of multirouted packets if required.
20583 			 * The TTL of such packets is bounded by the
20584 			 * ip_multirt_ttl ndd variable.
20585 			 */
20586 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20587 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20588 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20589 				    "(was %d), dst 0x%08x\n",
20590 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20591 				    ntohl(ire->ire_addr)));
20592 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20593 			}
20594 			/*
20595 			 * We look at this point if there are pending
20596 			 * unresolved routes. ire_multirt_resolvable()
20597 			 * checks in O(n) that all IRE_OFFSUBNET ire
20598 			 * entries for the packet's destination and
20599 			 * flagged RTF_MULTIRT are currently resolved.
20600 			 * If some remain unresolved, we make a copy
20601 			 * of the current message. It will be used
20602 			 * to initiate additional route resolutions.
20603 			 */
20604 			multirt_need_resolve =
20605 			    ire_multirt_need_resolve(ire->ire_addr,
20606 			    MBLK_GETLABEL(first_mp), ipst);
20607 			ip2dbg(("ip_wput[TCP]: ire %p, "
20608 			    "multirt_need_resolve %d, first_mp %p\n",
20609 			    (void *)ire, multirt_need_resolve,
20610 			    (void *)first_mp));
20611 			if (multirt_need_resolve) {
20612 				copy_mp = copymsg(first_mp);
20613 				if (copy_mp != NULL) {
20614 					MULTIRT_DEBUG_TAG(copy_mp);
20615 				}
20616 			}
20617 		}
20618 
20619 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20620 
20621 		/*
20622 		 * Try to resolve another multiroute if
20623 		 * ire_multirt_need_resolve() deemed it necessary.
20624 		 */
20625 		if (copy_mp != NULL) {
20626 			ip_newroute(q, copy_mp, dst, NULL, connp, zoneid, ipst);
20627 		}
20628 		if (need_decref)
20629 			CONN_DEC_REF(connp);
20630 		return;
20631 	}
20632 
20633 	/*
20634 	 * Access to conn_ire_cache. (protected by conn_lock)
20635 	 *
20636 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20637 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20638 	 * send a packet or two with the IRE_CACHE that is going away.
20639 	 * Access to the ire requires an ire refhold on the ire prior to
20640 	 * its use since an interface unplumb thread may delete the cached
20641 	 * ire and release the refhold at any time.
20642 	 *
20643 	 * Caching an ire in the conn_ire_cache
20644 	 *
20645 	 * o Caching an ire pointer in the conn requires a strict check for
20646 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20647 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20648 	 * in the conn is done after making sure under the bucket lock that the
20649 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20650 	 * caching an ire after the unplumb thread has cleaned up the conn.
20651 	 * If the conn does not send a packet subsequently the unplumb thread
20652 	 * will be hanging waiting for the ire count to drop to zero.
20653 	 *
20654 	 * o We also need to atomically test for a null conn_ire_cache and
20655 	 * set the conn_ire_cache under the the protection of the conn_lock
20656 	 * to avoid races among concurrent threads trying to simultaneously
20657 	 * cache an ire in the conn_ire_cache.
20658 	 */
20659 	mutex_enter(&connp->conn_lock);
20660 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20661 
20662 	if (ire != NULL && ire->ire_addr == dst &&
20663 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20664 
20665 		IRE_REFHOLD(ire);
20666 		mutex_exit(&connp->conn_lock);
20667 
20668 	} else {
20669 		boolean_t cached = B_FALSE;
20670 		connp->conn_ire_cache = NULL;
20671 		mutex_exit(&connp->conn_lock);
20672 		/* Release the old ire */
20673 		if (ire != NULL && sctp_ire == NULL)
20674 			IRE_REFRELE_NOTR(ire);
20675 
20676 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20677 		if (ire == NULL)
20678 			goto noirefound;
20679 		IRE_REFHOLD_NOTR(ire);
20680 
20681 		mutex_enter(&connp->conn_lock);
20682 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20683 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20684 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20685 				if (connp->conn_ulp == IPPROTO_TCP)
20686 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20687 				connp->conn_ire_cache = ire;
20688 				cached = B_TRUE;
20689 			}
20690 			rw_exit(&ire->ire_bucket->irb_lock);
20691 		}
20692 		mutex_exit(&connp->conn_lock);
20693 
20694 		/*
20695 		 * We can continue to use the ire but since it was
20696 		 * not cached, we should drop the extra reference.
20697 		 */
20698 		if (!cached)
20699 			IRE_REFRELE_NOTR(ire);
20700 	}
20701 
20702 
20703 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20704 	    "ip_wput_end: q %p (%S)", q, "end");
20705 
20706 	/*
20707 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20708 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20709 	 */
20710 	if (ire->ire_flags & RTF_MULTIRT) {
20711 
20712 		/*
20713 		 * Force the TTL of multirouted packets if required.
20714 		 * The TTL of such packets is bounded by the
20715 		 * ip_multirt_ttl ndd variable.
20716 		 */
20717 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20718 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20719 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20720 			    "(was %d), dst 0x%08x\n",
20721 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20722 			    ntohl(ire->ire_addr)));
20723 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20724 		}
20725 
20726 		/*
20727 		 * At this point, we check to see if there are any pending
20728 		 * unresolved routes. ire_multirt_resolvable()
20729 		 * checks in O(n) that all IRE_OFFSUBNET ire
20730 		 * entries for the packet's destination and
20731 		 * flagged RTF_MULTIRT are currently resolved.
20732 		 * If some remain unresolved, we make a copy
20733 		 * of the current message. It will be used
20734 		 * to initiate additional route resolutions.
20735 		 */
20736 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20737 		    MBLK_GETLABEL(first_mp), ipst);
20738 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20739 		    "multirt_need_resolve %d, first_mp %p\n",
20740 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20741 		if (multirt_need_resolve) {
20742 			copy_mp = copymsg(first_mp);
20743 			if (copy_mp != NULL) {
20744 				MULTIRT_DEBUG_TAG(copy_mp);
20745 			}
20746 		}
20747 	}
20748 
20749 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20750 
20751 	/*
20752 	 * Try to resolve another multiroute if
20753 	 * ire_multirt_resolvable() deemed it necessary
20754 	 */
20755 	if (copy_mp != NULL) {
20756 		ip_newroute(q, copy_mp, dst, NULL, connp, zoneid, ipst);
20757 	}
20758 	if (need_decref)
20759 		CONN_DEC_REF(connp);
20760 	return;
20761 
20762 qnext:
20763 	/*
20764 	 * Upper Level Protocols pass down complete IP datagrams
20765 	 * as M_DATA messages.	Everything else is a sideshow.
20766 	 *
20767 	 * 1) We could be re-entering ip_wput because of ip_neworute
20768 	 *    in which case we could have a IPSEC_OUT message. We
20769 	 *    need to pass through ip_wput like other datagrams and
20770 	 *    hence cannot branch to ip_wput_nondata.
20771 	 *
20772 	 * 2) ARP, AH, ESP, and other clients who are on the module
20773 	 *    instance of IP stream, give us something to deal with.
20774 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20775 	 *
20776 	 * 3) ICMP replies also could come here.
20777 	 */
20778 	ipst = ILLQ_TO_IPST(q);
20779 
20780 	if (DB_TYPE(mp) != M_DATA) {
20781 notdata:
20782 		if (DB_TYPE(mp) == M_CTL) {
20783 			/*
20784 			 * M_CTL messages are used by ARP, AH and ESP to
20785 			 * communicate with IP. We deal with IPSEC_IN and
20786 			 * IPSEC_OUT here. ip_wput_nondata handles other
20787 			 * cases.
20788 			 */
20789 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20790 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20791 				first_mp = mp->b_cont;
20792 				first_mp->b_flag &= ~MSGHASREF;
20793 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20794 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20795 				CONN_DEC_REF(connp);
20796 				connp = NULL;
20797 			}
20798 			if (ii->ipsec_info_type == IPSEC_IN) {
20799 				/*
20800 				 * Either this message goes back to
20801 				 * IPSEC for further processing or to
20802 				 * ULP after policy checks.
20803 				 */
20804 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20805 				return;
20806 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20807 				io = (ipsec_out_t *)ii;
20808 				if (io->ipsec_out_proc_begin) {
20809 					/*
20810 					 * IPSEC processing has already started.
20811 					 * Complete it.
20812 					 * IPQoS notes: We don't care what is
20813 					 * in ipsec_out_ill_index since this
20814 					 * won't be processed for IPQoS policies
20815 					 * in ipsec_out_process.
20816 					 */
20817 					ipsec_out_process(q, mp, NULL,
20818 					    io->ipsec_out_ill_index);
20819 					return;
20820 				} else {
20821 					connp = (q->q_next != NULL) ?
20822 					    NULL : Q_TO_CONN(q);
20823 					first_mp = mp;
20824 					mp = mp->b_cont;
20825 					mctl_present = B_TRUE;
20826 				}
20827 				zoneid = io->ipsec_out_zoneid;
20828 				ASSERT(zoneid != ALL_ZONES);
20829 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20830 				/*
20831 				 * It's an IPsec control message requesting
20832 				 * an SADB update to be sent to the IPsec
20833 				 * hardware acceleration capable ills.
20834 				 */
20835 				ipsec_ctl_t *ipsec_ctl =
20836 				    (ipsec_ctl_t *)mp->b_rptr;
20837 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20838 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20839 				mblk_t *cmp = mp->b_cont;
20840 
20841 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20842 				ASSERT(cmp != NULL);
20843 
20844 				freeb(mp);
20845 				ill_ipsec_capab_send_all(satype, cmp, sa,
20846 				    ipst->ips_netstack);
20847 				return;
20848 			} else {
20849 				/*
20850 				 * This must be ARP or special TSOL signaling.
20851 				 */
20852 				ip_wput_nondata(NULL, q, mp, NULL);
20853 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20854 				    "ip_wput_end: q %p (%S)", q, "nondata");
20855 				return;
20856 			}
20857 		} else {
20858 			/*
20859 			 * This must be non-(ARP/AH/ESP) messages.
20860 			 */
20861 			ASSERT(!need_decref);
20862 			ip_wput_nondata(NULL, q, mp, NULL);
20863 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20864 			    "ip_wput_end: q %p (%S)", q, "nondata");
20865 			return;
20866 		}
20867 	} else {
20868 		first_mp = mp;
20869 		mctl_present = B_FALSE;
20870 	}
20871 
20872 	ASSERT(first_mp != NULL);
20873 	/*
20874 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
20875 	 * to make sure that this packet goes out on the same interface it
20876 	 * came in. We handle that here.
20877 	 */
20878 	if (mctl_present) {
20879 		uint_t ifindex;
20880 
20881 		io = (ipsec_out_t *)first_mp->b_rptr;
20882 		if (io->ipsec_out_attach_if ||
20883 		    io->ipsec_out_xmit_if ||
20884 		    io->ipsec_out_ip_nexthop) {
20885 			ill_t	*ill;
20886 
20887 			/*
20888 			 * We may have lost the conn context if we are
20889 			 * coming here from ip_newroute(). Copy the
20890 			 * nexthop information.
20891 			 */
20892 			if (io->ipsec_out_ip_nexthop) {
20893 				ip_nexthop = B_TRUE;
20894 				nexthop_addr = io->ipsec_out_nexthop_addr;
20895 
20896 				ipha = (ipha_t *)mp->b_rptr;
20897 				dst = ipha->ipha_dst;
20898 				goto send_from_ill;
20899 			} else {
20900 				ASSERT(io->ipsec_out_ill_index != 0);
20901 				ifindex = io->ipsec_out_ill_index;
20902 				ill = ill_lookup_on_ifindex(ifindex, B_FALSE,
20903 				    NULL, NULL, NULL, NULL, ipst);
20904 				/*
20905 				 * ipsec_out_xmit_if bit is used to tell
20906 				 * ip_wput to use the ill to send outgoing data
20907 				 * as we have no conn when data comes from ICMP
20908 				 * error msg routines. Currently this feature is
20909 				 * only used by ip_mrtun_forward routine.
20910 				 */
20911 				if (io->ipsec_out_xmit_if) {
20912 					xmit_ill = ill;
20913 					if (xmit_ill == NULL) {
20914 						ip1dbg(("ip_output:bad ifindex "
20915 						    "for xmit_ill %d\n",
20916 						    ifindex));
20917 						freemsg(first_mp);
20918 						BUMP_MIB(&ipst->ips_ip_mib,
20919 						    ipIfStatsOutDiscards);
20920 						ASSERT(!need_decref);
20921 						return;
20922 					}
20923 					/* Free up the ipsec_out_t mblk */
20924 					ASSERT(first_mp->b_cont == mp);
20925 					first_mp->b_cont = NULL;
20926 					freeb(first_mp);
20927 					/* Just send the IP header+ICMP+data */
20928 					first_mp = mp;
20929 					ipha = (ipha_t *)mp->b_rptr;
20930 					dst = ipha->ipha_dst;
20931 					goto send_from_ill;
20932 				} else {
20933 					attach_ill = ill;
20934 				}
20935 
20936 				if (attach_ill == NULL) {
20937 					ASSERT(xmit_ill == NULL);
20938 					ip1dbg(("ip_output: bad ifindex for "
20939 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
20940 					    ifindex));
20941 					freemsg(first_mp);
20942 					BUMP_MIB(&ipst->ips_ip_mib,
20943 					    ipIfStatsOutDiscards);
20944 					ASSERT(!need_decref);
20945 					return;
20946 				}
20947 			}
20948 		}
20949 	}
20950 
20951 	ASSERT(xmit_ill == NULL);
20952 
20953 	/* We have a complete IP datagram heading outbound. */
20954 	ipha = (ipha_t *)mp->b_rptr;
20955 
20956 #ifndef SPEED_BEFORE_SAFETY
20957 	/*
20958 	 * Make sure we have a full-word aligned message and that at least
20959 	 * a simple IP header is accessible in the first message.  If not,
20960 	 * try a pullup.
20961 	 */
20962 	if (!OK_32PTR(rptr) ||
20963 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
20964 hdrtoosmall:
20965 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20966 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20967 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20968 			if (first_mp == NULL)
20969 				first_mp = mp;
20970 			goto discard_pkt;
20971 		}
20972 
20973 		/* This function assumes that mp points to an IPv4 packet. */
20974 		if (is_system_labeled() && q->q_next == NULL &&
20975 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20976 		    !connp->conn_ulp_labeled) {
20977 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20978 			    &adjust, connp->conn_mac_exempt, ipst);
20979 			ipha = (ipha_t *)mp->b_rptr;
20980 			if (first_mp != NULL)
20981 				first_mp->b_cont = mp;
20982 			if (err != 0) {
20983 				if (first_mp == NULL)
20984 					first_mp = mp;
20985 				if (err == EINVAL)
20986 					goto icmp_parameter_problem;
20987 				ip2dbg(("ip_wput: label check failed (%d)\n",
20988 				    err));
20989 				goto discard_pkt;
20990 			}
20991 			iplen = ntohs(ipha->ipha_length) + adjust;
20992 			ipha->ipha_length = htons(iplen);
20993 		}
20994 
20995 		ipha = (ipha_t *)mp->b_rptr;
20996 		if (first_mp == NULL) {
20997 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
20998 			/*
20999 			 * If we got here because of "goto hdrtoosmall"
21000 			 * We need to attach a IPSEC_OUT.
21001 			 */
21002 			if (connp->conn_out_enforce_policy) {
21003 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
21004 				    NULL, ipha->ipha_protocol,
21005 				    ipst->ips_netstack)) == NULL)) {
21006 					BUMP_MIB(&ipst->ips_ip_mib,
21007 					    ipIfStatsOutDiscards);
21008 					if (need_decref)
21009 						CONN_DEC_REF(connp);
21010 					return;
21011 				} else {
21012 					ASSERT(mp->b_datap->db_type == M_CTL);
21013 					first_mp = mp;
21014 					mp = mp->b_cont;
21015 					mctl_present = B_TRUE;
21016 				}
21017 			} else {
21018 				first_mp = mp;
21019 				mctl_present = B_FALSE;
21020 			}
21021 		}
21022 	}
21023 #endif
21024 
21025 	/* Most of the code below is written for speed, not readability */
21026 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21027 
21028 	/*
21029 	 * If ip_newroute() fails, we're going to need a full
21030 	 * header for the icmp wraparound.
21031 	 */
21032 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
21033 		uint_t	v_hlen;
21034 version_hdrlen_check:
21035 		ASSERT(first_mp != NULL);
21036 		v_hlen = V_HLEN;
21037 		/*
21038 		 * siphon off IPv6 packets coming down from transport
21039 		 * layer modules here.
21040 		 * Note: high-order bit carries NUD reachability confirmation
21041 		 */
21042 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
21043 			/*
21044 			 * XXX implement a IPv4 and IPv6 packet counter per
21045 			 * conn and switch when ratio exceeds e.g. 10:1
21046 			 */
21047 #ifdef notyet
21048 			if (q->q_next == NULL) /* Avoid ill queue */
21049 				ip_setqinfo(RD(q), B_TRUE, B_TRUE, ipst);
21050 #endif
21051 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
21052 			ASSERT(xmit_ill == NULL);
21053 			if (attach_ill != NULL)
21054 				ill_refrele(attach_ill);
21055 			if (need_decref)
21056 				mp->b_flag |= MSGHASREF;
21057 			(void) ip_output_v6(arg, first_mp, arg2, caller);
21058 			return;
21059 		}
21060 
21061 		if ((v_hlen >> 4) != IP_VERSION) {
21062 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21063 			    "ip_wput_end: q %p (%S)", q, "badvers");
21064 			goto discard_pkt;
21065 		}
21066 		/*
21067 		 * Is the header length at least 20 bytes?
21068 		 *
21069 		 * Are there enough bytes accessible in the header?  If
21070 		 * not, try a pullup.
21071 		 */
21072 		v_hlen &= 0xF;
21073 		v_hlen <<= 2;
21074 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
21075 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21076 			    "ip_wput_end: q %p (%S)", q, "badlen");
21077 			goto discard_pkt;
21078 		}
21079 		if (v_hlen > (mp->b_wptr - rptr)) {
21080 			if (!pullupmsg(mp, v_hlen)) {
21081 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21082 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
21083 				goto discard_pkt;
21084 			}
21085 			ipha = (ipha_t *)mp->b_rptr;
21086 		}
21087 		/*
21088 		 * Move first entry from any source route into ipha_dst and
21089 		 * verify the options
21090 		 */
21091 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
21092 		    zoneid, ipst)) {
21093 			ASSERT(xmit_ill == NULL);
21094 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21095 			if (attach_ill != NULL)
21096 				ill_refrele(attach_ill);
21097 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21098 			    "ip_wput_end: q %p (%S)", q, "badopts");
21099 			if (need_decref)
21100 				CONN_DEC_REF(connp);
21101 			return;
21102 		}
21103 	}
21104 	dst = ipha->ipha_dst;
21105 
21106 	/*
21107 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
21108 	 * we have to run the packet through ip_newroute which will take
21109 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
21110 	 * a resolver, or assigning a default gateway, etc.
21111 	 */
21112 	if (CLASSD(dst)) {
21113 		ipif_t	*ipif;
21114 		uint32_t setsrc = 0;
21115 
21116 multicast:
21117 		ASSERT(first_mp != NULL);
21118 		ip2dbg(("ip_wput: CLASSD\n"));
21119 		if (connp == NULL) {
21120 			/*
21121 			 * Use the first good ipif on the ill.
21122 			 * XXX Should this ever happen? (Appears
21123 			 * to show up with just ppp and no ethernet due
21124 			 * to in.rdisc.)
21125 			 * However, ire_send should be able to
21126 			 * call ip_wput_ire directly.
21127 			 *
21128 			 * XXX Also, this can happen for ICMP and other packets
21129 			 * with multicast source addresses.  Perhaps we should
21130 			 * fix things so that we drop the packet in question,
21131 			 * but for now, just run with it.
21132 			 */
21133 			ill_t *ill = (ill_t *)q->q_ptr;
21134 
21135 			/*
21136 			 * Don't honor attach_if for this case. If ill
21137 			 * is part of the group, ipif could belong to
21138 			 * any ill and we cannot maintain attach_ill
21139 			 * and ipif_ill same anymore and the assert
21140 			 * below would fail.
21141 			 */
21142 			if (mctl_present && io->ipsec_out_attach_if) {
21143 				io->ipsec_out_ill_index = 0;
21144 				io->ipsec_out_attach_if = B_FALSE;
21145 				ASSERT(attach_ill != NULL);
21146 				ill_refrele(attach_ill);
21147 				attach_ill = NULL;
21148 			}
21149 
21150 			ASSERT(attach_ill == NULL);
21151 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
21152 			if (ipif == NULL) {
21153 				if (need_decref)
21154 					CONN_DEC_REF(connp);
21155 				freemsg(first_mp);
21156 				return;
21157 			}
21158 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
21159 			    ntohl(dst), ill->ill_name));
21160 		} else {
21161 			/*
21162 			 * The order of precedence is IP_XMIT_IF, IP_PKTINFO
21163 			 * and IP_MULTICAST_IF.
21164 			 * Block comment above this function explains the
21165 			 * locking mechanism used here
21166 			 */
21167 			if (xmit_ill == NULL) {
21168 				xmit_ill = conn_get_held_ill(connp,
21169 				    &connp->conn_xmit_if_ill, &err);
21170 				if (err == ILL_LOOKUP_FAILED) {
21171 					ip1dbg(("ip_wput: No ill for "
21172 					    "IP_XMIT_IF\n"));
21173 					BUMP_MIB(&ipst->ips_ip_mib,
21174 					    ipIfStatsOutNoRoutes);
21175 					goto drop_pkt;
21176 				}
21177 			}
21178 
21179 			if (xmit_ill == NULL) {
21180 				ipif = conn_get_held_ipif(connp,
21181 				    &connp->conn_multicast_ipif, &err);
21182 				if (err == IPIF_LOOKUP_FAILED) {
21183 					ip1dbg(("ip_wput: No ipif for "
21184 					    "multicast\n"));
21185 					BUMP_MIB(&ipst->ips_ip_mib,
21186 					    ipIfStatsOutNoRoutes);
21187 					goto drop_pkt;
21188 				}
21189 			}
21190 			if (xmit_ill != NULL) {
21191 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21192 				if (ipif == NULL) {
21193 					ip1dbg(("ip_wput: No ipif for "
21194 					    "IP_XMIT_IF\n"));
21195 					BUMP_MIB(&ipst->ips_ip_mib,
21196 					    ipIfStatsOutNoRoutes);
21197 					goto drop_pkt;
21198 				}
21199 			} else if (ipif == NULL || ipif->ipif_isv6) {
21200 				/*
21201 				 * We must do this ipif determination here
21202 				 * else we could pass through ip_newroute
21203 				 * and come back here without the conn context.
21204 				 *
21205 				 * Note: we do late binding i.e. we bind to
21206 				 * the interface when the first packet is sent.
21207 				 * For performance reasons we do not rebind on
21208 				 * each packet but keep the binding until the
21209 				 * next IP_MULTICAST_IF option.
21210 				 *
21211 				 * conn_multicast_{ipif,ill} are shared between
21212 				 * IPv4 and IPv6 and AF_INET6 sockets can
21213 				 * send both IPv4 and IPv6 packets. Hence
21214 				 * we have to check that "isv6" matches above.
21215 				 */
21216 				if (ipif != NULL)
21217 					ipif_refrele(ipif);
21218 				ipif = ipif_lookup_group(dst, zoneid, ipst);
21219 				if (ipif == NULL) {
21220 					ip1dbg(("ip_wput: No ipif for "
21221 					    "multicast\n"));
21222 					BUMP_MIB(&ipst->ips_ip_mib,
21223 					    ipIfStatsOutNoRoutes);
21224 					goto drop_pkt;
21225 				}
21226 				err = conn_set_held_ipif(connp,
21227 				    &connp->conn_multicast_ipif, ipif);
21228 				if (err == IPIF_LOOKUP_FAILED) {
21229 					ipif_refrele(ipif);
21230 					ip1dbg(("ip_wput: No ipif for "
21231 					    "multicast\n"));
21232 					BUMP_MIB(&ipst->ips_ip_mib,
21233 					    ipIfStatsOutNoRoutes);
21234 					goto drop_pkt;
21235 				}
21236 			}
21237 		}
21238 		ASSERT(!ipif->ipif_isv6);
21239 		/*
21240 		 * As we may lose the conn by the time we reach ip_wput_ire,
21241 		 * we copy conn_multicast_loop and conn_dontroute on to an
21242 		 * ipsec_out. In case if this datagram goes out secure,
21243 		 * we need the ill_index also. Copy that also into the
21244 		 * ipsec_out.
21245 		 */
21246 		if (mctl_present) {
21247 			io = (ipsec_out_t *)first_mp->b_rptr;
21248 			ASSERT(first_mp->b_datap->db_type == M_CTL);
21249 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
21250 		} else {
21251 			ASSERT(mp == first_mp);
21252 			if ((first_mp = allocb(sizeof (ipsec_info_t),
21253 			    BPRI_HI)) == NULL) {
21254 				ipif_refrele(ipif);
21255 				first_mp = mp;
21256 				goto discard_pkt;
21257 			}
21258 			first_mp->b_datap->db_type = M_CTL;
21259 			first_mp->b_wptr += sizeof (ipsec_info_t);
21260 			/* ipsec_out_secure is B_FALSE now */
21261 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
21262 			io = (ipsec_out_t *)first_mp->b_rptr;
21263 			io->ipsec_out_type = IPSEC_OUT;
21264 			io->ipsec_out_len = sizeof (ipsec_out_t);
21265 			io->ipsec_out_use_global_policy = B_TRUE;
21266 			io->ipsec_out_ns = ipst->ips_netstack;
21267 			first_mp->b_cont = mp;
21268 			mctl_present = B_TRUE;
21269 		}
21270 		if (attach_ill != NULL) {
21271 			ASSERT(attach_ill == ipif->ipif_ill);
21272 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21273 
21274 			/*
21275 			 * Check if we need an ire that will not be
21276 			 * looked up by anybody else i.e. HIDDEN.
21277 			 */
21278 			if (ill_is_probeonly(attach_ill)) {
21279 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21280 			}
21281 			io->ipsec_out_ill_index =
21282 			    attach_ill->ill_phyint->phyint_ifindex;
21283 			io->ipsec_out_attach_if = B_TRUE;
21284 		} else {
21285 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
21286 			io->ipsec_out_ill_index =
21287 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
21288 		}
21289 		if (connp != NULL) {
21290 			io->ipsec_out_multicast_loop =
21291 			    connp->conn_multicast_loop;
21292 			io->ipsec_out_dontroute = connp->conn_dontroute;
21293 			io->ipsec_out_zoneid = connp->conn_zoneid;
21294 		}
21295 		/*
21296 		 * If the application uses IP_MULTICAST_IF with
21297 		 * different logical addresses of the same ILL, we
21298 		 * need to make sure that the soruce address of
21299 		 * the packet matches the logical IP address used
21300 		 * in the option. We do it by initializing ipha_src
21301 		 * here. This should keep IPSEC also happy as
21302 		 * when we return from IPSEC processing, we don't
21303 		 * have to worry about getting the right address on
21304 		 * the packet. Thus it is sufficient to look for
21305 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
21306 		 * MATCH_IRE_IPIF.
21307 		 *
21308 		 * NOTE : We need to do it for non-secure case also as
21309 		 * this might go out secure if there is a global policy
21310 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
21311 		 * address, the source should be initialized already and
21312 		 * hence we won't be initializing here.
21313 		 *
21314 		 * As we do not have the ire yet, it is possible that
21315 		 * we set the source address here and then later discover
21316 		 * that the ire implies the source address to be assigned
21317 		 * through the RTF_SETSRC flag.
21318 		 * In that case, the setsrc variable will remind us
21319 		 * that overwritting the source address by the one
21320 		 * of the RTF_SETSRC-flagged ire is allowed.
21321 		 */
21322 		if (ipha->ipha_src == INADDR_ANY &&
21323 		    (connp == NULL || !connp->conn_unspec_src)) {
21324 			ipha->ipha_src = ipif->ipif_src_addr;
21325 			setsrc = RTF_SETSRC;
21326 		}
21327 		/*
21328 		 * Find an IRE which matches the destination and the outgoing
21329 		 * queue (i.e. the outgoing interface.)
21330 		 * For loopback use a unicast IP address for
21331 		 * the ire lookup.
21332 		 */
21333 		if (IS_LOOPBACK(ipif->ipif_ill))
21334 			dst = ipif->ipif_lcl_addr;
21335 
21336 		/*
21337 		 * If IP_XMIT_IF is set, we branch out to ip_newroute_ipif.
21338 		 * We don't need to lookup ire in ctable as the packet
21339 		 * needs to be sent to the destination through the specified
21340 		 * ill irrespective of ires in the cache table.
21341 		 */
21342 		ire = NULL;
21343 		if (xmit_ill == NULL) {
21344 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21345 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21346 		}
21347 
21348 		/*
21349 		 * refrele attach_ill as its not needed anymore.
21350 		 */
21351 		if (attach_ill != NULL) {
21352 			ill_refrele(attach_ill);
21353 			attach_ill = NULL;
21354 		}
21355 
21356 		if (ire == NULL) {
21357 			/*
21358 			 * Multicast loopback and multicast forwarding is
21359 			 * done in ip_wput_ire.
21360 			 *
21361 			 * Mark this packet to make it be delivered to
21362 			 * ip_wput_ire after the new ire has been
21363 			 * created.
21364 			 *
21365 			 * The call to ip_newroute_ipif takes into account
21366 			 * the setsrc reminder. In any case, we take care
21367 			 * of the RTF_MULTIRT flag.
21368 			 */
21369 			mp->b_prev = mp->b_next = NULL;
21370 			if (xmit_ill == NULL ||
21371 			    xmit_ill->ill_ipif_up_count > 0) {
21372 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21373 				    setsrc | RTF_MULTIRT, zoneid, infop);
21374 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21375 				    "ip_wput_end: q %p (%S)", q, "noire");
21376 			} else {
21377 				freemsg(first_mp);
21378 			}
21379 			ipif_refrele(ipif);
21380 			if (xmit_ill != NULL)
21381 				ill_refrele(xmit_ill);
21382 			if (need_decref)
21383 				CONN_DEC_REF(connp);
21384 			return;
21385 		}
21386 
21387 		ipif_refrele(ipif);
21388 		ipif = NULL;
21389 		ASSERT(xmit_ill == NULL);
21390 
21391 		/*
21392 		 * Honor the RTF_SETSRC flag for multicast packets,
21393 		 * if allowed by the setsrc reminder.
21394 		 */
21395 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21396 			ipha->ipha_src = ire->ire_src_addr;
21397 		}
21398 
21399 		/*
21400 		 * Unconditionally force the TTL to 1 for
21401 		 * multirouted multicast packets:
21402 		 * multirouted multicast should not cross
21403 		 * multicast routers.
21404 		 */
21405 		if (ire->ire_flags & RTF_MULTIRT) {
21406 			if (ipha->ipha_ttl > 1) {
21407 				ip2dbg(("ip_wput: forcing multicast "
21408 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21409 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21410 				ipha->ipha_ttl = 1;
21411 			}
21412 		}
21413 	} else {
21414 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
21415 		if ((ire != NULL) && (ire->ire_type &
21416 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21417 			ignore_dontroute = B_TRUE;
21418 			ignore_nexthop = B_TRUE;
21419 		}
21420 		if (ire != NULL) {
21421 			ire_refrele(ire);
21422 			ire = NULL;
21423 		}
21424 		/*
21425 		 * Guard against coming in from arp in which case conn is NULL.
21426 		 * Also guard against non M_DATA with dontroute set but
21427 		 * destined to local, loopback or broadcast addresses.
21428 		 */
21429 		if (connp != NULL && connp->conn_dontroute &&
21430 		    !ignore_dontroute) {
21431 dontroute:
21432 			/*
21433 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21434 			 * routing protocols from seeing false direct
21435 			 * connectivity.
21436 			 */
21437 			ipha->ipha_ttl = 1;
21438 			/*
21439 			 * If IP_XMIT_IF is also set (conn_xmit_if_ill != NULL)
21440 			 * along with SO_DONTROUTE, higher precedence is
21441 			 * given to IP_XMIT_IF and the IP_XMIT_IF ipif is used.
21442 			 */
21443 			if (connp->conn_xmit_if_ill == NULL) {
21444 				/* If suitable ipif not found, drop packet */
21445 				dst_ipif = ipif_lookup_onlink_addr(dst, zoneid,
21446 				    ipst);
21447 				if (dst_ipif == NULL) {
21448 					ip1dbg(("ip_wput: no route for "
21449 					    "dst using SO_DONTROUTE\n"));
21450 					BUMP_MIB(&ipst->ips_ip_mib,
21451 					    ipIfStatsOutNoRoutes);
21452 					mp->b_prev = mp->b_next = NULL;
21453 					if (first_mp == NULL)
21454 						first_mp = mp;
21455 					goto drop_pkt;
21456 				} else {
21457 					/*
21458 					 * If suitable ipif has been found, set
21459 					 * xmit_ill to the corresponding
21460 					 * ipif_ill because we'll be following
21461 					 * the IP_XMIT_IF logic.
21462 					 */
21463 					ASSERT(xmit_ill == NULL);
21464 					xmit_ill = dst_ipif->ipif_ill;
21465 					mutex_enter(&xmit_ill->ill_lock);
21466 					if (!ILL_CAN_LOOKUP(xmit_ill)) {
21467 						mutex_exit(&xmit_ill->ill_lock);
21468 						xmit_ill = NULL;
21469 						ipif_refrele(dst_ipif);
21470 						ip1dbg(("ip_wput: no route for"
21471 						    " dst using"
21472 						    " SO_DONTROUTE\n"));
21473 						BUMP_MIB(&ipst->ips_ip_mib,
21474 						    ipIfStatsOutNoRoutes);
21475 						mp->b_prev = mp->b_next = NULL;
21476 						if (first_mp == NULL)
21477 							first_mp = mp;
21478 						goto drop_pkt;
21479 					}
21480 					ill_refhold_locked(xmit_ill);
21481 					mutex_exit(&xmit_ill->ill_lock);
21482 					ipif_refrele(dst_ipif);
21483 				}
21484 			}
21485 
21486 		}
21487 		/*
21488 		 * If we are bound to IPIF_NOFAILOVER address, look for
21489 		 * an IRE_CACHE matching the ill.
21490 		 */
21491 send_from_ill:
21492 		if (attach_ill != NULL) {
21493 			ipif_t	*attach_ipif;
21494 
21495 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21496 
21497 			/*
21498 			 * Check if we need an ire that will not be
21499 			 * looked up by anybody else i.e. HIDDEN.
21500 			 */
21501 			if (ill_is_probeonly(attach_ill)) {
21502 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21503 			}
21504 
21505 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
21506 			if (attach_ipif == NULL) {
21507 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
21508 				goto discard_pkt;
21509 			}
21510 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
21511 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21512 			ipif_refrele(attach_ipif);
21513 		} else if (xmit_ill != NULL || (connp != NULL &&
21514 		    connp->conn_xmit_if_ill != NULL)) {
21515 			/*
21516 			 * Mark this packet as originated locally
21517 			 */
21518 			mp->b_prev = mp->b_next = NULL;
21519 			/*
21520 			 * xmit_ill could be NULL if SO_DONTROUTE
21521 			 * is also set.
21522 			 */
21523 			if (xmit_ill == NULL) {
21524 				xmit_ill = conn_get_held_ill(connp,
21525 				    &connp->conn_xmit_if_ill, &err);
21526 				if (err == ILL_LOOKUP_FAILED) {
21527 					BUMP_MIB(&ipst->ips_ip_mib,
21528 					    ipIfStatsOutDiscards);
21529 					if (need_decref)
21530 						CONN_DEC_REF(connp);
21531 					freemsg(first_mp);
21532 					return;
21533 				}
21534 				if (xmit_ill == NULL) {
21535 					if (connp->conn_dontroute)
21536 						goto dontroute;
21537 					goto send_from_ill;
21538 				}
21539 			}
21540 			/*
21541 			 * Could be SO_DONTROUTE case also.
21542 			 * check at least one interface is UP as
21543 			 * specified by this ILL
21544 			 */
21545 			if (xmit_ill->ill_ipif_up_count > 0) {
21546 				ipif_t *ipif;
21547 
21548 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21549 				if (ipif == NULL) {
21550 					ip1dbg(("ip_output: "
21551 					    "xmit_ill NULL ipif\n"));
21552 					goto drop_pkt;
21553 				}
21554 				/*
21555 				 * Look for a ire that is part of the group,
21556 				 * if found use it else call ip_newroute_ipif.
21557 				 * IPCL_ZONEID is not used for matching because
21558 				 * IP_ALLZONES option is valid only when the
21559 				 * ill is accessible from all zones i.e has a
21560 				 * valid ipif in all zones.
21561 				 */
21562 				match_flags = MATCH_IRE_ILL_GROUP |
21563 				    MATCH_IRE_SECATTR;
21564 				ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21565 				    MBLK_GETLABEL(mp), match_flags, ipst);
21566 				/*
21567 				 * If an ire exists use it or else create
21568 				 * an ire but don't add it to the cache.
21569 				 * Adding an ire may cause issues with
21570 				 * asymmetric routing.
21571 				 * In case of multiroute always act as if
21572 				 * ire does not exist.
21573 				 */
21574 				if (ire == NULL ||
21575 				    ire->ire_flags & RTF_MULTIRT) {
21576 					if (ire != NULL)
21577 						ire_refrele(ire);
21578 					ip_newroute_ipif(q, first_mp, ipif,
21579 					    dst, connp, 0, zoneid, infop);
21580 					ipif_refrele(ipif);
21581 					ip1dbg(("ip_wput: ip_unicast_if\n"));
21582 					ill_refrele(xmit_ill);
21583 					if (need_decref)
21584 						CONN_DEC_REF(connp);
21585 					return;
21586 				}
21587 				ipif_refrele(ipif);
21588 			} else {
21589 				goto drop_pkt;
21590 			}
21591 		} else if (ip_nexthop || (connp != NULL &&
21592 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21593 			if (!ip_nexthop) {
21594 				ip_nexthop = B_TRUE;
21595 				nexthop_addr = connp->conn_nexthop_v4;
21596 			}
21597 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21598 			    MATCH_IRE_GW;
21599 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21600 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21601 		} else {
21602 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp),
21603 			    ipst);
21604 		}
21605 		if (!ire) {
21606 			/*
21607 			 * Make sure we don't load spread if this
21608 			 * is IPIF_NOFAILOVER case.
21609 			 */
21610 			if ((attach_ill != NULL) ||
21611 			    (ip_nexthop && !ignore_nexthop)) {
21612 				if (mctl_present) {
21613 					io = (ipsec_out_t *)first_mp->b_rptr;
21614 					ASSERT(first_mp->b_datap->db_type ==
21615 					    M_CTL);
21616 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21617 				} else {
21618 					ASSERT(mp == first_mp);
21619 					first_mp = allocb(
21620 					    sizeof (ipsec_info_t), BPRI_HI);
21621 					if (first_mp == NULL) {
21622 						first_mp = mp;
21623 						goto discard_pkt;
21624 					}
21625 					first_mp->b_datap->db_type = M_CTL;
21626 					first_mp->b_wptr +=
21627 					    sizeof (ipsec_info_t);
21628 					/* ipsec_out_secure is B_FALSE now */
21629 					bzero(first_mp->b_rptr,
21630 					    sizeof (ipsec_info_t));
21631 					io = (ipsec_out_t *)first_mp->b_rptr;
21632 					io->ipsec_out_type = IPSEC_OUT;
21633 					io->ipsec_out_len =
21634 					    sizeof (ipsec_out_t);
21635 					io->ipsec_out_use_global_policy =
21636 					    B_TRUE;
21637 					io->ipsec_out_ns = ipst->ips_netstack;
21638 					first_mp->b_cont = mp;
21639 					mctl_present = B_TRUE;
21640 				}
21641 				if (attach_ill != NULL) {
21642 					io->ipsec_out_ill_index = attach_ill->
21643 					    ill_phyint->phyint_ifindex;
21644 					io->ipsec_out_attach_if = B_TRUE;
21645 				} else {
21646 					io->ipsec_out_ip_nexthop = ip_nexthop;
21647 					io->ipsec_out_nexthop_addr =
21648 					    nexthop_addr;
21649 				}
21650 			}
21651 noirefound:
21652 			/*
21653 			 * Mark this packet as having originated on
21654 			 * this machine.  This will be noted in
21655 			 * ire_add_then_send, which needs to know
21656 			 * whether to run it back through ip_wput or
21657 			 * ip_rput following successful resolution.
21658 			 */
21659 			mp->b_prev = NULL;
21660 			mp->b_next = NULL;
21661 			ip_newroute(q, first_mp, dst, NULL, connp, zoneid,
21662 			    ipst);
21663 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21664 			    "ip_wput_end: q %p (%S)", q, "newroute");
21665 			if (attach_ill != NULL)
21666 				ill_refrele(attach_ill);
21667 			if (xmit_ill != NULL)
21668 				ill_refrele(xmit_ill);
21669 			if (need_decref)
21670 				CONN_DEC_REF(connp);
21671 			return;
21672 		}
21673 	}
21674 
21675 	/* We now know where we are going with it. */
21676 
21677 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21678 	    "ip_wput_end: q %p (%S)", q, "end");
21679 
21680 	/*
21681 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21682 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21683 	 */
21684 	if (ire->ire_flags & RTF_MULTIRT) {
21685 		/*
21686 		 * Force the TTL of multirouted packets if required.
21687 		 * The TTL of such packets is bounded by the
21688 		 * ip_multirt_ttl ndd variable.
21689 		 */
21690 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21691 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21692 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21693 			    "(was %d), dst 0x%08x\n",
21694 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21695 			    ntohl(ire->ire_addr)));
21696 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21697 		}
21698 		/*
21699 		 * At this point, we check to see if there are any pending
21700 		 * unresolved routes. ire_multirt_resolvable()
21701 		 * checks in O(n) that all IRE_OFFSUBNET ire
21702 		 * entries for the packet's destination and
21703 		 * flagged RTF_MULTIRT are currently resolved.
21704 		 * If some remain unresolved, we make a copy
21705 		 * of the current message. It will be used
21706 		 * to initiate additional route resolutions.
21707 		 */
21708 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21709 		    MBLK_GETLABEL(first_mp), ipst);
21710 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21711 		    "multirt_need_resolve %d, first_mp %p\n",
21712 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21713 		if (multirt_need_resolve) {
21714 			copy_mp = copymsg(first_mp);
21715 			if (copy_mp != NULL) {
21716 				MULTIRT_DEBUG_TAG(copy_mp);
21717 			}
21718 		}
21719 	}
21720 
21721 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21722 	/*
21723 	 * Try to resolve another multiroute if
21724 	 * ire_multirt_resolvable() deemed it necessary.
21725 	 * At this point, we need to distinguish
21726 	 * multicasts from other packets. For multicasts,
21727 	 * we call ip_newroute_ipif() and request that both
21728 	 * multirouting and setsrc flags are checked.
21729 	 */
21730 	if (copy_mp != NULL) {
21731 		if (CLASSD(dst)) {
21732 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21733 			if (ipif) {
21734 				ASSERT(infop->ip_opt_ill_index == 0);
21735 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21736 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21737 				ipif_refrele(ipif);
21738 			} else {
21739 				MULTIRT_DEBUG_UNTAG(copy_mp);
21740 				freemsg(copy_mp);
21741 				copy_mp = NULL;
21742 			}
21743 		} else {
21744 			ip_newroute(q, copy_mp, dst, NULL, connp, zoneid, ipst);
21745 		}
21746 	}
21747 	if (attach_ill != NULL)
21748 		ill_refrele(attach_ill);
21749 	if (xmit_ill != NULL)
21750 		ill_refrele(xmit_ill);
21751 	if (need_decref)
21752 		CONN_DEC_REF(connp);
21753 	return;
21754 
21755 icmp_parameter_problem:
21756 	/* could not have originated externally */
21757 	ASSERT(mp->b_prev == NULL);
21758 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21759 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21760 		/* it's the IP header length that's in trouble */
21761 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21762 		first_mp = NULL;
21763 	}
21764 
21765 discard_pkt:
21766 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21767 drop_pkt:
21768 	ip1dbg(("ip_wput: dropped packet\n"));
21769 	if (ire != NULL)
21770 		ire_refrele(ire);
21771 	if (need_decref)
21772 		CONN_DEC_REF(connp);
21773 	freemsg(first_mp);
21774 	if (attach_ill != NULL)
21775 		ill_refrele(attach_ill);
21776 	if (xmit_ill != NULL)
21777 		ill_refrele(xmit_ill);
21778 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21779 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21780 }
21781 
21782 /*
21783  * If this is a conn_t queue, then we pass in the conn. This includes the
21784  * zoneid.
21785  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21786  * in which case we use the global zoneid since those are all part of
21787  * the global zone.
21788  */
21789 void
21790 ip_wput(queue_t *q, mblk_t *mp)
21791 {
21792 	if (CONN_Q(q))
21793 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21794 	else
21795 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21796 }
21797 
21798 /*
21799  *
21800  * The following rules must be observed when accessing any ipif or ill
21801  * that has been cached in the conn. Typically conn_nofailover_ill,
21802  * conn_xmit_if_ill, conn_multicast_ipif and conn_multicast_ill.
21803  *
21804  * Access: The ipif or ill pointed to from the conn can be accessed under
21805  * the protection of the conn_lock or after it has been refheld under the
21806  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21807  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21808  * The reason for this is that a concurrent unplumb could actually be
21809  * cleaning up these cached pointers by walking the conns and might have
21810  * finished cleaning up the conn in question. The macros check that an
21811  * unplumb has not yet started on the ipif or ill.
21812  *
21813  * Caching: An ipif or ill pointer may be cached in the conn only after
21814  * making sure that an unplumb has not started. So the caching is done
21815  * while holding both the conn_lock and the ill_lock and after using the
21816  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21817  * flag before starting the cleanup of conns.
21818  *
21819  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21820  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21821  * or a reference to the ipif or a reference to an ire that references the
21822  * ipif. An ipif does not change its ill except for failover/failback. Since
21823  * failover/failback happens only after bringing down the ipif and making sure
21824  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
21825  * the above holds.
21826  */
21827 ipif_t *
21828 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21829 {
21830 	ipif_t	*ipif;
21831 	ill_t	*ill;
21832 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21833 
21834 	*err = 0;
21835 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21836 	mutex_enter(&connp->conn_lock);
21837 	ipif = *ipifp;
21838 	if (ipif != NULL) {
21839 		ill = ipif->ipif_ill;
21840 		mutex_enter(&ill->ill_lock);
21841 		if (IPIF_CAN_LOOKUP(ipif)) {
21842 			ipif_refhold_locked(ipif);
21843 			mutex_exit(&ill->ill_lock);
21844 			mutex_exit(&connp->conn_lock);
21845 			rw_exit(&ipst->ips_ill_g_lock);
21846 			return (ipif);
21847 		} else {
21848 			*err = IPIF_LOOKUP_FAILED;
21849 		}
21850 		mutex_exit(&ill->ill_lock);
21851 	}
21852 	mutex_exit(&connp->conn_lock);
21853 	rw_exit(&ipst->ips_ill_g_lock);
21854 	return (NULL);
21855 }
21856 
21857 ill_t *
21858 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21859 {
21860 	ill_t	*ill;
21861 
21862 	*err = 0;
21863 	mutex_enter(&connp->conn_lock);
21864 	ill = *illp;
21865 	if (ill != NULL) {
21866 		mutex_enter(&ill->ill_lock);
21867 		if (ILL_CAN_LOOKUP(ill)) {
21868 			ill_refhold_locked(ill);
21869 			mutex_exit(&ill->ill_lock);
21870 			mutex_exit(&connp->conn_lock);
21871 			return (ill);
21872 		} else {
21873 			*err = ILL_LOOKUP_FAILED;
21874 		}
21875 		mutex_exit(&ill->ill_lock);
21876 	}
21877 	mutex_exit(&connp->conn_lock);
21878 	return (NULL);
21879 }
21880 
21881 static int
21882 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21883 {
21884 	ill_t	*ill;
21885 
21886 	ill = ipif->ipif_ill;
21887 	mutex_enter(&connp->conn_lock);
21888 	mutex_enter(&ill->ill_lock);
21889 	if (IPIF_CAN_LOOKUP(ipif)) {
21890 		*ipifp = ipif;
21891 		mutex_exit(&ill->ill_lock);
21892 		mutex_exit(&connp->conn_lock);
21893 		return (0);
21894 	}
21895 	mutex_exit(&ill->ill_lock);
21896 	mutex_exit(&connp->conn_lock);
21897 	return (IPIF_LOOKUP_FAILED);
21898 }
21899 
21900 /*
21901  * This is called if the outbound datagram needs fragmentation.
21902  *
21903  * NOTE : This function does not ire_refrele the ire argument passed in.
21904  */
21905 static void
21906 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21907     ip_stack_t *ipst)
21908 {
21909 	ipha_t		*ipha;
21910 	mblk_t		*mp;
21911 	uint32_t	v_hlen_tos_len;
21912 	uint32_t	max_frag;
21913 	uint32_t	frag_flag;
21914 	boolean_t	dont_use;
21915 
21916 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21917 		mp = ipsec_mp->b_cont;
21918 	} else {
21919 		mp = ipsec_mp;
21920 	}
21921 
21922 	ipha = (ipha_t *)mp->b_rptr;
21923 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21924 
21925 #ifdef	_BIG_ENDIAN
21926 #define	V_HLEN	(v_hlen_tos_len >> 24)
21927 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21928 #else
21929 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21930 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21931 #endif
21932 
21933 #ifndef SPEED_BEFORE_SAFETY
21934 	/*
21935 	 * Check that ipha_length is consistent with
21936 	 * the mblk length
21937 	 */
21938 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21939 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21940 		    LENGTH, msgdsize(mp)));
21941 		freemsg(ipsec_mp);
21942 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21943 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21944 		    "packet length mismatch");
21945 		return;
21946 	}
21947 #endif
21948 	/*
21949 	 * Don't use frag_flag if pre-built packet or source
21950 	 * routed or if multicast (since multicast packets do not solicit
21951 	 * ICMP "packet too big" messages). Get the values of
21952 	 * max_frag and frag_flag atomically by acquiring the
21953 	 * ire_lock.
21954 	 */
21955 	mutex_enter(&ire->ire_lock);
21956 	max_frag = ire->ire_max_frag;
21957 	frag_flag = ire->ire_frag_flag;
21958 	mutex_exit(&ire->ire_lock);
21959 
21960 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21961 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21962 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21963 
21964 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21965 	    (dont_use ? 0 : frag_flag), zoneid, ipst);
21966 }
21967 
21968 /*
21969  * Used for deciding the MSS size for the upper layer. Thus
21970  * we need to check the outbound policy values in the conn.
21971  */
21972 int
21973 conn_ipsec_length(conn_t *connp)
21974 {
21975 	ipsec_latch_t *ipl;
21976 
21977 	ipl = connp->conn_latch;
21978 	if (ipl == NULL)
21979 		return (0);
21980 
21981 	if (ipl->ipl_out_policy == NULL)
21982 		return (0);
21983 
21984 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21985 }
21986 
21987 /*
21988  * Returns an estimate of the IPSEC headers size. This is used if
21989  * we don't want to call into IPSEC to get the exact size.
21990  */
21991 int
21992 ipsec_out_extra_length(mblk_t *ipsec_mp)
21993 {
21994 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21995 	ipsec_action_t *a;
21996 
21997 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21998 	if (!io->ipsec_out_secure)
21999 		return (0);
22000 
22001 	a = io->ipsec_out_act;
22002 
22003 	if (a == NULL) {
22004 		ASSERT(io->ipsec_out_policy != NULL);
22005 		a = io->ipsec_out_policy->ipsp_act;
22006 	}
22007 	ASSERT(a != NULL);
22008 
22009 	return (a->ipa_ovhd);
22010 }
22011 
22012 /*
22013  * Returns an estimate of the IPSEC headers size. This is used if
22014  * we don't want to call into IPSEC to get the exact size.
22015  */
22016 int
22017 ipsec_in_extra_length(mblk_t *ipsec_mp)
22018 {
22019 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
22020 	ipsec_action_t *a;
22021 
22022 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
22023 
22024 	a = ii->ipsec_in_action;
22025 	return (a == NULL ? 0 : a->ipa_ovhd);
22026 }
22027 
22028 /*
22029  * If there are any source route options, return the true final
22030  * destination. Otherwise, return the destination.
22031  */
22032 ipaddr_t
22033 ip_get_dst(ipha_t *ipha)
22034 {
22035 	ipoptp_t	opts;
22036 	uchar_t		*opt;
22037 	uint8_t		optval;
22038 	uint8_t		optlen;
22039 	ipaddr_t	dst;
22040 	uint32_t off;
22041 
22042 	dst = ipha->ipha_dst;
22043 
22044 	if (IS_SIMPLE_IPH(ipha))
22045 		return (dst);
22046 
22047 	for (optval = ipoptp_first(&opts, ipha);
22048 	    optval != IPOPT_EOL;
22049 	    optval = ipoptp_next(&opts)) {
22050 		opt = opts.ipoptp_cur;
22051 		optlen = opts.ipoptp_len;
22052 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
22053 		switch (optval) {
22054 		case IPOPT_SSRR:
22055 		case IPOPT_LSRR:
22056 			off = opt[IPOPT_OFFSET];
22057 			/*
22058 			 * If one of the conditions is true, it means
22059 			 * end of options and dst already has the right
22060 			 * value.
22061 			 */
22062 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
22063 				off = optlen - IP_ADDR_LEN;
22064 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
22065 			}
22066 			return (dst);
22067 		default:
22068 			break;
22069 		}
22070 	}
22071 
22072 	return (dst);
22073 }
22074 
22075 mblk_t *
22076 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
22077     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
22078 {
22079 	ipsec_out_t	*io;
22080 	mblk_t		*first_mp;
22081 	boolean_t policy_present;
22082 	ip_stack_t	*ipst;
22083 	ipsec_stack_t	*ipss;
22084 
22085 	ASSERT(ire != NULL);
22086 	ipst = ire->ire_ipst;
22087 	ipss = ipst->ips_netstack->netstack_ipsec;
22088 
22089 	first_mp = mp;
22090 	if (mp->b_datap->db_type == M_CTL) {
22091 		io = (ipsec_out_t *)first_mp->b_rptr;
22092 		/*
22093 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
22094 		 *
22095 		 * 1) There is per-socket policy (including cached global
22096 		 *    policy) or a policy on the IP-in-IP tunnel.
22097 		 * 2) There is no per-socket policy, but it is
22098 		 *    a multicast packet that needs to go out
22099 		 *    on a specific interface. This is the case
22100 		 *    where (ip_wput and ip_wput_multicast) attaches
22101 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
22102 		 *
22103 		 * In case (2) we check with global policy to
22104 		 * see if there is a match and set the ill_index
22105 		 * appropriately so that we can lookup the ire
22106 		 * properly in ip_wput_ipsec_out.
22107 		 */
22108 
22109 		/*
22110 		 * ipsec_out_use_global_policy is set to B_FALSE
22111 		 * in ipsec_in_to_out(). Refer to that function for
22112 		 * details.
22113 		 */
22114 		if ((io->ipsec_out_latch == NULL) &&
22115 		    (io->ipsec_out_use_global_policy)) {
22116 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
22117 			    ire, connp, unspec_src, zoneid));
22118 		}
22119 		if (!io->ipsec_out_secure) {
22120 			/*
22121 			 * If this is not a secure packet, drop
22122 			 * the IPSEC_OUT mp and treat it as a clear
22123 			 * packet. This happens when we are sending
22124 			 * a ICMP reply back to a clear packet. See
22125 			 * ipsec_in_to_out() for details.
22126 			 */
22127 			mp = first_mp->b_cont;
22128 			freeb(first_mp);
22129 		}
22130 		return (mp);
22131 	}
22132 	/*
22133 	 * See whether we need to attach a global policy here. We
22134 	 * don't depend on the conn (as it could be null) for deciding
22135 	 * what policy this datagram should go through because it
22136 	 * should have happened in ip_wput if there was some
22137 	 * policy. This normally happens for connections which are not
22138 	 * fully bound preventing us from caching policies in
22139 	 * ip_bind. Packets coming from the TCP listener/global queue
22140 	 * - which are non-hard_bound - could also be affected by
22141 	 * applying policy here.
22142 	 *
22143 	 * If this packet is coming from tcp global queue or listener,
22144 	 * we will be applying policy here.  This may not be *right*
22145 	 * if these packets are coming from the detached connection as
22146 	 * it could have gone in clear before. This happens only if a
22147 	 * TCP connection started when there is no policy and somebody
22148 	 * added policy before it became detached. Thus packets of the
22149 	 * detached connection could go out secure and the other end
22150 	 * would drop it because it will be expecting in clear. The
22151 	 * converse is not true i.e if somebody starts a TCP
22152 	 * connection and deletes the policy, all the packets will
22153 	 * still go out with the policy that existed before deleting
22154 	 * because ip_unbind sends up policy information which is used
22155 	 * by TCP on subsequent ip_wputs. The right solution is to fix
22156 	 * TCP to attach a dummy IPSEC_OUT and set
22157 	 * ipsec_out_use_global_policy to B_FALSE. As this might
22158 	 * affect performance for normal cases, we are not doing it.
22159 	 * Thus, set policy before starting any TCP connections.
22160 	 *
22161 	 * NOTE - We might apply policy even for a hard bound connection
22162 	 * - for which we cached policy in ip_bind - if somebody added
22163 	 * global policy after we inherited the policy in ip_bind.
22164 	 * This means that the packets that were going out in clear
22165 	 * previously would start going secure and hence get dropped
22166 	 * on the other side. To fix this, TCP attaches a dummy
22167 	 * ipsec_out and make sure that we don't apply global policy.
22168 	 */
22169 	if (ipha != NULL)
22170 		policy_present = ipss->ipsec_outbound_v4_policy_present;
22171 	else
22172 		policy_present = ipss->ipsec_outbound_v6_policy_present;
22173 	if (!policy_present)
22174 		return (mp);
22175 
22176 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
22177 	    zoneid));
22178 }
22179 
22180 ire_t *
22181 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
22182 {
22183 	ipaddr_t addr;
22184 	ire_t *save_ire;
22185 	irb_t *irb;
22186 	ill_group_t *illgrp;
22187 	int	err;
22188 
22189 	save_ire = ire;
22190 	addr = ire->ire_addr;
22191 
22192 	ASSERT(ire->ire_type == IRE_BROADCAST);
22193 
22194 	illgrp = connp->conn_outgoing_ill->ill_group;
22195 	if (illgrp == NULL) {
22196 		*conn_outgoing_ill = conn_get_held_ill(connp,
22197 		    &connp->conn_outgoing_ill, &err);
22198 		if (err == ILL_LOOKUP_FAILED) {
22199 			ire_refrele(save_ire);
22200 			return (NULL);
22201 		}
22202 		return (save_ire);
22203 	}
22204 	/*
22205 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
22206 	 * If it is part of the group, we need to send on the ire
22207 	 * that has been cleared of IRE_MARK_NORECV and that belongs
22208 	 * to this group. This is okay as IP_BOUND_IF really means
22209 	 * any ill in the group. We depend on the fact that the
22210 	 * first ire in the group is always cleared of IRE_MARK_NORECV
22211 	 * if such an ire exists. This is possible only if you have
22212 	 * at least one ill in the group that has not failed.
22213 	 *
22214 	 * First get to the ire that matches the address and group.
22215 	 *
22216 	 * We don't look for an ire with a matching zoneid because a given zone
22217 	 * won't always have broadcast ires on all ills in the group.
22218 	 */
22219 	irb = ire->ire_bucket;
22220 	rw_enter(&irb->irb_lock, RW_READER);
22221 	if (ire->ire_marks & IRE_MARK_NORECV) {
22222 		/*
22223 		 * If the current zone only has an ire broadcast for this
22224 		 * address marked NORECV, the ire we want is ahead in the
22225 		 * bucket, so we look it up deliberately ignoring the zoneid.
22226 		 */
22227 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
22228 			if (ire->ire_addr != addr)
22229 				continue;
22230 			/* skip over deleted ires */
22231 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
22232 				continue;
22233 		}
22234 	}
22235 	while (ire != NULL) {
22236 		/*
22237 		 * If a new interface is coming up, we could end up
22238 		 * seeing the loopback ire and the non-loopback ire
22239 		 * may not have been added yet. So check for ire_stq
22240 		 */
22241 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
22242 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
22243 			break;
22244 		}
22245 		ire = ire->ire_next;
22246 	}
22247 	if (ire != NULL && ire->ire_addr == addr &&
22248 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
22249 		IRE_REFHOLD(ire);
22250 		rw_exit(&irb->irb_lock);
22251 		ire_refrele(save_ire);
22252 		*conn_outgoing_ill = ire_to_ill(ire);
22253 		/*
22254 		 * Refhold the ill to make the conn_outgoing_ill
22255 		 * independent of the ire. ip_wput_ire goes in a loop
22256 		 * and may refrele the ire. Since we have an ire at this
22257 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
22258 		 */
22259 		ill_refhold(*conn_outgoing_ill);
22260 		return (ire);
22261 	}
22262 	rw_exit(&irb->irb_lock);
22263 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
22264 	/*
22265 	 * If we can't find a suitable ire, return the original ire.
22266 	 */
22267 	return (save_ire);
22268 }
22269 
22270 /*
22271  * This function does the ire_refrele of the ire passed in as the
22272  * argument. As this function looks up more ires i.e broadcast ires,
22273  * it needs to REFRELE them. Currently, for simplicity we don't
22274  * differentiate the one passed in and looked up here. We always
22275  * REFRELE.
22276  * IPQoS Notes:
22277  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
22278  * IPSec packets are done in ipsec_out_process.
22279  *
22280  */
22281 void
22282 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
22283     zoneid_t zoneid)
22284 {
22285 	ipha_t		*ipha;
22286 #define	rptr	((uchar_t *)ipha)
22287 	queue_t		*stq;
22288 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
22289 	uint32_t	v_hlen_tos_len;
22290 	uint32_t	ttl_protocol;
22291 	ipaddr_t	src;
22292 	ipaddr_t	dst;
22293 	uint32_t	cksum;
22294 	ipaddr_t	orig_src;
22295 	ire_t		*ire1;
22296 	mblk_t		*next_mp;
22297 	uint_t		hlen;
22298 	uint16_t	*up;
22299 	uint32_t	max_frag = ire->ire_max_frag;
22300 	ill_t		*ill = ire_to_ill(ire);
22301 	int		clusterwide;
22302 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
22303 	int		ipsec_len;
22304 	mblk_t		*first_mp;
22305 	ipsec_out_t	*io;
22306 	boolean_t	conn_dontroute;		/* conn value for multicast */
22307 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
22308 	boolean_t	multicast_forward;	/* Should we forward ? */
22309 	boolean_t	unspec_src;
22310 	ill_t		*conn_outgoing_ill = NULL;
22311 	ill_t		*ire_ill;
22312 	ill_t		*ire1_ill;
22313 	ill_t		*out_ill;
22314 	uint32_t 	ill_index = 0;
22315 	boolean_t	multirt_send = B_FALSE;
22316 	int		err;
22317 	ipxmit_state_t	pktxmit_state;
22318 	ip_stack_t	*ipst = ire->ire_ipst;
22319 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
22320 
22321 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
22322 	    "ip_wput_ire_start: q %p", q);
22323 
22324 	multicast_forward = B_FALSE;
22325 	unspec_src = (connp != NULL && connp->conn_unspec_src);
22326 
22327 	if (ire->ire_flags & RTF_MULTIRT) {
22328 		/*
22329 		 * Multirouting case. The bucket where ire is stored
22330 		 * probably holds other RTF_MULTIRT flagged ire
22331 		 * to the destination. In this call to ip_wput_ire,
22332 		 * we attempt to send the packet through all
22333 		 * those ires. Thus, we first ensure that ire is the
22334 		 * first RTF_MULTIRT ire in the bucket,
22335 		 * before walking the ire list.
22336 		 */
22337 		ire_t *first_ire;
22338 		irb_t *irb = ire->ire_bucket;
22339 		ASSERT(irb != NULL);
22340 
22341 		/* Make sure we do not omit any multiroute ire. */
22342 		IRB_REFHOLD(irb);
22343 		for (first_ire = irb->irb_ire;
22344 		    first_ire != NULL;
22345 		    first_ire = first_ire->ire_next) {
22346 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22347 			    (first_ire->ire_addr == ire->ire_addr) &&
22348 			    !(first_ire->ire_marks &
22349 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
22350 				break;
22351 			}
22352 		}
22353 
22354 		if ((first_ire != NULL) && (first_ire != ire)) {
22355 			IRE_REFHOLD(first_ire);
22356 			ire_refrele(ire);
22357 			ire = first_ire;
22358 			ill = ire_to_ill(ire);
22359 		}
22360 		IRB_REFRELE(irb);
22361 	}
22362 
22363 	/*
22364 	 * conn_outgoing_ill is used only in the broadcast loop.
22365 	 * for performance we don't grab the mutexs in the fastpath
22366 	 */
22367 	if ((connp != NULL) &&
22368 	    (connp->conn_xmit_if_ill == NULL) &&
22369 	    (ire->ire_type == IRE_BROADCAST) &&
22370 	    ((connp->conn_nofailover_ill != NULL) ||
22371 	    (connp->conn_outgoing_ill != NULL))) {
22372 		/*
22373 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
22374 		 * option. So, see if this endpoint is bound to a
22375 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
22376 		 * that if the interface is failed, we will still send
22377 		 * the packet on the same ill which is what we want.
22378 		 */
22379 		conn_outgoing_ill = conn_get_held_ill(connp,
22380 		    &connp->conn_nofailover_ill, &err);
22381 		if (err == ILL_LOOKUP_FAILED) {
22382 			ire_refrele(ire);
22383 			freemsg(mp);
22384 			return;
22385 		}
22386 		if (conn_outgoing_ill == NULL) {
22387 			/*
22388 			 * Choose a good ill in the group to send the
22389 			 * packets on.
22390 			 */
22391 			ire = conn_set_outgoing_ill(connp, ire,
22392 			    &conn_outgoing_ill);
22393 			if (ire == NULL) {
22394 				freemsg(mp);
22395 				return;
22396 			}
22397 		}
22398 	}
22399 
22400 	if (mp->b_datap->db_type != M_CTL) {
22401 		ipha = (ipha_t *)mp->b_rptr;
22402 	} else {
22403 		io = (ipsec_out_t *)mp->b_rptr;
22404 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22405 		ASSERT(zoneid == io->ipsec_out_zoneid);
22406 		ASSERT(zoneid != ALL_ZONES);
22407 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22408 		dst = ipha->ipha_dst;
22409 		/*
22410 		 * For the multicast case, ipsec_out carries conn_dontroute and
22411 		 * conn_multicast_loop as conn may not be available here. We
22412 		 * need this for multicast loopback and forwarding which is done
22413 		 * later in the code.
22414 		 */
22415 		if (CLASSD(dst)) {
22416 			conn_dontroute = io->ipsec_out_dontroute;
22417 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22418 			/*
22419 			 * If conn_dontroute is not set or conn_multicast_loop
22420 			 * is set, we need to do forwarding/loopback. For
22421 			 * datagrams from ip_wput_multicast, conn_dontroute is
22422 			 * set to B_TRUE and conn_multicast_loop is set to
22423 			 * B_FALSE so that we neither do forwarding nor
22424 			 * loopback.
22425 			 */
22426 			if (!conn_dontroute || conn_multicast_loop)
22427 				multicast_forward = B_TRUE;
22428 		}
22429 	}
22430 
22431 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22432 	    ire->ire_zoneid != ALL_ZONES) {
22433 		/*
22434 		 * When a zone sends a packet to another zone, we try to deliver
22435 		 * the packet under the same conditions as if the destination
22436 		 * was a real node on the network. To do so, we look for a
22437 		 * matching route in the forwarding table.
22438 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22439 		 * ip_newroute() does.
22440 		 * Note that IRE_LOCAL are special, since they are used
22441 		 * when the zoneid doesn't match in some cases. This means that
22442 		 * we need to handle ipha_src differently since ire_src_addr
22443 		 * belongs to the receiving zone instead of the sending zone.
22444 		 * When ip_restrict_interzone_loopback is set, then
22445 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22446 		 * for loopback between zones when the logical "Ethernet" would
22447 		 * have looped them back.
22448 		 */
22449 		ire_t *src_ire;
22450 
22451 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22452 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22453 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22454 		if (src_ire != NULL &&
22455 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22456 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22457 		    ire_local_same_ill_group(ire, src_ire))) {
22458 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22459 				ipha->ipha_src = src_ire->ire_src_addr;
22460 			ire_refrele(src_ire);
22461 		} else {
22462 			ire_refrele(ire);
22463 			if (conn_outgoing_ill != NULL)
22464 				ill_refrele(conn_outgoing_ill);
22465 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22466 			if (src_ire != NULL) {
22467 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22468 					ire_refrele(src_ire);
22469 					freemsg(mp);
22470 					return;
22471 				}
22472 				ire_refrele(src_ire);
22473 			}
22474 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22475 				/* Failed */
22476 				freemsg(mp);
22477 				return;
22478 			}
22479 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22480 			    ipst);
22481 			return;
22482 		}
22483 	}
22484 
22485 	if (mp->b_datap->db_type == M_CTL ||
22486 	    ipss->ipsec_outbound_v4_policy_present) {
22487 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22488 		    unspec_src, zoneid);
22489 		if (mp == NULL) {
22490 			ire_refrele(ire);
22491 			if (conn_outgoing_ill != NULL)
22492 				ill_refrele(conn_outgoing_ill);
22493 			return;
22494 		}
22495 	}
22496 
22497 	first_mp = mp;
22498 	ipsec_len = 0;
22499 
22500 	if (first_mp->b_datap->db_type == M_CTL) {
22501 		io = (ipsec_out_t *)first_mp->b_rptr;
22502 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22503 		mp = first_mp->b_cont;
22504 		ipsec_len = ipsec_out_extra_length(first_mp);
22505 		ASSERT(ipsec_len >= 0);
22506 		/* We already picked up the zoneid from the M_CTL above */
22507 		ASSERT(zoneid == io->ipsec_out_zoneid);
22508 		ASSERT(zoneid != ALL_ZONES);
22509 
22510 		/*
22511 		 * Drop M_CTL here if IPsec processing is not needed.
22512 		 * (Non-IPsec use of M_CTL extracted any information it
22513 		 * needed above).
22514 		 */
22515 		if (ipsec_len == 0) {
22516 			freeb(first_mp);
22517 			first_mp = mp;
22518 		}
22519 	}
22520 
22521 	/*
22522 	 * Fast path for ip_wput_ire
22523 	 */
22524 
22525 	ipha = (ipha_t *)mp->b_rptr;
22526 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22527 	dst = ipha->ipha_dst;
22528 
22529 	/*
22530 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22531 	 * if the socket is a SOCK_RAW type. The transport checksum should
22532 	 * be provided in the pre-built packet, so we don't need to compute it.
22533 	 * Also, other application set flags, like DF, should not be altered.
22534 	 * Other transport MUST pass down zero.
22535 	 */
22536 	ip_hdr_included = ipha->ipha_ident;
22537 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22538 
22539 	if (CLASSD(dst)) {
22540 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22541 		    ntohl(dst),
22542 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22543 		    ntohl(ire->ire_addr)));
22544 	}
22545 
22546 /* Macros to extract header fields from data already in registers */
22547 #ifdef	_BIG_ENDIAN
22548 #define	V_HLEN	(v_hlen_tos_len >> 24)
22549 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22550 #define	PROTO	(ttl_protocol & 0xFF)
22551 #else
22552 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22553 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22554 #define	PROTO	(ttl_protocol >> 8)
22555 #endif
22556 
22557 
22558 	orig_src = src = ipha->ipha_src;
22559 	/* (The loop back to "another" is explained down below.) */
22560 another:;
22561 	/*
22562 	 * Assign an ident value for this packet.  We assign idents on
22563 	 * a per destination basis out of the IRE.  There could be
22564 	 * other threads targeting the same destination, so we have to
22565 	 * arrange for a atomic increment.  Note that we use a 32-bit
22566 	 * atomic add because it has better performance than its
22567 	 * 16-bit sibling.
22568 	 *
22569 	 * If running in cluster mode and if the source address
22570 	 * belongs to a replicated service then vector through
22571 	 * cl_inet_ipident vector to allocate ip identifier
22572 	 * NOTE: This is a contract private interface with the
22573 	 * clustering group.
22574 	 */
22575 	clusterwide = 0;
22576 	if (cl_inet_ipident) {
22577 		ASSERT(cl_inet_isclusterwide);
22578 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
22579 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
22580 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
22581 			    AF_INET, (uint8_t *)(uintptr_t)src,
22582 			    (uint8_t *)(uintptr_t)dst);
22583 			clusterwide = 1;
22584 		}
22585 	}
22586 	if (!clusterwide) {
22587 		ipha->ipha_ident =
22588 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22589 	}
22590 
22591 #ifndef _BIG_ENDIAN
22592 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22593 #endif
22594 
22595 	/*
22596 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22597 	 * This is needed to obey conn_unspec_src when packets go through
22598 	 * ip_newroute + arp.
22599 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22600 	 */
22601 	if (src == INADDR_ANY && !unspec_src) {
22602 		/*
22603 		 * Assign the appropriate source address from the IRE if none
22604 		 * was specified.
22605 		 */
22606 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22607 
22608 		/*
22609 		 * With IP multipathing, broadcast packets are sent on the ire
22610 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
22611 		 * the group. However, this ire might not be in the same zone so
22612 		 * we can't always use its source address. We look for a
22613 		 * broadcast ire in the same group and in the right zone.
22614 		 */
22615 		if (ire->ire_type == IRE_BROADCAST &&
22616 		    ire->ire_zoneid != zoneid) {
22617 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
22618 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
22619 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
22620 			if (src_ire != NULL) {
22621 				src = src_ire->ire_src_addr;
22622 				ire_refrele(src_ire);
22623 			} else {
22624 				ire_refrele(ire);
22625 				if (conn_outgoing_ill != NULL)
22626 					ill_refrele(conn_outgoing_ill);
22627 				freemsg(first_mp);
22628 				if (ill != NULL) {
22629 					BUMP_MIB(ill->ill_ip_mib,
22630 					    ipIfStatsOutDiscards);
22631 				} else {
22632 					BUMP_MIB(&ipst->ips_ip_mib,
22633 					    ipIfStatsOutDiscards);
22634 				}
22635 				return;
22636 			}
22637 		} else {
22638 			src = ire->ire_src_addr;
22639 		}
22640 
22641 		if (connp == NULL) {
22642 			ip1dbg(("ip_wput_ire: no connp and no src "
22643 			    "address for dst 0x%x, using src 0x%x\n",
22644 			    ntohl(dst),
22645 			    ntohl(src)));
22646 		}
22647 		ipha->ipha_src = src;
22648 	}
22649 	stq = ire->ire_stq;
22650 
22651 	/*
22652 	 * We only allow ire chains for broadcasts since there will
22653 	 * be multiple IRE_CACHE entries for the same multicast
22654 	 * address (one per ipif).
22655 	 */
22656 	next_mp = NULL;
22657 
22658 	/* broadcast packet */
22659 	if (ire->ire_type == IRE_BROADCAST)
22660 		goto broadcast;
22661 
22662 	/* loopback ? */
22663 	if (stq == NULL)
22664 		goto nullstq;
22665 
22666 	/* The ill_index for outbound ILL */
22667 	ill_index = Q_TO_INDEX(stq);
22668 
22669 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22670 	ttl_protocol = ((uint16_t *)ipha)[4];
22671 
22672 	/* pseudo checksum (do it in parts for IP header checksum) */
22673 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22674 
22675 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22676 		queue_t *dev_q = stq->q_next;
22677 
22678 		/* flow controlled */
22679 		if ((dev_q->q_next || dev_q->q_first) &&
22680 		    !canput(dev_q))
22681 			goto blocked;
22682 		if ((PROTO == IPPROTO_UDP) &&
22683 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22684 			hlen = (V_HLEN & 0xF) << 2;
22685 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22686 			if (*up != 0) {
22687 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22688 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22689 				/* Software checksum? */
22690 				if (DB_CKSUMFLAGS(mp) == 0) {
22691 					IP_STAT(ipst, ip_out_sw_cksum);
22692 					IP_STAT_UPDATE(ipst,
22693 					    ip_udp_out_sw_cksum_bytes,
22694 					    LENGTH - hlen);
22695 				}
22696 			}
22697 		}
22698 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22699 		hlen = (V_HLEN & 0xF) << 2;
22700 		if (PROTO == IPPROTO_TCP) {
22701 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22702 			/*
22703 			 * The packet header is processed once and for all, even
22704 			 * in the multirouting case. We disable hardware
22705 			 * checksum if the packet is multirouted, as it will be
22706 			 * replicated via several interfaces, and not all of
22707 			 * them may have this capability.
22708 			 */
22709 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22710 			    LENGTH, max_frag, ipsec_len, cksum);
22711 			/* Software checksum? */
22712 			if (DB_CKSUMFLAGS(mp) == 0) {
22713 				IP_STAT(ipst, ip_out_sw_cksum);
22714 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22715 				    LENGTH - hlen);
22716 			}
22717 		} else {
22718 			sctp_hdr_t	*sctph;
22719 
22720 			ASSERT(PROTO == IPPROTO_SCTP);
22721 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22722 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22723 			/*
22724 			 * Zero out the checksum field to ensure proper
22725 			 * checksum calculation.
22726 			 */
22727 			sctph->sh_chksum = 0;
22728 #ifdef	DEBUG
22729 			if (!skip_sctp_cksum)
22730 #endif
22731 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22732 		}
22733 	}
22734 
22735 	/*
22736 	 * If this is a multicast packet and originated from ip_wput
22737 	 * we need to do loopback and forwarding checks. If it comes
22738 	 * from ip_wput_multicast, we SHOULD not do this.
22739 	 */
22740 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22741 
22742 	/* checksum */
22743 	cksum += ttl_protocol;
22744 
22745 	/* fragment the packet */
22746 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22747 		goto fragmentit;
22748 	/*
22749 	 * Don't use frag_flag if packet is pre-built or source
22750 	 * routed or if multicast (since multicast packets do
22751 	 * not solicit ICMP "packet too big" messages).
22752 	 */
22753 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22754 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22755 	    !ip_source_route_included(ipha)) &&
22756 	    !CLASSD(ipha->ipha_dst))
22757 		ipha->ipha_fragment_offset_and_flags |=
22758 		    htons(ire->ire_frag_flag);
22759 
22760 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22761 		/* calculate IP header checksum */
22762 		cksum += ipha->ipha_ident;
22763 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22764 		cksum += ipha->ipha_fragment_offset_and_flags;
22765 
22766 		/* IP options present */
22767 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22768 		if (hlen)
22769 			goto checksumoptions;
22770 
22771 		/* calculate hdr checksum */
22772 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22773 		cksum = ~(cksum + (cksum >> 16));
22774 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22775 	}
22776 	if (ipsec_len != 0) {
22777 		/*
22778 		 * We will do the rest of the processing after
22779 		 * we come back from IPSEC in ip_wput_ipsec_out().
22780 		 */
22781 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22782 
22783 		io = (ipsec_out_t *)first_mp->b_rptr;
22784 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
22785 		    ill_phyint->phyint_ifindex;
22786 
22787 		ipsec_out_process(q, first_mp, ire, ill_index);
22788 		ire_refrele(ire);
22789 		if (conn_outgoing_ill != NULL)
22790 			ill_refrele(conn_outgoing_ill);
22791 		return;
22792 	}
22793 
22794 	/*
22795 	 * In most cases, the emission loop below is entered only
22796 	 * once. Only in the case where the ire holds the
22797 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22798 	 * flagged ires in the bucket, and send the packet
22799 	 * through all crossed RTF_MULTIRT routes.
22800 	 */
22801 	if (ire->ire_flags & RTF_MULTIRT) {
22802 		multirt_send = B_TRUE;
22803 	}
22804 	do {
22805 		if (multirt_send) {
22806 			irb_t *irb;
22807 			/*
22808 			 * We are in a multiple send case, need to get
22809 			 * the next ire and make a duplicate of the packet.
22810 			 * ire1 holds here the next ire to process in the
22811 			 * bucket. If multirouting is expected,
22812 			 * any non-RTF_MULTIRT ire that has the
22813 			 * right destination address is ignored.
22814 			 */
22815 			irb = ire->ire_bucket;
22816 			ASSERT(irb != NULL);
22817 
22818 			IRB_REFHOLD(irb);
22819 			for (ire1 = ire->ire_next;
22820 			    ire1 != NULL;
22821 			    ire1 = ire1->ire_next) {
22822 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22823 					continue;
22824 				if (ire1->ire_addr != ire->ire_addr)
22825 					continue;
22826 				if (ire1->ire_marks &
22827 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
22828 					continue;
22829 
22830 				/* Got one */
22831 				IRE_REFHOLD(ire1);
22832 				break;
22833 			}
22834 			IRB_REFRELE(irb);
22835 
22836 			if (ire1 != NULL) {
22837 				next_mp = copyb(mp);
22838 				if ((next_mp == NULL) ||
22839 				    ((mp->b_cont != NULL) &&
22840 				    ((next_mp->b_cont =
22841 				    dupmsg(mp->b_cont)) == NULL))) {
22842 					freemsg(next_mp);
22843 					next_mp = NULL;
22844 					ire_refrele(ire1);
22845 					ire1 = NULL;
22846 				}
22847 			}
22848 
22849 			/* Last multiroute ire; don't loop anymore. */
22850 			if (ire1 == NULL) {
22851 				multirt_send = B_FALSE;
22852 			}
22853 		}
22854 
22855 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22856 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22857 		    mblk_t *, mp);
22858 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22859 		    ipst->ips_ipv4firewall_physical_out,
22860 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, ipst);
22861 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22862 		if (mp == NULL)
22863 			goto release_ire_and_ill;
22864 
22865 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22866 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22867 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE);
22868 		if ((pktxmit_state == SEND_FAILED) ||
22869 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22870 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22871 			    "- packet dropped\n"));
22872 release_ire_and_ill:
22873 			ire_refrele(ire);
22874 			if (next_mp != NULL) {
22875 				freemsg(next_mp);
22876 				ire_refrele(ire1);
22877 			}
22878 			if (conn_outgoing_ill != NULL)
22879 				ill_refrele(conn_outgoing_ill);
22880 			return;
22881 		}
22882 
22883 		if (CLASSD(dst)) {
22884 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22885 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22886 			    LENGTH);
22887 		}
22888 
22889 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22890 		    "ip_wput_ire_end: q %p (%S)",
22891 		    q, "last copy out");
22892 		IRE_REFRELE(ire);
22893 
22894 		if (multirt_send) {
22895 			ASSERT(ire1);
22896 			/*
22897 			 * Proceed with the next RTF_MULTIRT ire,
22898 			 * Also set up the send-to queue accordingly.
22899 			 */
22900 			ire = ire1;
22901 			ire1 = NULL;
22902 			stq = ire->ire_stq;
22903 			mp = next_mp;
22904 			next_mp = NULL;
22905 			ipha = (ipha_t *)mp->b_rptr;
22906 			ill_index = Q_TO_INDEX(stq);
22907 			ill = (ill_t *)stq->q_ptr;
22908 		}
22909 	} while (multirt_send);
22910 	if (conn_outgoing_ill != NULL)
22911 		ill_refrele(conn_outgoing_ill);
22912 	return;
22913 
22914 	/*
22915 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22916 	 */
22917 broadcast:
22918 	{
22919 		/*
22920 		 * Avoid broadcast storms by setting the ttl to 1
22921 		 * for broadcasts. This parameter can be set
22922 		 * via ndd, so make sure that for the SO_DONTROUTE
22923 		 * case that ipha_ttl is always set to 1.
22924 		 * In the event that we are replying to incoming
22925 		 * ICMP packets, conn could be NULL.
22926 		 */
22927 		if ((connp != NULL) && connp->conn_dontroute)
22928 			ipha->ipha_ttl = 1;
22929 		else
22930 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22931 
22932 		/*
22933 		 * Note that we are not doing a IRB_REFHOLD here.
22934 		 * Actually we don't care if the list changes i.e
22935 		 * if somebody deletes an IRE from the list while
22936 		 * we drop the lock, the next time we come around
22937 		 * ire_next will be NULL and hence we won't send
22938 		 * out multiple copies which is fine.
22939 		 */
22940 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22941 		ire1 = ire->ire_next;
22942 		if (conn_outgoing_ill != NULL) {
22943 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22944 				ASSERT(ire1 == ire->ire_next);
22945 				if (ire1 != NULL && ire1->ire_addr == dst) {
22946 					ire_refrele(ire);
22947 					ire = ire1;
22948 					IRE_REFHOLD(ire);
22949 					ire1 = ire->ire_next;
22950 					continue;
22951 				}
22952 				rw_exit(&ire->ire_bucket->irb_lock);
22953 				/* Did not find a matching ill */
22954 				ip1dbg(("ip_wput_ire: broadcast with no "
22955 				    "matching IP_BOUND_IF ill %s\n",
22956 				    conn_outgoing_ill->ill_name));
22957 				freemsg(first_mp);
22958 				if (ire != NULL)
22959 					ire_refrele(ire);
22960 				ill_refrele(conn_outgoing_ill);
22961 				return;
22962 			}
22963 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22964 			/*
22965 			 * If the next IRE has the same address and is not one
22966 			 * of the two copies that we need to send, try to see
22967 			 * whether this copy should be sent at all. This
22968 			 * assumes that we insert loopbacks first and then
22969 			 * non-loopbacks. This is acheived by inserting the
22970 			 * loopback always before non-loopback.
22971 			 * This is used to send a single copy of a broadcast
22972 			 * packet out all physical interfaces that have an
22973 			 * matching IRE_BROADCAST while also looping
22974 			 * back one copy (to ip_wput_local) for each
22975 			 * matching physical interface. However, we avoid
22976 			 * sending packets out different logical that match by
22977 			 * having ipif_up/ipif_down supress duplicate
22978 			 * IRE_BROADCASTS.
22979 			 *
22980 			 * This feature is currently used to get broadcasts
22981 			 * sent to multiple interfaces, when the broadcast
22982 			 * address being used applies to multiple interfaces.
22983 			 * For example, a whole net broadcast will be
22984 			 * replicated on every connected subnet of
22985 			 * the target net.
22986 			 *
22987 			 * Each zone has its own set of IRE_BROADCASTs, so that
22988 			 * we're able to distribute inbound packets to multiple
22989 			 * zones who share a broadcast address. We avoid looping
22990 			 * back outbound packets in different zones but on the
22991 			 * same ill, as the application would see duplicates.
22992 			 *
22993 			 * If the interfaces are part of the same group,
22994 			 * we would want to send only one copy out for
22995 			 * whole group.
22996 			 *
22997 			 * This logic assumes that ire_add_v4() groups the
22998 			 * IRE_BROADCAST entries so that those with the same
22999 			 * ire_addr and ill_group are kept together.
23000 			 */
23001 			ire_ill = ire->ire_ipif->ipif_ill;
23002 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
23003 				if (ire_ill->ill_group != NULL &&
23004 				    (ire->ire_marks & IRE_MARK_NORECV)) {
23005 					/*
23006 					 * If the current zone only has an ire
23007 					 * broadcast for this address marked
23008 					 * NORECV, the ire we want is ahead in
23009 					 * the bucket, so we look it up
23010 					 * deliberately ignoring the zoneid.
23011 					 */
23012 					for (ire1 = ire->ire_bucket->irb_ire;
23013 					    ire1 != NULL;
23014 					    ire1 = ire1->ire_next) {
23015 						ire1_ill =
23016 						    ire1->ire_ipif->ipif_ill;
23017 						if (ire1->ire_addr != dst)
23018 							continue;
23019 						/* skip over the current ire */
23020 						if (ire1 == ire)
23021 							continue;
23022 						/* skip over deleted ires */
23023 						if (ire1->ire_marks &
23024 						    IRE_MARK_CONDEMNED)
23025 							continue;
23026 						/*
23027 						 * non-loopback ire in our
23028 						 * group: use it for the next
23029 						 * pass in the loop
23030 						 */
23031 						if (ire1->ire_stq != NULL &&
23032 						    ire1_ill->ill_group ==
23033 						    ire_ill->ill_group)
23034 							break;
23035 					}
23036 				}
23037 			} else {
23038 				while (ire1 != NULL && ire1->ire_addr == dst) {
23039 					ire1_ill = ire1->ire_ipif->ipif_ill;
23040 					/*
23041 					 * We can have two broadcast ires on the
23042 					 * same ill in different zones; here
23043 					 * we'll send a copy of the packet on
23044 					 * each ill and the fanout code will
23045 					 * call conn_wantpacket() to check that
23046 					 * the zone has the broadcast address
23047 					 * configured on the ill. If the two
23048 					 * ires are in the same group we only
23049 					 * send one copy up.
23050 					 */
23051 					if (ire1_ill != ire_ill &&
23052 					    (ire1_ill->ill_group == NULL ||
23053 					    ire_ill->ill_group == NULL ||
23054 					    ire1_ill->ill_group !=
23055 					    ire_ill->ill_group)) {
23056 						break;
23057 					}
23058 					ire1 = ire1->ire_next;
23059 				}
23060 			}
23061 		}
23062 		ASSERT(multirt_send == B_FALSE);
23063 		if (ire1 != NULL && ire1->ire_addr == dst) {
23064 			if ((ire->ire_flags & RTF_MULTIRT) &&
23065 			    (ire1->ire_flags & RTF_MULTIRT)) {
23066 				/*
23067 				 * We are in the multirouting case.
23068 				 * The message must be sent at least
23069 				 * on both ires. These ires have been
23070 				 * inserted AFTER the standard ones
23071 				 * in ip_rt_add(). There are thus no
23072 				 * other ire entries for the destination
23073 				 * address in the rest of the bucket
23074 				 * that do not have the RTF_MULTIRT
23075 				 * flag. We don't process a copy
23076 				 * of the message here. This will be
23077 				 * done in the final sending loop.
23078 				 */
23079 				multirt_send = B_TRUE;
23080 			} else {
23081 				next_mp = ip_copymsg(first_mp);
23082 				if (next_mp != NULL)
23083 					IRE_REFHOLD(ire1);
23084 			}
23085 		}
23086 		rw_exit(&ire->ire_bucket->irb_lock);
23087 	}
23088 
23089 	if (stq) {
23090 		/*
23091 		 * A non-NULL send-to queue means this packet is going
23092 		 * out of this machine.
23093 		 */
23094 		out_ill = (ill_t *)stq->q_ptr;
23095 
23096 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
23097 		ttl_protocol = ((uint16_t *)ipha)[4];
23098 		/*
23099 		 * We accumulate the pseudo header checksum in cksum.
23100 		 * This is pretty hairy code, so watch close.  One
23101 		 * thing to keep in mind is that UDP and TCP have
23102 		 * stored their respective datagram lengths in their
23103 		 * checksum fields.  This lines things up real nice.
23104 		 */
23105 		cksum = (dst >> 16) + (dst & 0xFFFF) +
23106 		    (src >> 16) + (src & 0xFFFF);
23107 		/*
23108 		 * We assume the udp checksum field contains the
23109 		 * length, so to compute the pseudo header checksum,
23110 		 * all we need is the protocol number and src/dst.
23111 		 */
23112 		/* Provide the checksums for UDP and TCP. */
23113 		if ((PROTO == IPPROTO_TCP) &&
23114 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
23115 			/* hlen gets the number of uchar_ts in the IP header */
23116 			hlen = (V_HLEN & 0xF) << 2;
23117 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
23118 			IP_STAT(ipst, ip_out_sw_cksum);
23119 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
23120 			    LENGTH - hlen);
23121 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
23122 		} else if (PROTO == IPPROTO_SCTP &&
23123 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
23124 			sctp_hdr_t	*sctph;
23125 
23126 			hlen = (V_HLEN & 0xF) << 2;
23127 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
23128 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
23129 			sctph->sh_chksum = 0;
23130 #ifdef	DEBUG
23131 			if (!skip_sctp_cksum)
23132 #endif
23133 				sctph->sh_chksum = sctp_cksum(mp, hlen);
23134 		} else {
23135 			queue_t *dev_q = stq->q_next;
23136 
23137 			if ((dev_q->q_next || dev_q->q_first) &&
23138 			    !canput(dev_q)) {
23139 blocked:
23140 				ipha->ipha_ident = ip_hdr_included;
23141 				/*
23142 				 * If we don't have a conn to apply
23143 				 * backpressure, free the message.
23144 				 * In the ire_send path, we don't know
23145 				 * the position to requeue the packet. Rather
23146 				 * than reorder packets, we just drop this
23147 				 * packet.
23148 				 */
23149 				if (ipst->ips_ip_output_queue &&
23150 				    connp != NULL &&
23151 				    caller != IRE_SEND) {
23152 					if (caller == IP_WSRV) {
23153 						connp->conn_did_putbq = 1;
23154 						(void) putbq(connp->conn_wq,
23155 						    first_mp);
23156 						conn_drain_insert(connp);
23157 						/*
23158 						 * This is the service thread,
23159 						 * and the queue is already
23160 						 * noenabled. The check for
23161 						 * canput and the putbq is not
23162 						 * atomic. So we need to check
23163 						 * again.
23164 						 */
23165 						if (canput(stq->q_next))
23166 							connp->conn_did_putbq
23167 							    = 0;
23168 						IP_STAT(ipst, ip_conn_flputbq);
23169 					} else {
23170 						/*
23171 						 * We are not the service proc.
23172 						 * ip_wsrv will be scheduled or
23173 						 * is already running.
23174 						 */
23175 						(void) putq(connp->conn_wq,
23176 						    first_mp);
23177 					}
23178 				} else {
23179 					out_ill = (ill_t *)stq->q_ptr;
23180 					BUMP_MIB(out_ill->ill_ip_mib,
23181 					    ipIfStatsOutDiscards);
23182 					freemsg(first_mp);
23183 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23184 					    "ip_wput_ire_end: q %p (%S)",
23185 					    q, "discard");
23186 				}
23187 				ire_refrele(ire);
23188 				if (next_mp) {
23189 					ire_refrele(ire1);
23190 					freemsg(next_mp);
23191 				}
23192 				if (conn_outgoing_ill != NULL)
23193 					ill_refrele(conn_outgoing_ill);
23194 				return;
23195 			}
23196 			if ((PROTO == IPPROTO_UDP) &&
23197 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
23198 				/*
23199 				 * hlen gets the number of uchar_ts in the
23200 				 * IP header
23201 				 */
23202 				hlen = (V_HLEN & 0xF) << 2;
23203 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
23204 				max_frag = ire->ire_max_frag;
23205 				if (*up != 0) {
23206 					IP_CKSUM_XMIT(ire_ill, ire, mp, ipha,
23207 					    up, PROTO, hlen, LENGTH, max_frag,
23208 					    ipsec_len, cksum);
23209 					/* Software checksum? */
23210 					if (DB_CKSUMFLAGS(mp) == 0) {
23211 						IP_STAT(ipst, ip_out_sw_cksum);
23212 						IP_STAT_UPDATE(ipst,
23213 						    ip_udp_out_sw_cksum_bytes,
23214 						    LENGTH - hlen);
23215 					}
23216 				}
23217 			}
23218 		}
23219 		/*
23220 		 * Need to do this even when fragmenting. The local
23221 		 * loopback can be done without computing checksums
23222 		 * but forwarding out other interface must be done
23223 		 * after the IP checksum (and ULP checksums) have been
23224 		 * computed.
23225 		 *
23226 		 * NOTE : multicast_forward is set only if this packet
23227 		 * originated from ip_wput. For packets originating from
23228 		 * ip_wput_multicast, it is not set.
23229 		 */
23230 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
23231 multi_loopback:
23232 			ip2dbg(("ip_wput: multicast, loop %d\n",
23233 			    conn_multicast_loop));
23234 
23235 			/*  Forget header checksum offload */
23236 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
23237 
23238 			/*
23239 			 * Local loopback of multicasts?  Check the
23240 			 * ill.
23241 			 *
23242 			 * Note that the loopback function will not come
23243 			 * in through ip_rput - it will only do the
23244 			 * client fanout thus we need to do an mforward
23245 			 * as well.  The is different from the BSD
23246 			 * logic.
23247 			 */
23248 			if (ill != NULL) {
23249 				ilm_t	*ilm;
23250 
23251 				ILM_WALKER_HOLD(ill);
23252 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
23253 				    ALL_ZONES);
23254 				ILM_WALKER_RELE(ill);
23255 				if (ilm != NULL) {
23256 					/*
23257 					 * Pass along the virtual output q.
23258 					 * ip_wput_local() will distribute the
23259 					 * packet to all the matching zones,
23260 					 * except the sending zone when
23261 					 * IP_MULTICAST_LOOP is false.
23262 					 */
23263 					ip_multicast_loopback(q, ill, first_mp,
23264 					    conn_multicast_loop ? 0 :
23265 					    IP_FF_NO_MCAST_LOOP, zoneid);
23266 				}
23267 			}
23268 			if (ipha->ipha_ttl == 0) {
23269 				/*
23270 				 * 0 => only to this host i.e. we are
23271 				 * done. We are also done if this was the
23272 				 * loopback interface since it is sufficient
23273 				 * to loopback one copy of a multicast packet.
23274 				 */
23275 				freemsg(first_mp);
23276 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23277 				    "ip_wput_ire_end: q %p (%S)",
23278 				    q, "loopback");
23279 				ire_refrele(ire);
23280 				if (conn_outgoing_ill != NULL)
23281 					ill_refrele(conn_outgoing_ill);
23282 				return;
23283 			}
23284 			/*
23285 			 * ILLF_MULTICAST is checked in ip_newroute
23286 			 * i.e. we don't need to check it here since
23287 			 * all IRE_CACHEs come from ip_newroute.
23288 			 * For multicast traffic, SO_DONTROUTE is interpreted
23289 			 * to mean only send the packet out the interface
23290 			 * (optionally specified with IP_MULTICAST_IF)
23291 			 * and do not forward it out additional interfaces.
23292 			 * RSVP and the rsvp daemon is an example of a
23293 			 * protocol and user level process that
23294 			 * handles it's own routing. Hence, it uses the
23295 			 * SO_DONTROUTE option to accomplish this.
23296 			 */
23297 
23298 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
23299 			    ill != NULL) {
23300 				/* Unconditionally redo the checksum */
23301 				ipha->ipha_hdr_checksum = 0;
23302 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23303 
23304 				/*
23305 				 * If this needs to go out secure, we need
23306 				 * to wait till we finish the IPSEC
23307 				 * processing.
23308 				 */
23309 				if (ipsec_len == 0 &&
23310 				    ip_mforward(ill, ipha, mp)) {
23311 					freemsg(first_mp);
23312 					ip1dbg(("ip_wput: mforward failed\n"));
23313 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23314 					    "ip_wput_ire_end: q %p (%S)",
23315 					    q, "mforward failed");
23316 					ire_refrele(ire);
23317 					if (conn_outgoing_ill != NULL)
23318 						ill_refrele(conn_outgoing_ill);
23319 					return;
23320 				}
23321 			}
23322 		}
23323 		max_frag = ire->ire_max_frag;
23324 		cksum += ttl_protocol;
23325 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
23326 			/* No fragmentation required for this one. */
23327 			/*
23328 			 * Don't use frag_flag if packet is pre-built or source
23329 			 * routed or if multicast (since multicast packets do
23330 			 * not solicit ICMP "packet too big" messages).
23331 			 */
23332 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
23333 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
23334 			    !ip_source_route_included(ipha)) &&
23335 			    !CLASSD(ipha->ipha_dst))
23336 				ipha->ipha_fragment_offset_and_flags |=
23337 				    htons(ire->ire_frag_flag);
23338 
23339 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
23340 				/* Complete the IP header checksum. */
23341 				cksum += ipha->ipha_ident;
23342 				cksum += (v_hlen_tos_len >> 16)+
23343 				    (v_hlen_tos_len & 0xFFFF);
23344 				cksum += ipha->ipha_fragment_offset_and_flags;
23345 				hlen = (V_HLEN & 0xF) -
23346 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
23347 				if (hlen) {
23348 checksumoptions:
23349 					/*
23350 					 * Account for the IP Options in the IP
23351 					 * header checksum.
23352 					 */
23353 					up = (uint16_t *)(rptr+
23354 					    IP_SIMPLE_HDR_LENGTH);
23355 					do {
23356 						cksum += up[0];
23357 						cksum += up[1];
23358 						up += 2;
23359 					} while (--hlen);
23360 				}
23361 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
23362 				cksum = ~(cksum + (cksum >> 16));
23363 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
23364 			}
23365 			if (ipsec_len != 0) {
23366 				ipsec_out_process(q, first_mp, ire, ill_index);
23367 				if (!next_mp) {
23368 					ire_refrele(ire);
23369 					if (conn_outgoing_ill != NULL)
23370 						ill_refrele(conn_outgoing_ill);
23371 					return;
23372 				}
23373 				goto next;
23374 			}
23375 
23376 			/*
23377 			 * multirt_send has already been handled
23378 			 * for broadcast, but not yet for multicast
23379 			 * or IP options.
23380 			 */
23381 			if (next_mp == NULL) {
23382 				if (ire->ire_flags & RTF_MULTIRT) {
23383 					multirt_send = B_TRUE;
23384 				}
23385 			}
23386 
23387 			/*
23388 			 * In most cases, the emission loop below is
23389 			 * entered only once. Only in the case where
23390 			 * the ire holds the RTF_MULTIRT flag, do we loop
23391 			 * to process all RTF_MULTIRT ires in the bucket,
23392 			 * and send the packet through all crossed
23393 			 * RTF_MULTIRT routes.
23394 			 */
23395 			do {
23396 				if (multirt_send) {
23397 					irb_t *irb;
23398 
23399 					irb = ire->ire_bucket;
23400 					ASSERT(irb != NULL);
23401 					/*
23402 					 * We are in a multiple send case,
23403 					 * need to get the next IRE and make
23404 					 * a duplicate of the packet.
23405 					 */
23406 					IRB_REFHOLD(irb);
23407 					for (ire1 = ire->ire_next;
23408 					    ire1 != NULL;
23409 					    ire1 = ire1->ire_next) {
23410 						if (!(ire1->ire_flags &
23411 						    RTF_MULTIRT)) {
23412 							continue;
23413 						}
23414 						if (ire1->ire_addr !=
23415 						    ire->ire_addr) {
23416 							continue;
23417 						}
23418 						if (ire1->ire_marks &
23419 						    (IRE_MARK_CONDEMNED|
23420 						    IRE_MARK_HIDDEN)) {
23421 							continue;
23422 						}
23423 
23424 						/* Got one */
23425 						IRE_REFHOLD(ire1);
23426 						break;
23427 					}
23428 					IRB_REFRELE(irb);
23429 
23430 					if (ire1 != NULL) {
23431 						next_mp = copyb(mp);
23432 						if ((next_mp == NULL) ||
23433 						    ((mp->b_cont != NULL) &&
23434 						    ((next_mp->b_cont =
23435 						    dupmsg(mp->b_cont))
23436 						    == NULL))) {
23437 							freemsg(next_mp);
23438 							next_mp = NULL;
23439 							ire_refrele(ire1);
23440 							ire1 = NULL;
23441 						}
23442 					}
23443 
23444 					/*
23445 					 * Last multiroute ire; don't loop
23446 					 * anymore. The emission is over
23447 					 * and next_mp is NULL.
23448 					 */
23449 					if (ire1 == NULL) {
23450 						multirt_send = B_FALSE;
23451 					}
23452 				}
23453 
23454 				out_ill = ire->ire_ipif->ipif_ill;
23455 				DTRACE_PROBE4(ip4__physical__out__start,
23456 				    ill_t *, NULL,
23457 				    ill_t *, out_ill,
23458 				    ipha_t *, ipha, mblk_t *, mp);
23459 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23460 				    ipst->ips_ipv4firewall_physical_out,
23461 				    NULL, out_ill, ipha, mp, mp, ipst);
23462 				DTRACE_PROBE1(ip4__physical__out__end,
23463 				    mblk_t *, mp);
23464 				if (mp == NULL)
23465 					goto release_ire_and_ill_2;
23466 
23467 				ASSERT(ipsec_len == 0);
23468 				mp->b_prev =
23469 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23470 				DTRACE_PROBE2(ip__xmit__2,
23471 				    mblk_t *, mp, ire_t *, ire);
23472 				pktxmit_state = ip_xmit_v4(mp, ire,
23473 				    NULL, B_TRUE);
23474 				if ((pktxmit_state == SEND_FAILED) ||
23475 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23476 release_ire_and_ill_2:
23477 					if (next_mp) {
23478 						freemsg(next_mp);
23479 						ire_refrele(ire1);
23480 					}
23481 					ire_refrele(ire);
23482 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23483 					    "ip_wput_ire_end: q %p (%S)",
23484 					    q, "discard MDATA");
23485 					if (conn_outgoing_ill != NULL)
23486 						ill_refrele(conn_outgoing_ill);
23487 					return;
23488 				}
23489 
23490 				if (CLASSD(dst)) {
23491 					BUMP_MIB(out_ill->ill_ip_mib,
23492 					    ipIfStatsHCOutMcastPkts);
23493 					UPDATE_MIB(out_ill->ill_ip_mib,
23494 					    ipIfStatsHCOutMcastOctets,
23495 					    LENGTH);
23496 				} else if (ire->ire_type == IRE_BROADCAST) {
23497 					BUMP_MIB(out_ill->ill_ip_mib,
23498 					    ipIfStatsHCOutBcastPkts);
23499 				}
23500 
23501 				if (multirt_send) {
23502 					/*
23503 					 * We are in a multiple send case,
23504 					 * need to re-enter the sending loop
23505 					 * using the next ire.
23506 					 */
23507 					ire_refrele(ire);
23508 					ire = ire1;
23509 					stq = ire->ire_stq;
23510 					mp = next_mp;
23511 					next_mp = NULL;
23512 					ipha = (ipha_t *)mp->b_rptr;
23513 					ill_index = Q_TO_INDEX(stq);
23514 				}
23515 			} while (multirt_send);
23516 
23517 			if (!next_mp) {
23518 				/*
23519 				 * Last copy going out (the ultra-common
23520 				 * case).  Note that we intentionally replicate
23521 				 * the putnext rather than calling it before
23522 				 * the next_mp check in hopes of a little
23523 				 * tail-call action out of the compiler.
23524 				 */
23525 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23526 				    "ip_wput_ire_end: q %p (%S)",
23527 				    q, "last copy out(1)");
23528 				ire_refrele(ire);
23529 				if (conn_outgoing_ill != NULL)
23530 					ill_refrele(conn_outgoing_ill);
23531 				return;
23532 			}
23533 			/* More copies going out below. */
23534 		} else {
23535 			int offset;
23536 fragmentit:
23537 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23538 			/*
23539 			 * If this would generate a icmp_frag_needed message,
23540 			 * we need to handle it before we do the IPSEC
23541 			 * processing. Otherwise, we need to strip the IPSEC
23542 			 * headers before we send up the message to the ULPs
23543 			 * which becomes messy and difficult.
23544 			 */
23545 			if (ipsec_len != 0) {
23546 				if ((max_frag < (unsigned int)(LENGTH +
23547 				    ipsec_len)) && (offset & IPH_DF)) {
23548 					out_ill = (ill_t *)stq->q_ptr;
23549 					BUMP_MIB(out_ill->ill_ip_mib,
23550 					    ipIfStatsOutFragFails);
23551 					BUMP_MIB(out_ill->ill_ip_mib,
23552 					    ipIfStatsOutFragReqds);
23553 					ipha->ipha_hdr_checksum = 0;
23554 					ipha->ipha_hdr_checksum =
23555 					    (uint16_t)ip_csum_hdr(ipha);
23556 					icmp_frag_needed(ire->ire_stq, first_mp,
23557 					    max_frag, zoneid, ipst);
23558 					if (!next_mp) {
23559 						ire_refrele(ire);
23560 						if (conn_outgoing_ill != NULL) {
23561 							ill_refrele(
23562 							    conn_outgoing_ill);
23563 						}
23564 						return;
23565 					}
23566 				} else {
23567 					/*
23568 					 * This won't cause a icmp_frag_needed
23569 					 * message. to be generated. Send it on
23570 					 * the wire. Note that this could still
23571 					 * cause fragmentation and all we
23572 					 * do is the generation of the message
23573 					 * to the ULP if needed before IPSEC.
23574 					 */
23575 					if (!next_mp) {
23576 						ipsec_out_process(q, first_mp,
23577 						    ire, ill_index);
23578 						TRACE_2(TR_FAC_IP,
23579 						    TR_IP_WPUT_IRE_END,
23580 						    "ip_wput_ire_end: q %p "
23581 						    "(%S)", q,
23582 						    "last ipsec_out_process");
23583 						ire_refrele(ire);
23584 						if (conn_outgoing_ill != NULL) {
23585 							ill_refrele(
23586 							    conn_outgoing_ill);
23587 						}
23588 						return;
23589 					}
23590 					ipsec_out_process(q, first_mp,
23591 					    ire, ill_index);
23592 				}
23593 			} else {
23594 				/*
23595 				 * Initiate IPPF processing. For
23596 				 * fragmentable packets we finish
23597 				 * all QOS packet processing before
23598 				 * calling:
23599 				 * ip_wput_ire_fragmentit->ip_wput_frag
23600 				 */
23601 
23602 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23603 					ip_process(IPP_LOCAL_OUT, &mp,
23604 					    ill_index);
23605 					if (mp == NULL) {
23606 						out_ill = (ill_t *)stq->q_ptr;
23607 						BUMP_MIB(out_ill->ill_ip_mib,
23608 						    ipIfStatsOutDiscards);
23609 						if (next_mp != NULL) {
23610 							freemsg(next_mp);
23611 							ire_refrele(ire1);
23612 						}
23613 						ire_refrele(ire);
23614 						TRACE_2(TR_FAC_IP,
23615 						    TR_IP_WPUT_IRE_END,
23616 						    "ip_wput_ire: q %p (%S)",
23617 						    q, "discard MDATA");
23618 						if (conn_outgoing_ill != NULL) {
23619 							ill_refrele(
23620 							    conn_outgoing_ill);
23621 						}
23622 						return;
23623 					}
23624 				}
23625 				if (!next_mp) {
23626 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23627 					    "ip_wput_ire_end: q %p (%S)",
23628 					    q, "last fragmentation");
23629 					ip_wput_ire_fragmentit(mp, ire,
23630 					    zoneid, ipst);
23631 					ire_refrele(ire);
23632 					if (conn_outgoing_ill != NULL)
23633 						ill_refrele(conn_outgoing_ill);
23634 					return;
23635 				}
23636 				ip_wput_ire_fragmentit(mp, ire, zoneid, ipst);
23637 			}
23638 		}
23639 	} else {
23640 nullstq:
23641 		/* A NULL stq means the destination address is local. */
23642 		UPDATE_OB_PKT_COUNT(ire);
23643 		ire->ire_last_used_time = lbolt;
23644 		ASSERT(ire->ire_ipif != NULL);
23645 		if (!next_mp) {
23646 			/*
23647 			 * Is there an "in" and "out" for traffic local
23648 			 * to a host (loopback)?  The code in Solaris doesn't
23649 			 * explicitly draw a line in its code for in vs out,
23650 			 * so we've had to draw a line in the sand: ip_wput_ire
23651 			 * is considered to be the "output" side and
23652 			 * ip_wput_local to be the "input" side.
23653 			 */
23654 			out_ill = ire->ire_ipif->ipif_ill;
23655 
23656 			DTRACE_PROBE4(ip4__loopback__out__start,
23657 			    ill_t *, NULL, ill_t *, out_ill,
23658 			    ipha_t *, ipha, mblk_t *, first_mp);
23659 
23660 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23661 			    ipst->ips_ipv4firewall_loopback_out,
23662 			    NULL, out_ill, ipha, first_mp, mp, ipst);
23663 
23664 			DTRACE_PROBE1(ip4__loopback__out_end,
23665 			    mblk_t *, first_mp);
23666 
23667 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23668 			    "ip_wput_ire_end: q %p (%S)",
23669 			    q, "local address");
23670 
23671 			if (first_mp != NULL)
23672 				ip_wput_local(q, out_ill, ipha,
23673 				    first_mp, ire, 0, ire->ire_zoneid);
23674 			ire_refrele(ire);
23675 			if (conn_outgoing_ill != NULL)
23676 				ill_refrele(conn_outgoing_ill);
23677 			return;
23678 		}
23679 
23680 		out_ill = ire->ire_ipif->ipif_ill;
23681 
23682 		DTRACE_PROBE4(ip4__loopback__out__start,
23683 		    ill_t *, NULL, ill_t *, out_ill,
23684 		    ipha_t *, ipha, mblk_t *, first_mp);
23685 
23686 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23687 		    ipst->ips_ipv4firewall_loopback_out,
23688 		    NULL, out_ill, ipha, first_mp, mp, ipst);
23689 
23690 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23691 
23692 		if (first_mp != NULL)
23693 			ip_wput_local(q, out_ill, ipha,
23694 			    first_mp, ire, 0, ire->ire_zoneid);
23695 	}
23696 next:
23697 	/*
23698 	 * More copies going out to additional interfaces.
23699 	 * ire1 has already been held. We don't need the
23700 	 * "ire" anymore.
23701 	 */
23702 	ire_refrele(ire);
23703 	ire = ire1;
23704 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23705 	mp = next_mp;
23706 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23707 	ill = ire_to_ill(ire);
23708 	first_mp = mp;
23709 	if (ipsec_len != 0) {
23710 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23711 		mp = mp->b_cont;
23712 	}
23713 	dst = ire->ire_addr;
23714 	ipha = (ipha_t *)mp->b_rptr;
23715 	/*
23716 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23717 	 * Restore ipha_ident "no checksum" flag.
23718 	 */
23719 	src = orig_src;
23720 	ipha->ipha_ident = ip_hdr_included;
23721 	goto another;
23722 
23723 #undef	rptr
23724 #undef	Q_TO_INDEX
23725 }
23726 
23727 /*
23728  * Routine to allocate a message that is used to notify the ULP about MDT.
23729  * The caller may provide a pointer to the link-layer MDT capabilities,
23730  * or NULL if MDT is to be disabled on the stream.
23731  */
23732 mblk_t *
23733 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23734 {
23735 	mblk_t *mp;
23736 	ip_mdt_info_t *mdti;
23737 	ill_mdt_capab_t *idst;
23738 
23739 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23740 		DB_TYPE(mp) = M_CTL;
23741 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23742 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23743 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23744 		idst = &(mdti->mdt_capab);
23745 
23746 		/*
23747 		 * If the caller provides us with the capability, copy
23748 		 * it over into our notification message; otherwise
23749 		 * we zero out the capability portion.
23750 		 */
23751 		if (isrc != NULL)
23752 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23753 		else
23754 			bzero((caddr_t)idst, sizeof (*idst));
23755 	}
23756 	return (mp);
23757 }
23758 
23759 /*
23760  * Routine which determines whether MDT can be enabled on the destination
23761  * IRE and IPC combination, and if so, allocates and returns the MDT
23762  * notification mblk that may be used by ULP.  We also check if we need to
23763  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23764  * MDT usage in the past have been lifted.  This gets called during IP
23765  * and ULP binding.
23766  */
23767 mblk_t *
23768 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23769     ill_mdt_capab_t *mdt_cap)
23770 {
23771 	mblk_t *mp;
23772 	boolean_t rc = B_FALSE;
23773 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23774 
23775 	ASSERT(dst_ire != NULL);
23776 	ASSERT(connp != NULL);
23777 	ASSERT(mdt_cap != NULL);
23778 
23779 	/*
23780 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23781 	 * Multidata, which is handled in tcp_multisend().  This
23782 	 * is the reason why we do all these checks here, to ensure
23783 	 * that we don't enable Multidata for the cases which we
23784 	 * can't handle at the moment.
23785 	 */
23786 	do {
23787 		/* Only do TCP at the moment */
23788 		if (connp->conn_ulp != IPPROTO_TCP)
23789 			break;
23790 
23791 		/*
23792 		 * IPSEC outbound policy present?  Note that we get here
23793 		 * after calling ipsec_conn_cache_policy() where the global
23794 		 * policy checking is performed.  conn_latch will be
23795 		 * non-NULL as long as there's a policy defined,
23796 		 * i.e. conn_out_enforce_policy may be NULL in such case
23797 		 * when the connection is non-secure, and hence we check
23798 		 * further if the latch refers to an outbound policy.
23799 		 */
23800 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23801 			break;
23802 
23803 		/* CGTP (multiroute) is enabled? */
23804 		if (dst_ire->ire_flags & RTF_MULTIRT)
23805 			break;
23806 
23807 		/* Outbound IPQoS enabled? */
23808 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23809 			/*
23810 			 * In this case, we disable MDT for this and all
23811 			 * future connections going over the interface.
23812 			 */
23813 			mdt_cap->ill_mdt_on = 0;
23814 			break;
23815 		}
23816 
23817 		/* socket option(s) present? */
23818 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23819 			break;
23820 
23821 		rc = B_TRUE;
23822 	/* CONSTCOND */
23823 	} while (0);
23824 
23825 	/* Remember the result */
23826 	connp->conn_mdt_ok = rc;
23827 
23828 	if (!rc)
23829 		return (NULL);
23830 	else if (!mdt_cap->ill_mdt_on) {
23831 		/*
23832 		 * If MDT has been previously turned off in the past, and we
23833 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23834 		 * then enable it for this interface.
23835 		 */
23836 		mdt_cap->ill_mdt_on = 1;
23837 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23838 		    "interface %s\n", ill_name));
23839 	}
23840 
23841 	/* Allocate the MDT info mblk */
23842 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23843 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23844 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23845 		return (NULL);
23846 	}
23847 	return (mp);
23848 }
23849 
23850 /*
23851  * Routine to allocate a message that is used to notify the ULP about LSO.
23852  * The caller may provide a pointer to the link-layer LSO capabilities,
23853  * or NULL if LSO is to be disabled on the stream.
23854  */
23855 mblk_t *
23856 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23857 {
23858 	mblk_t *mp;
23859 	ip_lso_info_t *lsoi;
23860 	ill_lso_capab_t *idst;
23861 
23862 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23863 		DB_TYPE(mp) = M_CTL;
23864 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23865 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23866 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23867 		idst = &(lsoi->lso_capab);
23868 
23869 		/*
23870 		 * If the caller provides us with the capability, copy
23871 		 * it over into our notification message; otherwise
23872 		 * we zero out the capability portion.
23873 		 */
23874 		if (isrc != NULL)
23875 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23876 		else
23877 			bzero((caddr_t)idst, sizeof (*idst));
23878 	}
23879 	return (mp);
23880 }
23881 
23882 /*
23883  * Routine which determines whether LSO can be enabled on the destination
23884  * IRE and IPC combination, and if so, allocates and returns the LSO
23885  * notification mblk that may be used by ULP.  We also check if we need to
23886  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23887  * LSO usage in the past have been lifted.  This gets called during IP
23888  * and ULP binding.
23889  */
23890 mblk_t *
23891 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23892     ill_lso_capab_t *lso_cap)
23893 {
23894 	mblk_t *mp;
23895 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23896 
23897 	ASSERT(dst_ire != NULL);
23898 	ASSERT(connp != NULL);
23899 	ASSERT(lso_cap != NULL);
23900 
23901 	connp->conn_lso_ok = B_TRUE;
23902 
23903 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23904 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23905 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23906 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23907 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23908 		connp->conn_lso_ok = B_FALSE;
23909 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23910 			/*
23911 			 * Disable LSO for this and all future connections going
23912 			 * over the interface.
23913 			 */
23914 			lso_cap->ill_lso_on = 0;
23915 		}
23916 	}
23917 
23918 	if (!connp->conn_lso_ok)
23919 		return (NULL);
23920 	else if (!lso_cap->ill_lso_on) {
23921 		/*
23922 		 * If LSO has been previously turned off in the past, and we
23923 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23924 		 * then enable it for this interface.
23925 		 */
23926 		lso_cap->ill_lso_on = 1;
23927 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23928 		    ill_name));
23929 	}
23930 
23931 	/* Allocate the LSO info mblk */
23932 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23933 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23934 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23935 
23936 	return (mp);
23937 }
23938 
23939 /*
23940  * Create destination address attribute, and fill it with the physical
23941  * destination address and SAP taken from the template DL_UNITDATA_REQ
23942  * message block.
23943  */
23944 boolean_t
23945 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23946 {
23947 	dl_unitdata_req_t *dlurp;
23948 	pattr_t *pa;
23949 	pattrinfo_t pa_info;
23950 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23951 	uint_t das_len, das_off;
23952 
23953 	ASSERT(dlmp != NULL);
23954 
23955 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23956 	das_len = dlurp->dl_dest_addr_length;
23957 	das_off = dlurp->dl_dest_addr_offset;
23958 
23959 	pa_info.type = PATTR_DSTADDRSAP;
23960 	pa_info.len = sizeof (**das) + das_len - 1;
23961 
23962 	/* create and associate the attribute */
23963 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23964 	if (pa != NULL) {
23965 		ASSERT(*das != NULL);
23966 		(*das)->addr_is_group = 0;
23967 		(*das)->addr_len = (uint8_t)das_len;
23968 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23969 	}
23970 
23971 	return (pa != NULL);
23972 }
23973 
23974 /*
23975  * Create hardware checksum attribute and fill it with the values passed.
23976  */
23977 boolean_t
23978 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23979     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23980 {
23981 	pattr_t *pa;
23982 	pattrinfo_t pa_info;
23983 
23984 	ASSERT(mmd != NULL);
23985 
23986 	pa_info.type = PATTR_HCKSUM;
23987 	pa_info.len = sizeof (pattr_hcksum_t);
23988 
23989 	/* create and associate the attribute */
23990 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23991 	if (pa != NULL) {
23992 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23993 
23994 		hck->hcksum_start_offset = start_offset;
23995 		hck->hcksum_stuff_offset = stuff_offset;
23996 		hck->hcksum_end_offset = end_offset;
23997 		hck->hcksum_flags = flags;
23998 	}
23999 	return (pa != NULL);
24000 }
24001 
24002 /*
24003  * Create zerocopy attribute and fill it with the specified flags
24004  */
24005 boolean_t
24006 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
24007 {
24008 	pattr_t *pa;
24009 	pattrinfo_t pa_info;
24010 
24011 	ASSERT(mmd != NULL);
24012 	pa_info.type = PATTR_ZCOPY;
24013 	pa_info.len = sizeof (pattr_zcopy_t);
24014 
24015 	/* create and associate the attribute */
24016 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
24017 	if (pa != NULL) {
24018 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
24019 
24020 		zcopy->zcopy_flags = flags;
24021 	}
24022 	return (pa != NULL);
24023 }
24024 
24025 /*
24026  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
24027  * block chain. We could rewrite to handle arbitrary message block chains but
24028  * that would make the code complicated and slow. Right now there three
24029  * restrictions:
24030  *
24031  *   1. The first message block must contain the complete IP header and
24032  *	at least 1 byte of payload data.
24033  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
24034  *	so that we can use a single Multidata message.
24035  *   3. No frag must be distributed over two or more message blocks so
24036  *	that we don't need more than two packet descriptors per frag.
24037  *
24038  * The above restrictions allow us to support userland applications (which
24039  * will send down a single message block) and NFS over UDP (which will
24040  * send down a chain of at most three message blocks).
24041  *
24042  * We also don't use MDT for payloads with less than or equal to
24043  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
24044  */
24045 boolean_t
24046 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
24047 {
24048 	int	blocks;
24049 	ssize_t	total, missing, size;
24050 
24051 	ASSERT(mp != NULL);
24052 	ASSERT(hdr_len > 0);
24053 
24054 	size = MBLKL(mp) - hdr_len;
24055 	if (size <= 0)
24056 		return (B_FALSE);
24057 
24058 	/* The first mblk contains the header and some payload. */
24059 	blocks = 1;
24060 	total = size;
24061 	size %= len;
24062 	missing = (size == 0) ? 0 : (len - size);
24063 	mp = mp->b_cont;
24064 
24065 	while (mp != NULL) {
24066 		/*
24067 		 * Give up if we encounter a zero length message block.
24068 		 * In practice, this should rarely happen and therefore
24069 		 * not worth the trouble of freeing and re-linking the
24070 		 * mblk from the chain to handle such case.
24071 		 */
24072 		if ((size = MBLKL(mp)) == 0)
24073 			return (B_FALSE);
24074 
24075 		/* Too many payload buffers for a single Multidata message? */
24076 		if (++blocks > MULTIDATA_MAX_PBUFS)
24077 			return (B_FALSE);
24078 
24079 		total += size;
24080 		/* Is a frag distributed over two or more message blocks? */
24081 		if (missing > size)
24082 			return (B_FALSE);
24083 		size -= missing;
24084 
24085 		size %= len;
24086 		missing = (size == 0) ? 0 : (len - size);
24087 
24088 		mp = mp->b_cont;
24089 	}
24090 
24091 	return (total > ip_wput_frag_mdt_min);
24092 }
24093 
24094 /*
24095  * Outbound IPv4 fragmentation routine using MDT.
24096  */
24097 static void
24098 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
24099     uint32_t frag_flag, int offset)
24100 {
24101 	ipha_t		*ipha_orig;
24102 	int		i1, ip_data_end;
24103 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
24104 	mblk_t		*hdr_mp, *md_mp = NULL;
24105 	unsigned char	*hdr_ptr, *pld_ptr;
24106 	multidata_t	*mmd;
24107 	ip_pdescinfo_t	pdi;
24108 	ill_t		*ill;
24109 	ip_stack_t	*ipst = ire->ire_ipst;
24110 
24111 	ASSERT(DB_TYPE(mp) == M_DATA);
24112 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
24113 
24114 	ill = ire_to_ill(ire);
24115 	ASSERT(ill != NULL);
24116 
24117 	ipha_orig = (ipha_t *)mp->b_rptr;
24118 	mp->b_rptr += sizeof (ipha_t);
24119 
24120 	/* Calculate how many packets we will send out */
24121 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
24122 	pkts = (i1 + len - 1) / len;
24123 	ASSERT(pkts > 1);
24124 
24125 	/* Allocate a message block which will hold all the IP Headers. */
24126 	wroff = ipst->ips_ip_wroff_extra;
24127 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
24128 
24129 	i1 = pkts * hdr_chunk_len;
24130 	/*
24131 	 * Create the header buffer, Multidata and destination address
24132 	 * and SAP attribute that should be associated with it.
24133 	 */
24134 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
24135 	    ((hdr_mp->b_wptr += i1),
24136 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
24137 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
24138 		freemsg(mp);
24139 		if (md_mp == NULL) {
24140 			freemsg(hdr_mp);
24141 		} else {
24142 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
24143 			freemsg(md_mp);
24144 		}
24145 		IP_STAT(ipst, ip_frag_mdt_allocfail);
24146 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
24147 		return;
24148 	}
24149 	IP_STAT(ipst, ip_frag_mdt_allocd);
24150 
24151 	/*
24152 	 * Add a payload buffer to the Multidata; this operation must not
24153 	 * fail, or otherwise our logic in this routine is broken.  There
24154 	 * is no memory allocation done by the routine, so any returned
24155 	 * failure simply tells us that we've done something wrong.
24156 	 *
24157 	 * A failure tells us that either we're adding the same payload
24158 	 * buffer more than once, or we're trying to add more buffers than
24159 	 * allowed.  None of the above cases should happen, and we panic
24160 	 * because either there's horrible heap corruption, and/or
24161 	 * programming mistake.
24162 	 */
24163 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24164 		goto pbuf_panic;
24165 
24166 	hdr_ptr = hdr_mp->b_rptr;
24167 	pld_ptr = mp->b_rptr;
24168 
24169 	/* Establish the ending byte offset, based on the starting offset. */
24170 	offset <<= 3;
24171 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
24172 	    IP_SIMPLE_HDR_LENGTH;
24173 
24174 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
24175 
24176 	while (pld_ptr < mp->b_wptr) {
24177 		ipha_t		*ipha;
24178 		uint16_t	offset_and_flags;
24179 		uint16_t	ip_len;
24180 		int		error;
24181 
24182 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
24183 		ipha = (ipha_t *)(hdr_ptr + wroff);
24184 		ASSERT(OK_32PTR(ipha));
24185 		*ipha = *ipha_orig;
24186 
24187 		if (ip_data_end - offset > len) {
24188 			offset_and_flags = IPH_MF;
24189 		} else {
24190 			/*
24191 			 * Last frag. Set len to the length of this last piece.
24192 			 */
24193 			len = ip_data_end - offset;
24194 			/* A frag of a frag might have IPH_MF non-zero */
24195 			offset_and_flags =
24196 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24197 			    IPH_MF;
24198 		}
24199 		offset_and_flags |= (uint16_t)(offset >> 3);
24200 		offset_and_flags |= (uint16_t)frag_flag;
24201 		/* Store the offset and flags in the IP header. */
24202 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24203 
24204 		/* Store the length in the IP header. */
24205 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
24206 		ipha->ipha_length = htons(ip_len);
24207 
24208 		/*
24209 		 * Set the IP header checksum.  Note that mp is just
24210 		 * the header, so this is easy to pass to ip_csum.
24211 		 */
24212 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24213 
24214 		/*
24215 		 * Record offset and size of header and data of the next packet
24216 		 * in the multidata message.
24217 		 */
24218 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
24219 		PDESC_PLD_INIT(&pdi);
24220 		i1 = MIN(mp->b_wptr - pld_ptr, len);
24221 		ASSERT(i1 > 0);
24222 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
24223 		if (i1 == len) {
24224 			pld_ptr += len;
24225 		} else {
24226 			i1 = len - i1;
24227 			mp = mp->b_cont;
24228 			ASSERT(mp != NULL);
24229 			ASSERT(MBLKL(mp) >= i1);
24230 			/*
24231 			 * Attach the next payload message block to the
24232 			 * multidata message.
24233 			 */
24234 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24235 				goto pbuf_panic;
24236 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
24237 			pld_ptr = mp->b_rptr + i1;
24238 		}
24239 
24240 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
24241 		    KM_NOSLEEP)) == NULL) {
24242 			/*
24243 			 * Any failure other than ENOMEM indicates that we
24244 			 * have passed in invalid pdesc info or parameters
24245 			 * to mmd_addpdesc, which must not happen.
24246 			 *
24247 			 * EINVAL is a result of failure on boundary checks
24248 			 * against the pdesc info contents.  It should not
24249 			 * happen, and we panic because either there's
24250 			 * horrible heap corruption, and/or programming
24251 			 * mistake.
24252 			 */
24253 			if (error != ENOMEM) {
24254 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
24255 				    "pdesc logic error detected for "
24256 				    "mmd %p pinfo %p (%d)\n",
24257 				    (void *)mmd, (void *)&pdi, error);
24258 				/* NOTREACHED */
24259 			}
24260 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
24261 			/* Free unattached payload message blocks as well */
24262 			md_mp->b_cont = mp->b_cont;
24263 			goto free_mmd;
24264 		}
24265 
24266 		/* Advance fragment offset. */
24267 		offset += len;
24268 
24269 		/* Advance to location for next header in the buffer. */
24270 		hdr_ptr += hdr_chunk_len;
24271 
24272 		/* Did we reach the next payload message block? */
24273 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
24274 			mp = mp->b_cont;
24275 			/*
24276 			 * Attach the next message block with payload
24277 			 * data to the multidata message.
24278 			 */
24279 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24280 				goto pbuf_panic;
24281 			pld_ptr = mp->b_rptr;
24282 		}
24283 	}
24284 
24285 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
24286 	ASSERT(mp->b_wptr == pld_ptr);
24287 
24288 	/* Update IP statistics */
24289 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
24290 
24291 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
24292 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
24293 
24294 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
24295 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
24296 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
24297 
24298 	if (pkt_type == OB_PKT) {
24299 		ire->ire_ob_pkt_count += pkts;
24300 		if (ire->ire_ipif != NULL)
24301 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
24302 	} else {
24303 		/*
24304 		 * The type is IB_PKT in the forwarding path and in
24305 		 * the mobile IP case when the packet is being reverse-
24306 		 * tunneled to the home agent.
24307 		 */
24308 		ire->ire_ib_pkt_count += pkts;
24309 		ASSERT(!IRE_IS_LOCAL(ire));
24310 		if (ire->ire_type & IRE_BROADCAST) {
24311 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
24312 		} else {
24313 			UPDATE_MIB(ill->ill_ip_mib,
24314 			    ipIfStatsHCOutForwDatagrams, pkts);
24315 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
24316 		}
24317 	}
24318 	ire->ire_last_used_time = lbolt;
24319 	/* Send it down */
24320 	putnext(ire->ire_stq, md_mp);
24321 	return;
24322 
24323 pbuf_panic:
24324 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
24325 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
24326 	    pbuf_idx);
24327 	/* NOTREACHED */
24328 }
24329 
24330 /*
24331  * Outbound IP fragmentation routine.
24332  *
24333  * NOTE : This routine does not ire_refrele the ire that is passed in
24334  * as the argument.
24335  */
24336 static void
24337 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
24338     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst)
24339 {
24340 	int		i1;
24341 	mblk_t		*ll_hdr_mp;
24342 	int 		ll_hdr_len;
24343 	int		hdr_len;
24344 	mblk_t		*hdr_mp;
24345 	ipha_t		*ipha;
24346 	int		ip_data_end;
24347 	int		len;
24348 	mblk_t		*mp = mp_orig, *mp1;
24349 	int		offset;
24350 	queue_t		*q;
24351 	uint32_t	v_hlen_tos_len;
24352 	mblk_t		*first_mp;
24353 	boolean_t	mctl_present;
24354 	ill_t		*ill;
24355 	ill_t		*out_ill;
24356 	mblk_t		*xmit_mp;
24357 	mblk_t		*carve_mp;
24358 	ire_t		*ire1 = NULL;
24359 	ire_t		*save_ire = NULL;
24360 	mblk_t  	*next_mp = NULL;
24361 	boolean_t	last_frag = B_FALSE;
24362 	boolean_t	multirt_send = B_FALSE;
24363 	ire_t		*first_ire = NULL;
24364 	irb_t		*irb = NULL;
24365 	mib2_ipIfStatsEntry_t *mibptr = NULL;
24366 
24367 	ill = ire_to_ill(ire);
24368 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
24369 
24370 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
24371 
24372 	if (max_frag == 0) {
24373 		ip1dbg(("ip_wput_frag: ire frag size is 0"
24374 		    " -  dropping packet\n"));
24375 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24376 		freemsg(mp);
24377 		return;
24378 	}
24379 
24380 	/*
24381 	 * IPSEC does not allow hw accelerated packets to be fragmented
24382 	 * This check is made in ip_wput_ipsec_out prior to coming here
24383 	 * via ip_wput_ire_fragmentit.
24384 	 *
24385 	 * If at this point we have an ire whose ARP request has not
24386 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24387 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24388 	 * This packet and all fragmentable packets for this ire will
24389 	 * continue to get dropped while ire_nce->nce_state remains in
24390 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24391 	 * ND_REACHABLE, all subsquent large packets for this ire will
24392 	 * get fragemented and sent out by this function.
24393 	 */
24394 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24395 		/* If nce_state is ND_INITIAL, trigger ARP query */
24396 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
24397 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24398 		    " -  dropping packet\n"));
24399 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24400 		freemsg(mp);
24401 		return;
24402 	}
24403 
24404 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24405 	    "ip_wput_frag_start:");
24406 
24407 	if (mp->b_datap->db_type == M_CTL) {
24408 		first_mp = mp;
24409 		mp_orig = mp = mp->b_cont;
24410 		mctl_present = B_TRUE;
24411 	} else {
24412 		first_mp = mp;
24413 		mctl_present = B_FALSE;
24414 	}
24415 
24416 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24417 	ipha = (ipha_t *)mp->b_rptr;
24418 
24419 	/*
24420 	 * If the Don't Fragment flag is on, generate an ICMP destination
24421 	 * unreachable, fragmentation needed.
24422 	 */
24423 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24424 	if (offset & IPH_DF) {
24425 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24426 		if (is_system_labeled()) {
24427 			max_frag = tsol_pmtu_adjust(mp, ire->ire_max_frag,
24428 			    ire->ire_max_frag - max_frag, AF_INET);
24429 		}
24430 		/*
24431 		 * Need to compute hdr checksum if called from ip_wput_ire.
24432 		 * Note that ip_rput_forward verifies the checksum before
24433 		 * calling this routine so in that case this is a noop.
24434 		 */
24435 		ipha->ipha_hdr_checksum = 0;
24436 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24437 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24438 		    ipst);
24439 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24440 		    "ip_wput_frag_end:(%S)",
24441 		    "don't fragment");
24442 		return;
24443 	}
24444 	/*
24445 	 * Labeled systems adjust max_frag if they add a label
24446 	 * to send the correct path mtu.  We need the real mtu since we
24447 	 * are fragmenting the packet after label adjustment.
24448 	 */
24449 	if (is_system_labeled())
24450 		max_frag = ire->ire_max_frag;
24451 	if (mctl_present)
24452 		freeb(first_mp);
24453 	/*
24454 	 * Establish the starting offset.  May not be zero if we are fragging
24455 	 * a fragment that is being forwarded.
24456 	 */
24457 	offset = offset & IPH_OFFSET;
24458 
24459 	/* TODO why is this test needed? */
24460 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24461 	if (((max_frag - LENGTH) & ~7) < 8) {
24462 		/* TODO: notify ulp somehow */
24463 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24464 		freemsg(mp);
24465 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24466 		    "ip_wput_frag_end:(%S)",
24467 		    "len < 8");
24468 		return;
24469 	}
24470 
24471 	hdr_len = (V_HLEN & 0xF) << 2;
24472 
24473 	ipha->ipha_hdr_checksum = 0;
24474 
24475 	/*
24476 	 * Establish the number of bytes maximum per frag, after putting
24477 	 * in the header.
24478 	 */
24479 	len = (max_frag - hdr_len) & ~7;
24480 
24481 	/* Check if we can use MDT to send out the frags. */
24482 	ASSERT(!IRE_IS_LOCAL(ire));
24483 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24484 	    ipst->ips_ip_multidata_outbound &&
24485 	    !(ire->ire_flags & RTF_MULTIRT) &&
24486 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24487 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24488 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24489 		ASSERT(ill->ill_mdt_capab != NULL);
24490 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24491 			/*
24492 			 * If MDT has been previously turned off in the past,
24493 			 * and we currently can do MDT (due to IPQoS policy
24494 			 * removal, etc.) then enable it for this interface.
24495 			 */
24496 			ill->ill_mdt_capab->ill_mdt_on = 1;
24497 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24498 			    ill->ill_name));
24499 		}
24500 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24501 		    offset);
24502 		return;
24503 	}
24504 
24505 	/* Get a copy of the header for the trailing frags */
24506 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst);
24507 	if (!hdr_mp) {
24508 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24509 		freemsg(mp);
24510 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24511 		    "ip_wput_frag_end:(%S)",
24512 		    "couldn't copy hdr");
24513 		return;
24514 	}
24515 	if (DB_CRED(mp) != NULL)
24516 		mblk_setcred(hdr_mp, DB_CRED(mp));
24517 
24518 	/* Store the starting offset, with the MoreFrags flag. */
24519 	i1 = offset | IPH_MF | frag_flag;
24520 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24521 
24522 	/* Establish the ending byte offset, based on the starting offset. */
24523 	offset <<= 3;
24524 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24525 
24526 	/* Store the length of the first fragment in the IP header. */
24527 	i1 = len + hdr_len;
24528 	ASSERT(i1 <= IP_MAXPACKET);
24529 	ipha->ipha_length = htons((uint16_t)i1);
24530 
24531 	/*
24532 	 * Compute the IP header checksum for the first frag.  We have to
24533 	 * watch out that we stop at the end of the header.
24534 	 */
24535 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24536 
24537 	/*
24538 	 * Now carve off the first frag.  Note that this will include the
24539 	 * original IP header.
24540 	 */
24541 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24542 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24543 		freeb(hdr_mp);
24544 		freemsg(mp_orig);
24545 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24546 		    "ip_wput_frag_end:(%S)",
24547 		    "couldn't carve first");
24548 		return;
24549 	}
24550 
24551 	/*
24552 	 * Multirouting case. Each fragment is replicated
24553 	 * via all non-condemned RTF_MULTIRT routes
24554 	 * currently resolved.
24555 	 * We ensure that first_ire is the first RTF_MULTIRT
24556 	 * ire in the bucket.
24557 	 */
24558 	if (ire->ire_flags & RTF_MULTIRT) {
24559 		irb = ire->ire_bucket;
24560 		ASSERT(irb != NULL);
24561 
24562 		multirt_send = B_TRUE;
24563 
24564 		/* Make sure we do not omit any multiroute ire. */
24565 		IRB_REFHOLD(irb);
24566 		for (first_ire = irb->irb_ire;
24567 		    first_ire != NULL;
24568 		    first_ire = first_ire->ire_next) {
24569 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24570 			    (first_ire->ire_addr == ire->ire_addr) &&
24571 			    !(first_ire->ire_marks &
24572 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
24573 				break;
24574 			}
24575 		}
24576 
24577 		if (first_ire != NULL) {
24578 			if (first_ire != ire) {
24579 				IRE_REFHOLD(first_ire);
24580 				/*
24581 				 * Do not release the ire passed in
24582 				 * as the argument.
24583 				 */
24584 				ire = first_ire;
24585 			} else {
24586 				first_ire = NULL;
24587 			}
24588 		}
24589 		IRB_REFRELE(irb);
24590 
24591 		/*
24592 		 * Save the first ire; we will need to restore it
24593 		 * for the trailing frags.
24594 		 * We REFHOLD save_ire, as each iterated ire will be
24595 		 * REFRELEd.
24596 		 */
24597 		save_ire = ire;
24598 		IRE_REFHOLD(save_ire);
24599 	}
24600 
24601 	/*
24602 	 * First fragment emission loop.
24603 	 * In most cases, the emission loop below is entered only
24604 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24605 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24606 	 * bucket, and send the fragment through all crossed
24607 	 * RTF_MULTIRT routes.
24608 	 */
24609 	do {
24610 		if (ire->ire_flags & RTF_MULTIRT) {
24611 			/*
24612 			 * We are in a multiple send case, need to get
24613 			 * the next ire and make a copy of the packet.
24614 			 * ire1 holds here the next ire to process in the
24615 			 * bucket. If multirouting is expected,
24616 			 * any non-RTF_MULTIRT ire that has the
24617 			 * right destination address is ignored.
24618 			 *
24619 			 * We have to take into account the MTU of
24620 			 * each walked ire. max_frag is set by the
24621 			 * the caller and generally refers to
24622 			 * the primary ire entry. Here we ensure that
24623 			 * no route with a lower MTU will be used, as
24624 			 * fragments are carved once for all ires,
24625 			 * then replicated.
24626 			 */
24627 			ASSERT(irb != NULL);
24628 			IRB_REFHOLD(irb);
24629 			for (ire1 = ire->ire_next;
24630 			    ire1 != NULL;
24631 			    ire1 = ire1->ire_next) {
24632 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24633 					continue;
24634 				if (ire1->ire_addr != ire->ire_addr)
24635 					continue;
24636 				if (ire1->ire_marks &
24637 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
24638 					continue;
24639 				/*
24640 				 * Ensure we do not exceed the MTU
24641 				 * of the next route.
24642 				 */
24643 				if (ire1->ire_max_frag < max_frag) {
24644 					ip_multirt_bad_mtu(ire1, max_frag);
24645 					continue;
24646 				}
24647 
24648 				/* Got one. */
24649 				IRE_REFHOLD(ire1);
24650 				break;
24651 			}
24652 			IRB_REFRELE(irb);
24653 
24654 			if (ire1 != NULL) {
24655 				next_mp = copyb(mp);
24656 				if ((next_mp == NULL) ||
24657 				    ((mp->b_cont != NULL) &&
24658 				    ((next_mp->b_cont =
24659 				    dupmsg(mp->b_cont)) == NULL))) {
24660 					freemsg(next_mp);
24661 					next_mp = NULL;
24662 					ire_refrele(ire1);
24663 					ire1 = NULL;
24664 				}
24665 			}
24666 
24667 			/* Last multiroute ire; don't loop anymore. */
24668 			if (ire1 == NULL) {
24669 				multirt_send = B_FALSE;
24670 			}
24671 		}
24672 
24673 		ll_hdr_len = 0;
24674 		LOCK_IRE_FP_MP(ire);
24675 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24676 		if (ll_hdr_mp != NULL) {
24677 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24678 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24679 		} else {
24680 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24681 		}
24682 
24683 		/* If there is a transmit header, get a copy for this frag. */
24684 		/*
24685 		 * TODO: should check db_ref before calling ip_carve_mp since
24686 		 * it might give us a dup.
24687 		 */
24688 		if (!ll_hdr_mp) {
24689 			/* No xmit header. */
24690 			xmit_mp = mp;
24691 
24692 		/* We have a link-layer header that can fit in our mblk. */
24693 		} else if (mp->b_datap->db_ref == 1 &&
24694 		    ll_hdr_len != 0 &&
24695 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24696 			/* M_DATA fastpath */
24697 			mp->b_rptr -= ll_hdr_len;
24698 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24699 			xmit_mp = mp;
24700 
24701 		/* Corner case if copyb has failed */
24702 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24703 			UNLOCK_IRE_FP_MP(ire);
24704 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24705 			freeb(hdr_mp);
24706 			freemsg(mp);
24707 			freemsg(mp_orig);
24708 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24709 			    "ip_wput_frag_end:(%S)",
24710 			    "discard");
24711 
24712 			if (multirt_send) {
24713 				ASSERT(ire1);
24714 				ASSERT(next_mp);
24715 
24716 				freemsg(next_mp);
24717 				ire_refrele(ire1);
24718 			}
24719 			if (save_ire != NULL)
24720 				IRE_REFRELE(save_ire);
24721 
24722 			if (first_ire != NULL)
24723 				ire_refrele(first_ire);
24724 			return;
24725 
24726 		/*
24727 		 * Case of res_mp OR the fastpath mp can't fit
24728 		 * in the mblk
24729 		 */
24730 		} else {
24731 			xmit_mp->b_cont = mp;
24732 			if (DB_CRED(mp) != NULL)
24733 				mblk_setcred(xmit_mp, DB_CRED(mp));
24734 			/*
24735 			 * Get priority marking, if any.
24736 			 * We propagate the CoS marking from the
24737 			 * original packet that went to QoS processing
24738 			 * in ip_wput_ire to the newly carved mp.
24739 			 */
24740 			if (DB_TYPE(xmit_mp) == M_DATA)
24741 				xmit_mp->b_band = mp->b_band;
24742 		}
24743 		UNLOCK_IRE_FP_MP(ire);
24744 
24745 		q = ire->ire_stq;
24746 		out_ill = (ill_t *)q->q_ptr;
24747 
24748 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24749 
24750 		DTRACE_PROBE4(ip4__physical__out__start,
24751 		    ill_t *, NULL, ill_t *, out_ill,
24752 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24753 
24754 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24755 		    ipst->ips_ipv4firewall_physical_out,
24756 		    NULL, out_ill, ipha, xmit_mp, mp, ipst);
24757 
24758 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24759 
24760 		if (xmit_mp != NULL) {
24761 			putnext(q, xmit_mp);
24762 
24763 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24764 			UPDATE_MIB(out_ill->ill_ip_mib,
24765 			    ipIfStatsHCOutOctets, i1);
24766 
24767 			if (pkt_type != OB_PKT) {
24768 				/*
24769 				 * Update the packet count and MIB stats
24770 				 * of trailing RTF_MULTIRT ires.
24771 				 */
24772 				UPDATE_OB_PKT_COUNT(ire);
24773 				BUMP_MIB(out_ill->ill_ip_mib,
24774 				    ipIfStatsOutFragReqds);
24775 			}
24776 		}
24777 
24778 		if (multirt_send) {
24779 			/*
24780 			 * We are in a multiple send case; look for
24781 			 * the next ire and re-enter the loop.
24782 			 */
24783 			ASSERT(ire1);
24784 			ASSERT(next_mp);
24785 			/* REFRELE the current ire before looping */
24786 			ire_refrele(ire);
24787 			ire = ire1;
24788 			ire1 = NULL;
24789 			mp = next_mp;
24790 			next_mp = NULL;
24791 		}
24792 	} while (multirt_send);
24793 
24794 	ASSERT(ire1 == NULL);
24795 
24796 	/* Restore the original ire; we need it for the trailing frags */
24797 	if (save_ire != NULL) {
24798 		/* REFRELE the last iterated ire */
24799 		ire_refrele(ire);
24800 		/* save_ire has been REFHOLDed */
24801 		ire = save_ire;
24802 		save_ire = NULL;
24803 		q = ire->ire_stq;
24804 	}
24805 
24806 	if (pkt_type == OB_PKT) {
24807 		UPDATE_OB_PKT_COUNT(ire);
24808 	} else {
24809 		out_ill = (ill_t *)q->q_ptr;
24810 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24811 		UPDATE_IB_PKT_COUNT(ire);
24812 	}
24813 
24814 	/* Advance the offset to the second frag starting point. */
24815 	offset += len;
24816 	/*
24817 	 * Update hdr_len from the copied header - there might be less options
24818 	 * in the later fragments.
24819 	 */
24820 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24821 	/* Loop until done. */
24822 	for (;;) {
24823 		uint16_t	offset_and_flags;
24824 		uint16_t	ip_len;
24825 
24826 		if (ip_data_end - offset > len) {
24827 			/*
24828 			 * Carve off the appropriate amount from the original
24829 			 * datagram.
24830 			 */
24831 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24832 				mp = NULL;
24833 				break;
24834 			}
24835 			/*
24836 			 * More frags after this one.  Get another copy
24837 			 * of the header.
24838 			 */
24839 			if (carve_mp->b_datap->db_ref == 1 &&
24840 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24841 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24842 				/* Inline IP header */
24843 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24844 				    hdr_mp->b_rptr;
24845 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24846 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24847 				mp = carve_mp;
24848 			} else {
24849 				if (!(mp = copyb(hdr_mp))) {
24850 					freemsg(carve_mp);
24851 					break;
24852 				}
24853 				/* Get priority marking, if any. */
24854 				mp->b_band = carve_mp->b_band;
24855 				mp->b_cont = carve_mp;
24856 			}
24857 			ipha = (ipha_t *)mp->b_rptr;
24858 			offset_and_flags = IPH_MF;
24859 		} else {
24860 			/*
24861 			 * Last frag.  Consume the header. Set len to
24862 			 * the length of this last piece.
24863 			 */
24864 			len = ip_data_end - offset;
24865 
24866 			/*
24867 			 * Carve off the appropriate amount from the original
24868 			 * datagram.
24869 			 */
24870 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24871 				mp = NULL;
24872 				break;
24873 			}
24874 			if (carve_mp->b_datap->db_ref == 1 &&
24875 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24876 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24877 				/* Inline IP header */
24878 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24879 				    hdr_mp->b_rptr;
24880 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24881 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24882 				mp = carve_mp;
24883 				freeb(hdr_mp);
24884 				hdr_mp = mp;
24885 			} else {
24886 				mp = hdr_mp;
24887 				/* Get priority marking, if any. */
24888 				mp->b_band = carve_mp->b_band;
24889 				mp->b_cont = carve_mp;
24890 			}
24891 			ipha = (ipha_t *)mp->b_rptr;
24892 			/* A frag of a frag might have IPH_MF non-zero */
24893 			offset_and_flags =
24894 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24895 			    IPH_MF;
24896 		}
24897 		offset_and_flags |= (uint16_t)(offset >> 3);
24898 		offset_and_flags |= (uint16_t)frag_flag;
24899 		/* Store the offset and flags in the IP header. */
24900 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24901 
24902 		/* Store the length in the IP header. */
24903 		ip_len = (uint16_t)(len + hdr_len);
24904 		ipha->ipha_length = htons(ip_len);
24905 
24906 		/*
24907 		 * Set the IP header checksum.	Note that mp is just
24908 		 * the header, so this is easy to pass to ip_csum.
24909 		 */
24910 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24911 
24912 		/* Attach a transmit header, if any, and ship it. */
24913 		if (pkt_type == OB_PKT) {
24914 			UPDATE_OB_PKT_COUNT(ire);
24915 		} else {
24916 			out_ill = (ill_t *)q->q_ptr;
24917 			BUMP_MIB(out_ill->ill_ip_mib,
24918 			    ipIfStatsHCOutForwDatagrams);
24919 			UPDATE_IB_PKT_COUNT(ire);
24920 		}
24921 
24922 		if (ire->ire_flags & RTF_MULTIRT) {
24923 			irb = ire->ire_bucket;
24924 			ASSERT(irb != NULL);
24925 
24926 			multirt_send = B_TRUE;
24927 
24928 			/*
24929 			 * Save the original ire; we will need to restore it
24930 			 * for the tailing frags.
24931 			 */
24932 			save_ire = ire;
24933 			IRE_REFHOLD(save_ire);
24934 		}
24935 		/*
24936 		 * Emission loop for this fragment, similar
24937 		 * to what is done for the first fragment.
24938 		 */
24939 		do {
24940 			if (multirt_send) {
24941 				/*
24942 				 * We are in a multiple send case, need to get
24943 				 * the next ire and make a copy of the packet.
24944 				 */
24945 				ASSERT(irb != NULL);
24946 				IRB_REFHOLD(irb);
24947 				for (ire1 = ire->ire_next;
24948 				    ire1 != NULL;
24949 				    ire1 = ire1->ire_next) {
24950 					if (!(ire1->ire_flags & RTF_MULTIRT))
24951 						continue;
24952 					if (ire1->ire_addr != ire->ire_addr)
24953 						continue;
24954 					if (ire1->ire_marks &
24955 					    (IRE_MARK_CONDEMNED|
24956 					    IRE_MARK_HIDDEN)) {
24957 						continue;
24958 					}
24959 					/*
24960 					 * Ensure we do not exceed the MTU
24961 					 * of the next route.
24962 					 */
24963 					if (ire1->ire_max_frag < max_frag) {
24964 						ip_multirt_bad_mtu(ire1,
24965 						    max_frag);
24966 						continue;
24967 					}
24968 
24969 					/* Got one. */
24970 					IRE_REFHOLD(ire1);
24971 					break;
24972 				}
24973 				IRB_REFRELE(irb);
24974 
24975 				if (ire1 != NULL) {
24976 					next_mp = copyb(mp);
24977 					if ((next_mp == NULL) ||
24978 					    ((mp->b_cont != NULL) &&
24979 					    ((next_mp->b_cont =
24980 					    dupmsg(mp->b_cont)) == NULL))) {
24981 						freemsg(next_mp);
24982 						next_mp = NULL;
24983 						ire_refrele(ire1);
24984 						ire1 = NULL;
24985 					}
24986 				}
24987 
24988 				/* Last multiroute ire; don't loop anymore. */
24989 				if (ire1 == NULL) {
24990 					multirt_send = B_FALSE;
24991 				}
24992 			}
24993 
24994 			/* Update transmit header */
24995 			ll_hdr_len = 0;
24996 			LOCK_IRE_FP_MP(ire);
24997 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24998 			if (ll_hdr_mp != NULL) {
24999 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
25000 				ll_hdr_len = MBLKL(ll_hdr_mp);
25001 			} else {
25002 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
25003 			}
25004 
25005 			if (!ll_hdr_mp) {
25006 				xmit_mp = mp;
25007 
25008 			/*
25009 			 * We have link-layer header that can fit in
25010 			 * our mblk.
25011 			 */
25012 			} else if (mp->b_datap->db_ref == 1 &&
25013 			    ll_hdr_len != 0 &&
25014 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
25015 				/* M_DATA fastpath */
25016 				mp->b_rptr -= ll_hdr_len;
25017 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
25018 				    ll_hdr_len);
25019 				xmit_mp = mp;
25020 
25021 			/*
25022 			 * Case of res_mp OR the fastpath mp can't fit
25023 			 * in the mblk
25024 			 */
25025 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
25026 				xmit_mp->b_cont = mp;
25027 				if (DB_CRED(mp) != NULL)
25028 					mblk_setcred(xmit_mp, DB_CRED(mp));
25029 				/* Get priority marking, if any. */
25030 				if (DB_TYPE(xmit_mp) == M_DATA)
25031 					xmit_mp->b_band = mp->b_band;
25032 
25033 			/* Corner case if copyb failed */
25034 			} else {
25035 				/*
25036 				 * Exit both the replication and
25037 				 * fragmentation loops.
25038 				 */
25039 				UNLOCK_IRE_FP_MP(ire);
25040 				goto drop_pkt;
25041 			}
25042 			UNLOCK_IRE_FP_MP(ire);
25043 
25044 			mp1 = mp;
25045 			out_ill = (ill_t *)q->q_ptr;
25046 
25047 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
25048 
25049 			DTRACE_PROBE4(ip4__physical__out__start,
25050 			    ill_t *, NULL, ill_t *, out_ill,
25051 			    ipha_t *, ipha, mblk_t *, xmit_mp);
25052 
25053 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
25054 			    ipst->ips_ipv4firewall_physical_out,
25055 			    NULL, out_ill, ipha, xmit_mp, mp, ipst);
25056 
25057 			DTRACE_PROBE1(ip4__physical__out__end,
25058 			    mblk_t *, xmit_mp);
25059 
25060 			if (mp != mp1 && hdr_mp == mp1)
25061 				hdr_mp = mp;
25062 			if (mp != mp1 && mp_orig == mp1)
25063 				mp_orig = mp;
25064 
25065 			if (xmit_mp != NULL) {
25066 				putnext(q, xmit_mp);
25067 
25068 				BUMP_MIB(out_ill->ill_ip_mib,
25069 				    ipIfStatsHCOutTransmits);
25070 				UPDATE_MIB(out_ill->ill_ip_mib,
25071 				    ipIfStatsHCOutOctets, ip_len);
25072 
25073 				if (pkt_type != OB_PKT) {
25074 					/*
25075 					 * Update the packet count of trailing
25076 					 * RTF_MULTIRT ires.
25077 					 */
25078 					UPDATE_OB_PKT_COUNT(ire);
25079 				}
25080 			}
25081 
25082 			/* All done if we just consumed the hdr_mp. */
25083 			if (mp == hdr_mp) {
25084 				last_frag = B_TRUE;
25085 				BUMP_MIB(out_ill->ill_ip_mib,
25086 				    ipIfStatsOutFragOKs);
25087 			}
25088 
25089 			if (multirt_send) {
25090 				/*
25091 				 * We are in a multiple send case; look for
25092 				 * the next ire and re-enter the loop.
25093 				 */
25094 				ASSERT(ire1);
25095 				ASSERT(next_mp);
25096 				/* REFRELE the current ire before looping */
25097 				ire_refrele(ire);
25098 				ire = ire1;
25099 				ire1 = NULL;
25100 				q = ire->ire_stq;
25101 				mp = next_mp;
25102 				next_mp = NULL;
25103 			}
25104 		} while (multirt_send);
25105 		/*
25106 		 * Restore the original ire; we need it for the
25107 		 * trailing frags
25108 		 */
25109 		if (save_ire != NULL) {
25110 			ASSERT(ire1 == NULL);
25111 			/* REFRELE the last iterated ire */
25112 			ire_refrele(ire);
25113 			/* save_ire has been REFHOLDed */
25114 			ire = save_ire;
25115 			q = ire->ire_stq;
25116 			save_ire = NULL;
25117 		}
25118 
25119 		if (last_frag) {
25120 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
25121 			    "ip_wput_frag_end:(%S)",
25122 			    "consumed hdr_mp");
25123 
25124 			if (first_ire != NULL)
25125 				ire_refrele(first_ire);
25126 			return;
25127 		}
25128 		/* Otherwise, advance and loop. */
25129 		offset += len;
25130 	}
25131 
25132 drop_pkt:
25133 	/* Clean up following allocation failure. */
25134 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
25135 	freemsg(mp);
25136 	if (mp != hdr_mp)
25137 		freeb(hdr_mp);
25138 	if (mp != mp_orig)
25139 		freemsg(mp_orig);
25140 
25141 	if (save_ire != NULL)
25142 		IRE_REFRELE(save_ire);
25143 	if (first_ire != NULL)
25144 		ire_refrele(first_ire);
25145 
25146 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
25147 	    "ip_wput_frag_end:(%S)",
25148 	    "end--alloc failure");
25149 }
25150 
25151 /*
25152  * Copy the header plus those options which have the copy bit set
25153  */
25154 static mblk_t *
25155 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst)
25156 {
25157 	mblk_t	*mp;
25158 	uchar_t	*up;
25159 
25160 	/*
25161 	 * Quick check if we need to look for options without the copy bit
25162 	 * set
25163 	 */
25164 	mp = allocb(ipst->ips_ip_wroff_extra + hdr_len, BPRI_HI);
25165 	if (!mp)
25166 		return (mp);
25167 	mp->b_rptr += ipst->ips_ip_wroff_extra;
25168 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
25169 		bcopy(rptr, mp->b_rptr, hdr_len);
25170 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
25171 		return (mp);
25172 	}
25173 	up  = mp->b_rptr;
25174 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
25175 	up += IP_SIMPLE_HDR_LENGTH;
25176 	rptr += IP_SIMPLE_HDR_LENGTH;
25177 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
25178 	while (hdr_len > 0) {
25179 		uint32_t optval;
25180 		uint32_t optlen;
25181 
25182 		optval = *rptr;
25183 		if (optval == IPOPT_EOL)
25184 			break;
25185 		if (optval == IPOPT_NOP)
25186 			optlen = 1;
25187 		else
25188 			optlen = rptr[1];
25189 		if (optval & IPOPT_COPY) {
25190 			bcopy(rptr, up, optlen);
25191 			up += optlen;
25192 		}
25193 		rptr += optlen;
25194 		hdr_len -= optlen;
25195 	}
25196 	/*
25197 	 * Make sure that we drop an even number of words by filling
25198 	 * with EOL to the next word boundary.
25199 	 */
25200 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
25201 	    hdr_len & 0x3; hdr_len++)
25202 		*up++ = IPOPT_EOL;
25203 	mp->b_wptr = up;
25204 	/* Update header length */
25205 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
25206 	return (mp);
25207 }
25208 
25209 /*
25210  * Delivery to local recipients including fanout to multiple recipients.
25211  * Does not do checksumming of UDP/TCP.
25212  * Note: q should be the read side queue for either the ill or conn.
25213  * Note: rq should be the read side q for the lower (ill) stream.
25214  * We don't send packets to IPPF processing, thus the last argument
25215  * to all the fanout calls are B_FALSE.
25216  */
25217 void
25218 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
25219     int fanout_flags, zoneid_t zoneid)
25220 {
25221 	uint32_t	protocol;
25222 	mblk_t		*first_mp;
25223 	boolean_t	mctl_present;
25224 	int		ire_type;
25225 #define	rptr	((uchar_t *)ipha)
25226 	ip_stack_t	*ipst = ill->ill_ipst;
25227 
25228 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
25229 	    "ip_wput_local_start: q %p", q);
25230 
25231 	if (ire != NULL) {
25232 		ire_type = ire->ire_type;
25233 	} else {
25234 		/*
25235 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
25236 		 * packet is not multicast, we can't tell the ire type.
25237 		 */
25238 		ASSERT(CLASSD(ipha->ipha_dst));
25239 		ire_type = IRE_BROADCAST;
25240 	}
25241 
25242 	first_mp = mp;
25243 	if (first_mp->b_datap->db_type == M_CTL) {
25244 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
25245 		if (!io->ipsec_out_secure) {
25246 			/*
25247 			 * This ipsec_out_t was allocated in ip_wput
25248 			 * for multicast packets to store the ill_index.
25249 			 * As this is being delivered locally, we don't
25250 			 * need this anymore.
25251 			 */
25252 			mp = first_mp->b_cont;
25253 			freeb(first_mp);
25254 			first_mp = mp;
25255 			mctl_present = B_FALSE;
25256 		} else {
25257 			/*
25258 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
25259 			 * security properties for the looped-back packet.
25260 			 */
25261 			mctl_present = B_TRUE;
25262 			mp = first_mp->b_cont;
25263 			ASSERT(mp != NULL);
25264 			ipsec_out_to_in(first_mp);
25265 		}
25266 	} else {
25267 		mctl_present = B_FALSE;
25268 	}
25269 
25270 	DTRACE_PROBE4(ip4__loopback__in__start,
25271 	    ill_t *, ill, ill_t *, NULL,
25272 	    ipha_t *, ipha, mblk_t *, first_mp);
25273 
25274 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
25275 	    ipst->ips_ipv4firewall_loopback_in,
25276 	    ill, NULL, ipha, first_mp, mp, ipst);
25277 
25278 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
25279 
25280 	if (first_mp == NULL)
25281 		return;
25282 
25283 	ipst->ips_loopback_packets++;
25284 
25285 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
25286 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
25287 	if (!IS_SIMPLE_IPH(ipha)) {
25288 		ip_wput_local_options(ipha, ipst);
25289 	}
25290 
25291 	protocol = ipha->ipha_protocol;
25292 	switch (protocol) {
25293 	case IPPROTO_ICMP: {
25294 		ire_t		*ire_zone;
25295 		ilm_t		*ilm;
25296 		mblk_t		*mp1;
25297 		zoneid_t	last_zoneid;
25298 
25299 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(ill)) {
25300 			ASSERT(ire_type == IRE_BROADCAST);
25301 			/*
25302 			 * In the multicast case, applications may have joined
25303 			 * the group from different zones, so we need to deliver
25304 			 * the packet to each of them. Loop through the
25305 			 * multicast memberships structures (ilm) on the receive
25306 			 * ill and send a copy of the packet up each matching
25307 			 * one. However, we don't do this for multicasts sent on
25308 			 * the loopback interface (PHYI_LOOPBACK flag set) as
25309 			 * they must stay in the sender's zone.
25310 			 *
25311 			 * ilm_add_v6() ensures that ilms in the same zone are
25312 			 * contiguous in the ill_ilm list. We use this property
25313 			 * to avoid sending duplicates needed when two
25314 			 * applications in the same zone join the same group on
25315 			 * different logical interfaces: we ignore the ilm if
25316 			 * it's zoneid is the same as the last matching one.
25317 			 * In addition, the sending of the packet for
25318 			 * ire_zoneid is delayed until all of the other ilms
25319 			 * have been exhausted.
25320 			 */
25321 			last_zoneid = -1;
25322 			ILM_WALKER_HOLD(ill);
25323 			for (ilm = ill->ill_ilm; ilm != NULL;
25324 			    ilm = ilm->ilm_next) {
25325 				if ((ilm->ilm_flags & ILM_DELETED) ||
25326 				    ipha->ipha_dst != ilm->ilm_addr ||
25327 				    ilm->ilm_zoneid == last_zoneid ||
25328 				    ilm->ilm_zoneid == zoneid ||
25329 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
25330 					continue;
25331 				mp1 = ip_copymsg(first_mp);
25332 				if (mp1 == NULL)
25333 					continue;
25334 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25335 				    mctl_present, B_FALSE, ill,
25336 				    ilm->ilm_zoneid);
25337 				last_zoneid = ilm->ilm_zoneid;
25338 			}
25339 			ILM_WALKER_RELE(ill);
25340 			/*
25341 			 * Loopback case: the sending endpoint has
25342 			 * IP_MULTICAST_LOOP disabled, therefore we don't
25343 			 * dispatch the multicast packet to the sending zone.
25344 			 */
25345 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
25346 				freemsg(first_mp);
25347 				return;
25348 			}
25349 		} else if (ire_type == IRE_BROADCAST) {
25350 			/*
25351 			 * In the broadcast case, there may be many zones
25352 			 * which need a copy of the packet delivered to them.
25353 			 * There is one IRE_BROADCAST per broadcast address
25354 			 * and per zone; we walk those using a helper function.
25355 			 * In addition, the sending of the packet for zoneid is
25356 			 * delayed until all of the other ires have been
25357 			 * processed.
25358 			 */
25359 			IRB_REFHOLD(ire->ire_bucket);
25360 			ire_zone = NULL;
25361 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25362 			    ire)) != NULL) {
25363 				mp1 = ip_copymsg(first_mp);
25364 				if (mp1 == NULL)
25365 					continue;
25366 
25367 				UPDATE_IB_PKT_COUNT(ire_zone);
25368 				ire_zone->ire_last_used_time = lbolt;
25369 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25370 				    mctl_present, B_FALSE, ill,
25371 				    ire_zone->ire_zoneid);
25372 			}
25373 			IRB_REFRELE(ire->ire_bucket);
25374 		}
25375 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25376 		    0, mctl_present, B_FALSE, ill, zoneid);
25377 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25378 		    "ip_wput_local_end: q %p (%S)",
25379 		    q, "icmp");
25380 		return;
25381 	}
25382 	case IPPROTO_IGMP:
25383 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25384 			/* Bad packet - discarded by igmp_input */
25385 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25386 			    "ip_wput_local_end: q %p (%S)",
25387 			    q, "igmp_input--bad packet");
25388 			if (mctl_present)
25389 				freeb(first_mp);
25390 			return;
25391 		}
25392 		/*
25393 		 * igmp_input() may have returned the pulled up message.
25394 		 * So first_mp and ipha need to be reinitialized.
25395 		 */
25396 		ipha = (ipha_t *)mp->b_rptr;
25397 		if (mctl_present)
25398 			first_mp->b_cont = mp;
25399 		else
25400 			first_mp = mp;
25401 		/* deliver to local raw users */
25402 		break;
25403 	case IPPROTO_ENCAP:
25404 		/*
25405 		 * This case is covered by either ip_fanout_proto, or by
25406 		 * the above security processing for self-tunneled packets.
25407 		 */
25408 		break;
25409 	case IPPROTO_UDP: {
25410 		uint16_t	*up;
25411 		uint32_t	ports;
25412 
25413 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25414 		    UDP_PORTS_OFFSET);
25415 		/* Force a 'valid' checksum. */
25416 		up[3] = 0;
25417 
25418 		ports = *(uint32_t *)up;
25419 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25420 		    (ire_type == IRE_BROADCAST),
25421 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25422 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25423 		    ill, zoneid);
25424 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25425 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25426 		return;
25427 	}
25428 	case IPPROTO_TCP: {
25429 
25430 		/*
25431 		 * For TCP, discard broadcast packets.
25432 		 */
25433 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25434 			freemsg(first_mp);
25435 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25436 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25437 			return;
25438 		}
25439 
25440 		if (mp->b_datap->db_type == M_DATA) {
25441 			/*
25442 			 * M_DATA mblk, so init mblk (chain) for no struio().
25443 			 */
25444 			mblk_t	*mp1 = mp;
25445 
25446 			do {
25447 				mp1->b_datap->db_struioflag = 0;
25448 			} while ((mp1 = mp1->b_cont) != NULL);
25449 		}
25450 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25451 		    <= mp->b_wptr);
25452 		ip_fanout_tcp(q, first_mp, ill, ipha,
25453 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25454 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25455 		    mctl_present, B_FALSE, zoneid);
25456 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25457 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25458 		return;
25459 	}
25460 	case IPPROTO_SCTP:
25461 	{
25462 		uint32_t	ports;
25463 
25464 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25465 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25466 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25467 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25468 		return;
25469 	}
25470 
25471 	default:
25472 		break;
25473 	}
25474 	/*
25475 	 * Find a client for some other protocol.  We give
25476 	 * copies to multiple clients, if more than one is
25477 	 * bound.
25478 	 */
25479 	ip_fanout_proto(q, first_mp, ill, ipha,
25480 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25481 	    mctl_present, B_FALSE, ill, zoneid);
25482 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25483 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25484 #undef	rptr
25485 }
25486 
25487 /*
25488  * Update any source route, record route, or timestamp options.
25489  * Check that we are at end of strict source route.
25490  * The options have been sanity checked by ip_wput_options().
25491  */
25492 static void
25493 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25494 {
25495 	ipoptp_t	opts;
25496 	uchar_t		*opt;
25497 	uint8_t		optval;
25498 	uint8_t		optlen;
25499 	ipaddr_t	dst;
25500 	uint32_t	ts;
25501 	ire_t		*ire;
25502 	timestruc_t	now;
25503 
25504 	ip2dbg(("ip_wput_local_options\n"));
25505 	for (optval = ipoptp_first(&opts, ipha);
25506 	    optval != IPOPT_EOL;
25507 	    optval = ipoptp_next(&opts)) {
25508 		opt = opts.ipoptp_cur;
25509 		optlen = opts.ipoptp_len;
25510 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25511 		switch (optval) {
25512 			uint32_t off;
25513 		case IPOPT_SSRR:
25514 		case IPOPT_LSRR:
25515 			off = opt[IPOPT_OFFSET];
25516 			off--;
25517 			if (optlen < IP_ADDR_LEN ||
25518 			    off > optlen - IP_ADDR_LEN) {
25519 				/* End of source route */
25520 				break;
25521 			}
25522 			/*
25523 			 * This will only happen if two consecutive entries
25524 			 * in the source route contains our address or if
25525 			 * it is a packet with a loose source route which
25526 			 * reaches us before consuming the whole source route
25527 			 */
25528 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25529 			if (optval == IPOPT_SSRR) {
25530 				return;
25531 			}
25532 			/*
25533 			 * Hack: instead of dropping the packet truncate the
25534 			 * source route to what has been used by filling the
25535 			 * rest with IPOPT_NOP.
25536 			 */
25537 			opt[IPOPT_OLEN] = (uint8_t)off;
25538 			while (off < optlen) {
25539 				opt[off++] = IPOPT_NOP;
25540 			}
25541 			break;
25542 		case IPOPT_RR:
25543 			off = opt[IPOPT_OFFSET];
25544 			off--;
25545 			if (optlen < IP_ADDR_LEN ||
25546 			    off > optlen - IP_ADDR_LEN) {
25547 				/* No more room - ignore */
25548 				ip1dbg((
25549 				    "ip_wput_forward_options: end of RR\n"));
25550 				break;
25551 			}
25552 			dst = htonl(INADDR_LOOPBACK);
25553 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25554 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25555 			break;
25556 		case IPOPT_TS:
25557 			/* Insert timestamp if there is romm */
25558 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25559 			case IPOPT_TS_TSONLY:
25560 				off = IPOPT_TS_TIMELEN;
25561 				break;
25562 			case IPOPT_TS_PRESPEC:
25563 			case IPOPT_TS_PRESPEC_RFC791:
25564 				/* Verify that the address matched */
25565 				off = opt[IPOPT_OFFSET] - 1;
25566 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25567 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25568 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25569 				    ipst);
25570 				if (ire == NULL) {
25571 					/* Not for us */
25572 					break;
25573 				}
25574 				ire_refrele(ire);
25575 				/* FALLTHRU */
25576 			case IPOPT_TS_TSANDADDR:
25577 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25578 				break;
25579 			default:
25580 				/*
25581 				 * ip_*put_options should have already
25582 				 * dropped this packet.
25583 				 */
25584 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25585 				    "unknown IT - bug in ip_wput_options?\n");
25586 				return;	/* Keep "lint" happy */
25587 			}
25588 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25589 				/* Increase overflow counter */
25590 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25591 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25592 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25593 				    (off << 4);
25594 				break;
25595 			}
25596 			off = opt[IPOPT_OFFSET] - 1;
25597 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25598 			case IPOPT_TS_PRESPEC:
25599 			case IPOPT_TS_PRESPEC_RFC791:
25600 			case IPOPT_TS_TSANDADDR:
25601 				dst = htonl(INADDR_LOOPBACK);
25602 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25603 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25604 				/* FALLTHRU */
25605 			case IPOPT_TS_TSONLY:
25606 				off = opt[IPOPT_OFFSET] - 1;
25607 				/* Compute # of milliseconds since midnight */
25608 				gethrestime(&now);
25609 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25610 				    now.tv_nsec / (NANOSEC / MILLISEC);
25611 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25612 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25613 				break;
25614 			}
25615 			break;
25616 		}
25617 	}
25618 }
25619 
25620 /*
25621  * Send out a multicast packet on interface ipif.
25622  * The sender does not have an conn.
25623  * Caller verifies that this isn't a PHYI_LOOPBACK.
25624  */
25625 void
25626 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25627 {
25628 	ipha_t	*ipha;
25629 	ire_t	*ire;
25630 	ipaddr_t	dst;
25631 	mblk_t		*first_mp;
25632 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25633 
25634 	/* igmp_sendpkt always allocates a ipsec_out_t */
25635 	ASSERT(mp->b_datap->db_type == M_CTL);
25636 	ASSERT(!ipif->ipif_isv6);
25637 	ASSERT(!IS_LOOPBACK(ipif->ipif_ill));
25638 
25639 	first_mp = mp;
25640 	mp = first_mp->b_cont;
25641 	ASSERT(mp->b_datap->db_type == M_DATA);
25642 	ipha = (ipha_t *)mp->b_rptr;
25643 
25644 	/*
25645 	 * Find an IRE which matches the destination and the outgoing
25646 	 * queue (i.e. the outgoing interface.)
25647 	 */
25648 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25649 		dst = ipif->ipif_pp_dst_addr;
25650 	else
25651 		dst = ipha->ipha_dst;
25652 	/*
25653 	 * The source address has already been initialized by the
25654 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25655 	 * be sufficient rather than MATCH_IRE_IPIF.
25656 	 *
25657 	 * This function is used for sending IGMP packets. We need
25658 	 * to make sure that we send the packet out of the interface
25659 	 * (ipif->ipif_ill) where we joined the group. This is to
25660 	 * prevent from switches doing IGMP snooping to send us multicast
25661 	 * packets for a given group on the interface we have joined.
25662 	 * If we can't find an ire, igmp_sendpkt has already initialized
25663 	 * ipsec_out_attach_if so that this will not be load spread in
25664 	 * ip_newroute_ipif.
25665 	 */
25666 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25667 	    MATCH_IRE_ILL, ipst);
25668 	if (!ire) {
25669 		/*
25670 		 * Mark this packet to make it be delivered to
25671 		 * ip_wput_ire after the new ire has been
25672 		 * created.
25673 		 */
25674 		mp->b_prev = NULL;
25675 		mp->b_next = NULL;
25676 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25677 		    zoneid, &zero_info);
25678 		return;
25679 	}
25680 
25681 	/*
25682 	 * Honor the RTF_SETSRC flag; this is the only case
25683 	 * where we force this addr whatever the current src addr is,
25684 	 * because this address is set by igmp_sendpkt(), and
25685 	 * cannot be specified by any user.
25686 	 */
25687 	if (ire->ire_flags & RTF_SETSRC) {
25688 		ipha->ipha_src = ire->ire_src_addr;
25689 	}
25690 
25691 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25692 }
25693 
25694 /*
25695  * NOTE : This function does not ire_refrele the ire argument passed in.
25696  *
25697  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25698  * failure. The nce_fp_mp can vanish any time in the case of IRE_MIPRTUN
25699  * and IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25700  * the ire_lock to access the nce_fp_mp in this case.
25701  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25702  * prepending a fastpath message IPQoS processing must precede it, we also set
25703  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25704  * (IPQoS might have set the b_band for CoS marking).
25705  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25706  * must follow it so that IPQoS can mark the dl_priority field for CoS
25707  * marking, if needed.
25708  */
25709 static mblk_t *
25710 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
25711 {
25712 	uint_t	hlen;
25713 	ipha_t *ipha;
25714 	mblk_t *mp1;
25715 	boolean_t qos_done = B_FALSE;
25716 	uchar_t	*ll_hdr;
25717 	ip_stack_t	*ipst = ire->ire_ipst;
25718 
25719 #define	rptr	((uchar_t *)ipha)
25720 
25721 	ipha = (ipha_t *)mp->b_rptr;
25722 	hlen = 0;
25723 	LOCK_IRE_FP_MP(ire);
25724 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25725 		ASSERT(DB_TYPE(mp1) == M_DATA);
25726 		/* Initiate IPPF processing */
25727 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25728 			UNLOCK_IRE_FP_MP(ire);
25729 			ip_process(proc, &mp, ill_index);
25730 			if (mp == NULL)
25731 				return (NULL);
25732 
25733 			ipha = (ipha_t *)mp->b_rptr;
25734 			LOCK_IRE_FP_MP(ire);
25735 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25736 				qos_done = B_TRUE;
25737 				goto no_fp_mp;
25738 			}
25739 			ASSERT(DB_TYPE(mp1) == M_DATA);
25740 		}
25741 		hlen = MBLKL(mp1);
25742 		/*
25743 		 * Check if we have enough room to prepend fastpath
25744 		 * header
25745 		 */
25746 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25747 			ll_hdr = rptr - hlen;
25748 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25749 			/*
25750 			 * Set the b_rptr to the start of the link layer
25751 			 * header
25752 			 */
25753 			mp->b_rptr = ll_hdr;
25754 			mp1 = mp;
25755 		} else {
25756 			mp1 = copyb(mp1);
25757 			if (mp1 == NULL)
25758 				goto unlock_err;
25759 			mp1->b_band = mp->b_band;
25760 			mp1->b_cont = mp;
25761 			/*
25762 			 * certain system generated traffic may not
25763 			 * have cred/label in ip header block. This
25764 			 * is true even for a labeled system. But for
25765 			 * labeled traffic, inherit the label in the
25766 			 * new header.
25767 			 */
25768 			if (DB_CRED(mp) != NULL)
25769 				mblk_setcred(mp1, DB_CRED(mp));
25770 			/*
25771 			 * XXX disable ICK_VALID and compute checksum
25772 			 * here; can happen if nce_fp_mp changes and
25773 			 * it can't be copied now due to insufficient
25774 			 * space. (unlikely, fp mp can change, but it
25775 			 * does not increase in length)
25776 			 */
25777 		}
25778 		UNLOCK_IRE_FP_MP(ire);
25779 	} else {
25780 no_fp_mp:
25781 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25782 		if (mp1 == NULL) {
25783 unlock_err:
25784 			UNLOCK_IRE_FP_MP(ire);
25785 			freemsg(mp);
25786 			return (NULL);
25787 		}
25788 		UNLOCK_IRE_FP_MP(ire);
25789 		mp1->b_cont = mp;
25790 		/*
25791 		 * certain system generated traffic may not
25792 		 * have cred/label in ip header block. This
25793 		 * is true even for a labeled system. But for
25794 		 * labeled traffic, inherit the label in the
25795 		 * new header.
25796 		 */
25797 		if (DB_CRED(mp) != NULL)
25798 			mblk_setcred(mp1, DB_CRED(mp));
25799 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25800 			ip_process(proc, &mp1, ill_index);
25801 			if (mp1 == NULL)
25802 				return (NULL);
25803 		}
25804 	}
25805 	return (mp1);
25806 #undef rptr
25807 }
25808 
25809 /*
25810  * Finish the outbound IPsec processing for an IPv6 packet. This function
25811  * is called from ipsec_out_process() if the IPsec packet was processed
25812  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25813  * asynchronously.
25814  */
25815 void
25816 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25817     ire_t *ire_arg)
25818 {
25819 	in6_addr_t *v6dstp;
25820 	ire_t *ire;
25821 	mblk_t *mp;
25822 	ip6_t *ip6h1;
25823 	uint_t	ill_index;
25824 	ipsec_out_t *io;
25825 	boolean_t attach_if, hwaccel;
25826 	uint32_t flags = IP6_NO_IPPOLICY;
25827 	int match_flags;
25828 	zoneid_t zoneid;
25829 	boolean_t ill_need_rele = B_FALSE;
25830 	boolean_t ire_need_rele = B_FALSE;
25831 	ip_stack_t	*ipst;
25832 
25833 	mp = ipsec_mp->b_cont;
25834 	ip6h1 = (ip6_t *)mp->b_rptr;
25835 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25836 	ASSERT(io->ipsec_out_ns != NULL);
25837 	ipst = io->ipsec_out_ns->netstack_ip;
25838 	ill_index = io->ipsec_out_ill_index;
25839 	if (io->ipsec_out_reachable) {
25840 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25841 	}
25842 	attach_if = io->ipsec_out_attach_if;
25843 	hwaccel = io->ipsec_out_accelerated;
25844 	zoneid = io->ipsec_out_zoneid;
25845 	ASSERT(zoneid != ALL_ZONES);
25846 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25847 	/* Multicast addresses should have non-zero ill_index. */
25848 	v6dstp = &ip6h->ip6_dst;
25849 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25850 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25851 	ASSERT(!attach_if || ill_index != 0);
25852 	if (ill_index != 0) {
25853 		if (ill == NULL) {
25854 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
25855 			    B_TRUE, ipst);
25856 
25857 			/* Failure case frees things for us. */
25858 			if (ill == NULL)
25859 				return;
25860 
25861 			ill_need_rele = B_TRUE;
25862 		}
25863 		/*
25864 		 * If this packet needs to go out on a particular interface
25865 		 * honor it.
25866 		 */
25867 		if (attach_if) {
25868 			match_flags = MATCH_IRE_ILL;
25869 
25870 			/*
25871 			 * Check if we need an ire that will not be
25872 			 * looked up by anybody else i.e. HIDDEN.
25873 			 */
25874 			if (ill_is_probeonly(ill)) {
25875 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25876 			}
25877 		}
25878 	}
25879 	ASSERT(mp != NULL);
25880 
25881 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25882 		boolean_t unspec_src;
25883 		ipif_t	*ipif;
25884 
25885 		/*
25886 		 * Use the ill_index to get the right ill.
25887 		 */
25888 		unspec_src = io->ipsec_out_unspec_src;
25889 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25890 		if (ipif == NULL) {
25891 			if (ill_need_rele)
25892 				ill_refrele(ill);
25893 			freemsg(ipsec_mp);
25894 			return;
25895 		}
25896 
25897 		if (ire_arg != NULL) {
25898 			ire = ire_arg;
25899 		} else {
25900 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25901 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25902 			ire_need_rele = B_TRUE;
25903 		}
25904 		if (ire != NULL) {
25905 			ipif_refrele(ipif);
25906 			/*
25907 			 * XXX Do the multicast forwarding now, as the IPSEC
25908 			 * processing has been done.
25909 			 */
25910 			goto send;
25911 		}
25912 
25913 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25914 		mp->b_prev = NULL;
25915 		mp->b_next = NULL;
25916 
25917 		/*
25918 		 * If the IPsec packet was processed asynchronously,
25919 		 * drop it now.
25920 		 */
25921 		if (q == NULL) {
25922 			if (ill_need_rele)
25923 				ill_refrele(ill);
25924 			freemsg(ipsec_mp);
25925 			return;
25926 		}
25927 
25928 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
25929 		    unspec_src, zoneid);
25930 		ipif_refrele(ipif);
25931 	} else {
25932 		if (attach_if) {
25933 			ipif_t	*ipif;
25934 
25935 			ipif = ipif_get_next_ipif(NULL, ill);
25936 			if (ipif == NULL) {
25937 				if (ill_need_rele)
25938 					ill_refrele(ill);
25939 				freemsg(ipsec_mp);
25940 				return;
25941 			}
25942 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25943 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25944 			ire_need_rele = B_TRUE;
25945 			ipif_refrele(ipif);
25946 		} else {
25947 			if (ire_arg != NULL) {
25948 				ire = ire_arg;
25949 			} else {
25950 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL,
25951 				    ipst);
25952 				ire_need_rele = B_TRUE;
25953 			}
25954 		}
25955 		if (ire != NULL)
25956 			goto send;
25957 		/*
25958 		 * ire disappeared underneath.
25959 		 *
25960 		 * What we need to do here is the ip_newroute
25961 		 * logic to get the ire without doing the IPSEC
25962 		 * processing. Follow the same old path. But this
25963 		 * time, ip_wput or ire_add_then_send will call us
25964 		 * directly as all the IPSEC operations are done.
25965 		 */
25966 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25967 		mp->b_prev = NULL;
25968 		mp->b_next = NULL;
25969 
25970 		/*
25971 		 * If the IPsec packet was processed asynchronously,
25972 		 * drop it now.
25973 		 */
25974 		if (q == NULL) {
25975 			if (ill_need_rele)
25976 				ill_refrele(ill);
25977 			freemsg(ipsec_mp);
25978 			return;
25979 		}
25980 
25981 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25982 		    zoneid, ipst);
25983 	}
25984 	if (ill != NULL && ill_need_rele)
25985 		ill_refrele(ill);
25986 	return;
25987 send:
25988 	if (ill != NULL && ill_need_rele)
25989 		ill_refrele(ill);
25990 
25991 	/* Local delivery */
25992 	if (ire->ire_stq == NULL) {
25993 		ill_t	*out_ill;
25994 		ASSERT(q != NULL);
25995 
25996 		/* PFHooks: LOOPBACK_OUT */
25997 		out_ill = ire->ire_ipif->ipif_ill;
25998 
25999 		DTRACE_PROBE4(ip6__loopback__out__start,
26000 		    ill_t *, NULL, ill_t *, out_ill,
26001 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
26002 
26003 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
26004 		    ipst->ips_ipv6firewall_loopback_out,
26005 		    NULL, out_ill, ip6h1, ipsec_mp, mp, ipst);
26006 
26007 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
26008 
26009 		if (ipsec_mp != NULL)
26010 			ip_wput_local_v6(RD(q), out_ill,
26011 			    ip6h, ipsec_mp, ire, 0);
26012 		if (ire_need_rele)
26013 			ire_refrele(ire);
26014 		return;
26015 	}
26016 	/*
26017 	 * Everything is done. Send it out on the wire.
26018 	 * We force the insertion of a fragment header using the
26019 	 * IPH_FRAG_HDR flag in two cases:
26020 	 * - after reception of an ICMPv6 "packet too big" message
26021 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
26022 	 * - for multirouted IPv6 packets, so that the receiver can
26023 	 *   discard duplicates according to their fragment identifier
26024 	 */
26025 	/* XXX fix flow control problems. */
26026 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
26027 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
26028 		if (hwaccel) {
26029 			/*
26030 			 * hardware acceleration does not handle these
26031 			 * "slow path" cases.
26032 			 */
26033 			/* IPsec KSTATS: should bump bean counter here. */
26034 			if (ire_need_rele)
26035 				ire_refrele(ire);
26036 			freemsg(ipsec_mp);
26037 			return;
26038 		}
26039 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
26040 		    (mp->b_cont ? msgdsize(mp) :
26041 		    mp->b_wptr - (uchar_t *)ip6h)) {
26042 			/* IPsec KSTATS: should bump bean counter here. */
26043 			ip0dbg(("Packet length mismatch: %d, %ld\n",
26044 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
26045 			    msgdsize(mp)));
26046 			if (ire_need_rele)
26047 				ire_refrele(ire);
26048 			freemsg(ipsec_mp);
26049 			return;
26050 		}
26051 		ASSERT(mp->b_prev == NULL);
26052 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
26053 		    ntohs(ip6h->ip6_plen) +
26054 		    IPV6_HDR_LEN, ire->ire_max_frag));
26055 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
26056 		    ire->ire_max_frag);
26057 	} else {
26058 		UPDATE_OB_PKT_COUNT(ire);
26059 		ire->ire_last_used_time = lbolt;
26060 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
26061 	}
26062 	if (ire_need_rele)
26063 		ire_refrele(ire);
26064 	freeb(ipsec_mp);
26065 }
26066 
26067 void
26068 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
26069 {
26070 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
26071 	da_ipsec_t *hada;	/* data attributes */
26072 	ill_t *ill = (ill_t *)q->q_ptr;
26073 
26074 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
26075 
26076 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
26077 		/* IPsec KSTATS: Bump lose counter here! */
26078 		freemsg(mp);
26079 		return;
26080 	}
26081 
26082 	/*
26083 	 * It's an IPsec packet that must be
26084 	 * accelerated by the Provider, and the
26085 	 * outbound ill is IPsec acceleration capable.
26086 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
26087 	 * to the ill.
26088 	 * IPsec KSTATS: should bump packet counter here.
26089 	 */
26090 
26091 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
26092 	if (hada_mp == NULL) {
26093 		/* IPsec KSTATS: should bump packet counter here. */
26094 		freemsg(mp);
26095 		return;
26096 	}
26097 
26098 	hada_mp->b_datap->db_type = M_CTL;
26099 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
26100 	hada_mp->b_cont = mp;
26101 
26102 	hada = (da_ipsec_t *)hada_mp->b_rptr;
26103 	bzero(hada, sizeof (da_ipsec_t));
26104 	hada->da_type = IPHADA_M_CTL;
26105 
26106 	putnext(q, hada_mp);
26107 }
26108 
26109 /*
26110  * Finish the outbound IPsec processing. This function is called from
26111  * ipsec_out_process() if the IPsec packet was processed
26112  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
26113  * asynchronously.
26114  */
26115 void
26116 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
26117     ire_t *ire_arg)
26118 {
26119 	uint32_t v_hlen_tos_len;
26120 	ipaddr_t	dst;
26121 	ipif_t	*ipif = NULL;
26122 	ire_t *ire;
26123 	ire_t *ire1 = NULL;
26124 	mblk_t *next_mp = NULL;
26125 	uint32_t max_frag;
26126 	boolean_t multirt_send = B_FALSE;
26127 	mblk_t *mp;
26128 	mblk_t *mp1;
26129 	ipha_t *ipha1;
26130 	uint_t	ill_index;
26131 	ipsec_out_t *io;
26132 	boolean_t attach_if;
26133 	int match_flags, offset;
26134 	irb_t *irb = NULL;
26135 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
26136 	zoneid_t zoneid;
26137 	uint32_t cksum;
26138 	uint16_t *up;
26139 	ipxmit_state_t	pktxmit_state;
26140 	ip_stack_t	*ipst;
26141 
26142 #ifdef	_BIG_ENDIAN
26143 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
26144 #else
26145 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
26146 #endif
26147 
26148 	mp = ipsec_mp->b_cont;
26149 	ipha1 = (ipha_t *)mp->b_rptr;
26150 	ASSERT(mp != NULL);
26151 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
26152 	dst = ipha->ipha_dst;
26153 
26154 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26155 	ill_index = io->ipsec_out_ill_index;
26156 	attach_if = io->ipsec_out_attach_if;
26157 	zoneid = io->ipsec_out_zoneid;
26158 	ASSERT(zoneid != ALL_ZONES);
26159 	ipst = io->ipsec_out_ns->netstack_ip;
26160 	ASSERT(io->ipsec_out_ns != NULL);
26161 
26162 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
26163 	if (ill_index != 0) {
26164 		if (ill == NULL) {
26165 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
26166 			    ill_index, B_FALSE, ipst);
26167 
26168 			/* Failure case frees things for us. */
26169 			if (ill == NULL)
26170 				return;
26171 
26172 			ill_need_rele = B_TRUE;
26173 		}
26174 		/*
26175 		 * If this packet needs to go out on a particular interface
26176 		 * honor it.
26177 		 */
26178 		if (attach_if) {
26179 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
26180 
26181 			/*
26182 			 * Check if we need an ire that will not be
26183 			 * looked up by anybody else i.e. HIDDEN.
26184 			 */
26185 			if (ill_is_probeonly(ill)) {
26186 				match_flags |= MATCH_IRE_MARK_HIDDEN;
26187 			}
26188 		}
26189 	}
26190 
26191 	if (CLASSD(dst)) {
26192 		boolean_t conn_dontroute;
26193 		/*
26194 		 * Use the ill_index to get the right ipif.
26195 		 */
26196 		conn_dontroute = io->ipsec_out_dontroute;
26197 		if (ill_index == 0)
26198 			ipif = ipif_lookup_group(dst, zoneid, ipst);
26199 		else
26200 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
26201 		if (ipif == NULL) {
26202 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
26203 			    " multicast\n"));
26204 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
26205 			freemsg(ipsec_mp);
26206 			goto done;
26207 		}
26208 		/*
26209 		 * ipha_src has already been intialized with the
26210 		 * value of the ipif in ip_wput. All we need now is
26211 		 * an ire to send this downstream.
26212 		 */
26213 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
26214 		    MBLK_GETLABEL(mp), match_flags, ipst);
26215 		if (ire != NULL) {
26216 			ill_t *ill1;
26217 			/*
26218 			 * Do the multicast forwarding now, as the IPSEC
26219 			 * processing has been done.
26220 			 */
26221 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
26222 			    (ill1 = ire_to_ill(ire))) {
26223 				if (ip_mforward(ill1, ipha, mp)) {
26224 					freemsg(ipsec_mp);
26225 					ip1dbg(("ip_wput_ipsec_out: mforward "
26226 					    "failed\n"));
26227 					ire_refrele(ire);
26228 					goto done;
26229 				}
26230 			}
26231 			goto send;
26232 		}
26233 
26234 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
26235 		mp->b_prev = NULL;
26236 		mp->b_next = NULL;
26237 
26238 		/*
26239 		 * If the IPsec packet was processed asynchronously,
26240 		 * drop it now.
26241 		 */
26242 		if (q == NULL) {
26243 			freemsg(ipsec_mp);
26244 			goto done;
26245 		}
26246 
26247 		/*
26248 		 * We may be using a wrong ipif to create the ire.
26249 		 * But it is okay as the source address is assigned
26250 		 * for the packet already. Next outbound packet would
26251 		 * create the IRE with the right IPIF in ip_wput.
26252 		 *
26253 		 * Also handle RTF_MULTIRT routes.
26254 		 */
26255 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
26256 		    zoneid, &zero_info);
26257 	} else {
26258 		if (attach_if) {
26259 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
26260 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
26261 		} else {
26262 			if (ire_arg != NULL) {
26263 				ire = ire_arg;
26264 				ire_need_rele = B_FALSE;
26265 			} else {
26266 				ire = ire_cache_lookup(dst, zoneid,
26267 				    MBLK_GETLABEL(mp), ipst);
26268 			}
26269 		}
26270 		if (ire != NULL) {
26271 			goto send;
26272 		}
26273 
26274 		/*
26275 		 * ire disappeared underneath.
26276 		 *
26277 		 * What we need to do here is the ip_newroute
26278 		 * logic to get the ire without doing the IPSEC
26279 		 * processing. Follow the same old path. But this
26280 		 * time, ip_wput or ire_add_then_put will call us
26281 		 * directly as all the IPSEC operations are done.
26282 		 */
26283 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
26284 		mp->b_prev = NULL;
26285 		mp->b_next = NULL;
26286 
26287 		/*
26288 		 * If the IPsec packet was processed asynchronously,
26289 		 * drop it now.
26290 		 */
26291 		if (q == NULL) {
26292 			freemsg(ipsec_mp);
26293 			goto done;
26294 		}
26295 
26296 		/*
26297 		 * Since we're going through ip_newroute() again, we
26298 		 * need to make sure we don't:
26299 		 *
26300 		 *	1.) Trigger the ASSERT() with the ipha_ident
26301 		 *	    overloading.
26302 		 *	2.) Redo transport-layer checksumming, since we've
26303 		 *	    already done all that to get this far.
26304 		 *
26305 		 * The easiest way not do either of the above is to set
26306 		 * the ipha_ident field to IP_HDR_INCLUDED.
26307 		 */
26308 		ipha->ipha_ident = IP_HDR_INCLUDED;
26309 		ip_newroute(q, ipsec_mp, dst, NULL,
26310 		    (CONN_Q(q) ? Q_TO_CONN(q) : NULL), zoneid, ipst);
26311 	}
26312 	goto done;
26313 send:
26314 	if (ipha->ipha_protocol == IPPROTO_UDP &&
26315 	    udp_compute_checksum(ipst->ips_netstack)) {
26316 		/*
26317 		 * ESP NAT-Traversal packet.
26318 		 *
26319 		 * Just do software checksum for now.
26320 		 */
26321 
26322 		offset = IP_SIMPLE_HDR_LENGTH + UDP_CHECKSUM_OFFSET;
26323 		IP_STAT(ipst, ip_out_sw_cksum);
26324 		IP_STAT_UPDATE(ipst, ip_udp_out_sw_cksum_bytes,
26325 		    ntohs(htons(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH));
26326 #define	iphs	((uint16_t *)ipha)
26327 		cksum = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
26328 		    iphs[9] + ntohs(htons(ipha->ipha_length) -
26329 		    IP_SIMPLE_HDR_LENGTH);
26330 #undef iphs
26331 		cksum = IP_CSUM(mp, IP_SIMPLE_HDR_LENGTH, cksum);
26332 		for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont)
26333 			if (mp1->b_wptr - mp1->b_rptr >=
26334 			    offset + sizeof (uint16_t)) {
26335 				up = (uint16_t *)(mp1->b_rptr + offset);
26336 				*up = cksum;
26337 				break;	/* out of for loop */
26338 			} else {
26339 				offset -= (mp->b_wptr - mp->b_rptr);
26340 			}
26341 	} /* Otherwise, just keep the all-zero checksum. */
26342 
26343 	if (ire->ire_stq == NULL) {
26344 		ill_t	*out_ill;
26345 		/*
26346 		 * Loopbacks go through ip_wput_local except for one case.
26347 		 * We come here if we generate a icmp_frag_needed message
26348 		 * after IPSEC processing is over. When this function calls
26349 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
26350 		 * icmp_frag_needed. The message generated comes back here
26351 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
26352 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
26353 		 * source address as it is usually set in ip_wput_ire. As
26354 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
26355 		 * and we end up here. We can't enter ip_wput_ire once the
26356 		 * IPSEC processing is over and hence we need to do it here.
26357 		 */
26358 		ASSERT(q != NULL);
26359 		UPDATE_OB_PKT_COUNT(ire);
26360 		ire->ire_last_used_time = lbolt;
26361 		if (ipha->ipha_src == 0)
26362 			ipha->ipha_src = ire->ire_src_addr;
26363 
26364 		/* PFHooks: LOOPBACK_OUT */
26365 		out_ill = ire->ire_ipif->ipif_ill;
26366 
26367 		DTRACE_PROBE4(ip4__loopback__out__start,
26368 		    ill_t *, NULL, ill_t *, out_ill,
26369 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
26370 
26371 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
26372 		    ipst->ips_ipv4firewall_loopback_out,
26373 		    NULL, out_ill, ipha1, ipsec_mp, mp, ipst);
26374 
26375 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
26376 
26377 		if (ipsec_mp != NULL)
26378 			ip_wput_local(RD(q), out_ill,
26379 			    ipha, ipsec_mp, ire, 0, zoneid);
26380 		if (ire_need_rele)
26381 			ire_refrele(ire);
26382 		goto done;
26383 	}
26384 
26385 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
26386 		/*
26387 		 * We are through with IPSEC processing.
26388 		 * Fragment this and send it on the wire.
26389 		 */
26390 		if (io->ipsec_out_accelerated) {
26391 			/*
26392 			 * The packet has been accelerated but must
26393 			 * be fragmented. This should not happen
26394 			 * since AH and ESP must not accelerate
26395 			 * packets that need fragmentation, however
26396 			 * the configuration could have changed
26397 			 * since the AH or ESP processing.
26398 			 * Drop packet.
26399 			 * IPsec KSTATS: bump bean counter here.
26400 			 */
26401 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
26402 			    "fragmented accelerated packet!\n"));
26403 			freemsg(ipsec_mp);
26404 		} else {
26405 			ip_wput_ire_fragmentit(ipsec_mp, ire, zoneid, ipst);
26406 		}
26407 		if (ire_need_rele)
26408 			ire_refrele(ire);
26409 		goto done;
26410 	}
26411 
26412 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
26413 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
26414 	    (void *)ire->ire_ipif, (void *)ipif));
26415 
26416 	/*
26417 	 * Multiroute the secured packet, unless IPsec really
26418 	 * requires the packet to go out only through a particular
26419 	 * interface.
26420 	 */
26421 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
26422 		ire_t *first_ire;
26423 		irb = ire->ire_bucket;
26424 		ASSERT(irb != NULL);
26425 		/*
26426 		 * This ire has been looked up as the one that
26427 		 * goes through the given ipif;
26428 		 * make sure we do not omit any other multiroute ire
26429 		 * that may be present in the bucket before this one.
26430 		 */
26431 		IRB_REFHOLD(irb);
26432 		for (first_ire = irb->irb_ire;
26433 		    first_ire != NULL;
26434 		    first_ire = first_ire->ire_next) {
26435 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
26436 			    (first_ire->ire_addr == ire->ire_addr) &&
26437 			    !(first_ire->ire_marks &
26438 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
26439 				break;
26440 			}
26441 		}
26442 
26443 		if ((first_ire != NULL) && (first_ire != ire)) {
26444 			/*
26445 			 * Don't change the ire if the packet must
26446 			 * be fragmented if sent via this new one.
26447 			 */
26448 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26449 				IRE_REFHOLD(first_ire);
26450 				if (ire_need_rele)
26451 					ire_refrele(ire);
26452 				else
26453 					ire_need_rele = B_TRUE;
26454 				ire = first_ire;
26455 			}
26456 		}
26457 		IRB_REFRELE(irb);
26458 
26459 		multirt_send = B_TRUE;
26460 		max_frag = ire->ire_max_frag;
26461 	} else {
26462 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
26463 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
26464 			    "flag, attach_if %d\n", attach_if));
26465 		}
26466 	}
26467 
26468 	/*
26469 	 * In most cases, the emission loop below is entered only once.
26470 	 * Only in the case where the ire holds the RTF_MULTIRT
26471 	 * flag, we loop to process all RTF_MULTIRT ires in the
26472 	 * bucket, and send the packet through all crossed
26473 	 * RTF_MULTIRT routes.
26474 	 */
26475 	do {
26476 		if (multirt_send) {
26477 			/*
26478 			 * ire1 holds here the next ire to process in the
26479 			 * bucket. If multirouting is expected,
26480 			 * any non-RTF_MULTIRT ire that has the
26481 			 * right destination address is ignored.
26482 			 */
26483 			ASSERT(irb != NULL);
26484 			IRB_REFHOLD(irb);
26485 			for (ire1 = ire->ire_next;
26486 			    ire1 != NULL;
26487 			    ire1 = ire1->ire_next) {
26488 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26489 					continue;
26490 				if (ire1->ire_addr != ire->ire_addr)
26491 					continue;
26492 				if (ire1->ire_marks &
26493 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
26494 					continue;
26495 				/* No loopback here */
26496 				if (ire1->ire_stq == NULL)
26497 					continue;
26498 				/*
26499 				 * Ensure we do not exceed the MTU
26500 				 * of the next route.
26501 				 */
26502 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26503 					ip_multirt_bad_mtu(ire1, max_frag);
26504 					continue;
26505 				}
26506 
26507 				IRE_REFHOLD(ire1);
26508 				break;
26509 			}
26510 			IRB_REFRELE(irb);
26511 			if (ire1 != NULL) {
26512 				/*
26513 				 * We are in a multiple send case, need to
26514 				 * make a copy of the packet.
26515 				 */
26516 				next_mp = copymsg(ipsec_mp);
26517 				if (next_mp == NULL) {
26518 					ire_refrele(ire1);
26519 					ire1 = NULL;
26520 				}
26521 			}
26522 		}
26523 		/*
26524 		 * Everything is done. Send it out on the wire
26525 		 *
26526 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26527 		 * either send it on the wire or, in the case of
26528 		 * HW acceleration, call ipsec_hw_putnext.
26529 		 */
26530 		if (ire->ire_nce &&
26531 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26532 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26533 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26534 			/*
26535 			 * If ire's link-layer is unresolved (this
26536 			 * would only happen if the incomplete ire
26537 			 * was added to cachetable via forwarding path)
26538 			 * don't bother going to ip_xmit_v4. Just drop the
26539 			 * packet.
26540 			 * There is a slight risk here, in that, if we
26541 			 * have the forwarding path create an incomplete
26542 			 * IRE, then until the IRE is completed, any
26543 			 * transmitted IPSEC packets will be dropped
26544 			 * instead of being queued waiting for resolution.
26545 			 *
26546 			 * But the likelihood of a forwarding packet and a wput
26547 			 * packet sending to the same dst at the same time
26548 			 * and there not yet be an ARP entry for it is small.
26549 			 * Furthermore, if this actually happens, it might
26550 			 * be likely that wput would generate multiple
26551 			 * packets (and forwarding would also have a train
26552 			 * of packets) for that destination. If this is
26553 			 * the case, some of them would have been dropped
26554 			 * anyway, since ARP only queues a few packets while
26555 			 * waiting for resolution
26556 			 *
26557 			 * NOTE: We should really call ip_xmit_v4,
26558 			 * and let it queue the packet and send the
26559 			 * ARP query and have ARP come back thus:
26560 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26561 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26562 			 * hw accel work. But it's too complex to get
26563 			 * the IPsec hw  acceleration approach to fit
26564 			 * well with ip_xmit_v4 doing ARP without
26565 			 * doing IPSEC simplification. For now, we just
26566 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26567 			 * that we can continue with the send on the next
26568 			 * attempt.
26569 			 *
26570 			 * XXX THis should be revisited, when
26571 			 * the IPsec/IP interaction is cleaned up
26572 			 */
26573 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26574 			    " - dropping packet\n"));
26575 			freemsg(ipsec_mp);
26576 			/*
26577 			 * Call ip_xmit_v4() to trigger ARP query
26578 			 * in case the nce_state is ND_INITIAL
26579 			 */
26580 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
26581 			goto drop_pkt;
26582 		}
26583 
26584 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26585 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26586 		    mblk_t *, ipsec_mp);
26587 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26588 		    ipst->ips_ipv4firewall_physical_out,
26589 		    NULL, ire->ire_ipif->ipif_ill, ipha1, ipsec_mp, mp, ipst);
26590 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, ipsec_mp);
26591 		if (ipsec_mp == NULL)
26592 			goto drop_pkt;
26593 
26594 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26595 		pktxmit_state = ip_xmit_v4(mp, ire,
26596 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE);
26597 
26598 		if ((pktxmit_state ==  SEND_FAILED) ||
26599 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26600 
26601 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26602 drop_pkt:
26603 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26604 			    ipIfStatsOutDiscards);
26605 			if (ire_need_rele)
26606 				ire_refrele(ire);
26607 			if (ire1 != NULL) {
26608 				ire_refrele(ire1);
26609 				freemsg(next_mp);
26610 			}
26611 			goto done;
26612 		}
26613 
26614 		freeb(ipsec_mp);
26615 		if (ire_need_rele)
26616 			ire_refrele(ire);
26617 
26618 		if (ire1 != NULL) {
26619 			ire = ire1;
26620 			ire_need_rele = B_TRUE;
26621 			ASSERT(next_mp);
26622 			ipsec_mp = next_mp;
26623 			mp = ipsec_mp->b_cont;
26624 			ire1 = NULL;
26625 			next_mp = NULL;
26626 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26627 		} else {
26628 			multirt_send = B_FALSE;
26629 		}
26630 	} while (multirt_send);
26631 done:
26632 	if (ill != NULL && ill_need_rele)
26633 		ill_refrele(ill);
26634 	if (ipif != NULL)
26635 		ipif_refrele(ipif);
26636 }
26637 
26638 /*
26639  * Get the ill corresponding to the specified ire, and compare its
26640  * capabilities with the protocol and algorithms specified by the
26641  * the SA obtained from ipsec_out. If they match, annotate the
26642  * ipsec_out structure to indicate that the packet needs acceleration.
26643  *
26644  *
26645  * A packet is eligible for outbound hardware acceleration if the
26646  * following conditions are satisfied:
26647  *
26648  * 1. the packet will not be fragmented
26649  * 2. the provider supports the algorithm
26650  * 3. there is no pending control message being exchanged
26651  * 4. snoop is not attached
26652  * 5. the destination address is not a broadcast or multicast address.
26653  *
26654  * Rationale:
26655  *	- Hardware drivers do not support fragmentation with
26656  *	  the current interface.
26657  *	- snoop, multicast, and broadcast may result in exposure of
26658  *	  a cleartext datagram.
26659  * We check all five of these conditions here.
26660  *
26661  * XXX would like to nuke "ire_t *" parameter here; problem is that
26662  * IRE is only way to figure out if a v4 address is a broadcast and
26663  * thus ineligible for acceleration...
26664  */
26665 static void
26666 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26667 {
26668 	ipsec_out_t *io;
26669 	mblk_t *data_mp;
26670 	uint_t plen, overhead;
26671 	ip_stack_t	*ipst;
26672 
26673 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26674 		return;
26675 
26676 	if (ill == NULL)
26677 		return;
26678 	ipst = ill->ill_ipst;
26679 	/*
26680 	 * Destination address is a broadcast or multicast.  Punt.
26681 	 */
26682 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26683 	    IRE_LOCAL)))
26684 		return;
26685 
26686 	data_mp = ipsec_mp->b_cont;
26687 
26688 	if (ill->ill_isv6) {
26689 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26690 
26691 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26692 			return;
26693 
26694 		plen = ip6h->ip6_plen;
26695 	} else {
26696 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26697 
26698 		if (CLASSD(ipha->ipha_dst))
26699 			return;
26700 
26701 		plen = ipha->ipha_length;
26702 	}
26703 	/*
26704 	 * Is there a pending DLPI control message being exchanged
26705 	 * between IP/IPsec and the DLS Provider? If there is, it
26706 	 * could be a SADB update, and the state of the DLS Provider
26707 	 * SADB might not be in sync with the SADB maintained by
26708 	 * IPsec. To avoid dropping packets or using the wrong keying
26709 	 * material, we do not accelerate this packet.
26710 	 */
26711 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26712 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26713 		    "ill_dlpi_pending! don't accelerate packet\n"));
26714 		return;
26715 	}
26716 
26717 	/*
26718 	 * Is the Provider in promiscous mode? If it does, we don't
26719 	 * accelerate the packet since it will bounce back up to the
26720 	 * listeners in the clear.
26721 	 */
26722 	if (ill->ill_promisc_on_phys) {
26723 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26724 		    "ill in promiscous mode, don't accelerate packet\n"));
26725 		return;
26726 	}
26727 
26728 	/*
26729 	 * Will the packet require fragmentation?
26730 	 */
26731 
26732 	/*
26733 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26734 	 * as is used elsewhere.
26735 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26736 	 *	+ 2-byte trailer
26737 	 */
26738 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26739 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26740 
26741 	if ((plen + overhead) > ill->ill_max_mtu)
26742 		return;
26743 
26744 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26745 
26746 	/*
26747 	 * Can the ill accelerate this IPsec protocol and algorithm
26748 	 * specified by the SA?
26749 	 */
26750 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26751 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26752 		return;
26753 	}
26754 
26755 	/*
26756 	 * Tell AH or ESP that the outbound ill is capable of
26757 	 * accelerating this packet.
26758 	 */
26759 	io->ipsec_out_is_capab_ill = B_TRUE;
26760 }
26761 
26762 /*
26763  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26764  *
26765  * If this function returns B_TRUE, the requested SA's have been filled
26766  * into the ipsec_out_*_sa pointers.
26767  *
26768  * If the function returns B_FALSE, the packet has been "consumed", most
26769  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26770  *
26771  * The SA references created by the protocol-specific "select"
26772  * function will be released when the ipsec_mp is freed, thanks to the
26773  * ipsec_out_free destructor -- see spd.c.
26774  */
26775 static boolean_t
26776 ipsec_out_select_sa(mblk_t *ipsec_mp)
26777 {
26778 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26779 	ipsec_out_t *io;
26780 	ipsec_policy_t *pp;
26781 	ipsec_action_t *ap;
26782 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26783 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26784 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26785 
26786 	if (!io->ipsec_out_secure) {
26787 		/*
26788 		 * We came here by mistake.
26789 		 * Don't bother with ipsec processing
26790 		 * We should "discourage" this path in the future.
26791 		 */
26792 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26793 		return (B_FALSE);
26794 	}
26795 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26796 	ASSERT((io->ipsec_out_policy != NULL) ||
26797 	    (io->ipsec_out_act != NULL));
26798 
26799 	ASSERT(io->ipsec_out_failed == B_FALSE);
26800 
26801 	/*
26802 	 * IPSEC processing has started.
26803 	 */
26804 	io->ipsec_out_proc_begin = B_TRUE;
26805 	ap = io->ipsec_out_act;
26806 	if (ap == NULL) {
26807 		pp = io->ipsec_out_policy;
26808 		ASSERT(pp != NULL);
26809 		ap = pp->ipsp_act;
26810 		ASSERT(ap != NULL);
26811 	}
26812 
26813 	/*
26814 	 * We have an action.  now, let's select SA's.
26815 	 * (In the future, we can cache this in the conn_t..)
26816 	 */
26817 	if (ap->ipa_want_esp) {
26818 		if (io->ipsec_out_esp_sa == NULL) {
26819 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26820 			    IPPROTO_ESP);
26821 		}
26822 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26823 	}
26824 
26825 	if (ap->ipa_want_ah) {
26826 		if (io->ipsec_out_ah_sa == NULL) {
26827 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26828 			    IPPROTO_AH);
26829 		}
26830 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26831 		/*
26832 		 * The ESP and AH processing order needs to be preserved
26833 		 * when both protocols are required (ESP should be applied
26834 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26835 		 * when both ESP and AH are required, and an AH ACQUIRE
26836 		 * is needed.
26837 		 */
26838 		if (ap->ipa_want_esp && need_ah_acquire)
26839 			need_esp_acquire = B_TRUE;
26840 	}
26841 
26842 	/*
26843 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26844 	 * Release SAs that got referenced, but will not be used until we
26845 	 * acquire _all_ of the SAs we need.
26846 	 */
26847 	if (need_ah_acquire || need_esp_acquire) {
26848 		if (io->ipsec_out_ah_sa != NULL) {
26849 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26850 			io->ipsec_out_ah_sa = NULL;
26851 		}
26852 		if (io->ipsec_out_esp_sa != NULL) {
26853 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26854 			io->ipsec_out_esp_sa = NULL;
26855 		}
26856 
26857 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26858 		return (B_FALSE);
26859 	}
26860 
26861 	return (B_TRUE);
26862 }
26863 
26864 /*
26865  * Process an IPSEC_OUT message and see what you can
26866  * do with it.
26867  * IPQoS Notes:
26868  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26869  * IPSec.
26870  * XXX would like to nuke ire_t.
26871  * XXX ill_index better be "real"
26872  */
26873 void
26874 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26875 {
26876 	ipsec_out_t *io;
26877 	ipsec_policy_t *pp;
26878 	ipsec_action_t *ap;
26879 	ipha_t *ipha;
26880 	ip6_t *ip6h;
26881 	mblk_t *mp;
26882 	ill_t *ill;
26883 	zoneid_t zoneid;
26884 	ipsec_status_t ipsec_rc;
26885 	boolean_t ill_need_rele = B_FALSE;
26886 	ip_stack_t	*ipst;
26887 	ipsec_stack_t	*ipss;
26888 
26889 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26890 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26891 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26892 	ipst = io->ipsec_out_ns->netstack_ip;
26893 	mp = ipsec_mp->b_cont;
26894 
26895 	/*
26896 	 * Initiate IPPF processing. We do it here to account for packets
26897 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26898 	 * We can check for ipsec_out_proc_begin even for such packets, as
26899 	 * they will always be false (asserted below).
26900 	 */
26901 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26902 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26903 		    io->ipsec_out_ill_index : ill_index);
26904 		if (mp == NULL) {
26905 			ip2dbg(("ipsec_out_process: packet dropped "\
26906 			    "during IPPF processing\n"));
26907 			freeb(ipsec_mp);
26908 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26909 			return;
26910 		}
26911 	}
26912 
26913 	if (!io->ipsec_out_secure) {
26914 		/*
26915 		 * We came here by mistake.
26916 		 * Don't bother with ipsec processing
26917 		 * Should "discourage" this path in the future.
26918 		 */
26919 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26920 		goto done;
26921 	}
26922 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26923 	ASSERT((io->ipsec_out_policy != NULL) ||
26924 	    (io->ipsec_out_act != NULL));
26925 	ASSERT(io->ipsec_out_failed == B_FALSE);
26926 
26927 	ipss = ipst->ips_netstack->netstack_ipsec;
26928 	if (!ipsec_loaded(ipss)) {
26929 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26930 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26931 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26932 		} else {
26933 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26934 		}
26935 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26936 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26937 		    &ipss->ipsec_dropper);
26938 		return;
26939 	}
26940 
26941 	/*
26942 	 * IPSEC processing has started.
26943 	 */
26944 	io->ipsec_out_proc_begin = B_TRUE;
26945 	ap = io->ipsec_out_act;
26946 	if (ap == NULL) {
26947 		pp = io->ipsec_out_policy;
26948 		ASSERT(pp != NULL);
26949 		ap = pp->ipsp_act;
26950 		ASSERT(ap != NULL);
26951 	}
26952 
26953 	/*
26954 	 * Save the outbound ill index. When the packet comes back
26955 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26956 	 * before sending it the accelerated packet.
26957 	 */
26958 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26959 		int ifindex;
26960 		ill = ire_to_ill(ire);
26961 		ifindex = ill->ill_phyint->phyint_ifindex;
26962 		io->ipsec_out_capab_ill_index = ifindex;
26963 	}
26964 
26965 	/*
26966 	 * The order of processing is first insert a IP header if needed.
26967 	 * Then insert the ESP header and then the AH header.
26968 	 */
26969 	if ((io->ipsec_out_se_done == B_FALSE) &&
26970 	    (ap->ipa_want_se)) {
26971 		/*
26972 		 * First get the outer IP header before sending
26973 		 * it to ESP.
26974 		 */
26975 		ipha_t *oipha, *iipha;
26976 		mblk_t *outer_mp, *inner_mp;
26977 
26978 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26979 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26980 			    "ipsec_out_process: "
26981 			    "Self-Encapsulation failed: Out of memory\n");
26982 			freemsg(ipsec_mp);
26983 			if (ill != NULL) {
26984 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26985 			} else {
26986 				BUMP_MIB(&ipst->ips_ip_mib,
26987 				    ipIfStatsOutDiscards);
26988 			}
26989 			return;
26990 		}
26991 		inner_mp = ipsec_mp->b_cont;
26992 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26993 		oipha = (ipha_t *)outer_mp->b_rptr;
26994 		iipha = (ipha_t *)inner_mp->b_rptr;
26995 		*oipha = *iipha;
26996 		outer_mp->b_wptr += sizeof (ipha_t);
26997 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26998 		    sizeof (ipha_t));
26999 		oipha->ipha_protocol = IPPROTO_ENCAP;
27000 		oipha->ipha_version_and_hdr_length =
27001 		    IP_SIMPLE_HDR_VERSION;
27002 		oipha->ipha_hdr_checksum = 0;
27003 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
27004 		outer_mp->b_cont = inner_mp;
27005 		ipsec_mp->b_cont = outer_mp;
27006 
27007 		io->ipsec_out_se_done = B_TRUE;
27008 		io->ipsec_out_tunnel = B_TRUE;
27009 	}
27010 
27011 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
27012 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
27013 	    !ipsec_out_select_sa(ipsec_mp))
27014 		return;
27015 
27016 	/*
27017 	 * By now, we know what SA's to use.  Toss over to ESP & AH
27018 	 * to do the heavy lifting.
27019 	 */
27020 	zoneid = io->ipsec_out_zoneid;
27021 	ASSERT(zoneid != ALL_ZONES);
27022 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
27023 		ASSERT(io->ipsec_out_esp_sa != NULL);
27024 		io->ipsec_out_esp_done = B_TRUE;
27025 		/*
27026 		 * Note that since hw accel can only apply one transform,
27027 		 * not two, we skip hw accel for ESP if we also have AH
27028 		 * This is an design limitation of the interface
27029 		 * which should be revisited.
27030 		 */
27031 		ASSERT(ire != NULL);
27032 		if (io->ipsec_out_ah_sa == NULL) {
27033 			ill = (ill_t *)ire->ire_stq->q_ptr;
27034 			ipsec_out_is_accelerated(ipsec_mp,
27035 			    io->ipsec_out_esp_sa, ill, ire);
27036 		}
27037 
27038 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
27039 		switch (ipsec_rc) {
27040 		case IPSEC_STATUS_SUCCESS:
27041 			break;
27042 		case IPSEC_STATUS_FAILED:
27043 			if (ill != NULL) {
27044 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
27045 			} else {
27046 				BUMP_MIB(&ipst->ips_ip_mib,
27047 				    ipIfStatsOutDiscards);
27048 			}
27049 			/* FALLTHRU */
27050 		case IPSEC_STATUS_PENDING:
27051 			return;
27052 		}
27053 	}
27054 
27055 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
27056 		ASSERT(io->ipsec_out_ah_sa != NULL);
27057 		io->ipsec_out_ah_done = B_TRUE;
27058 		if (ire == NULL) {
27059 			int idx = io->ipsec_out_capab_ill_index;
27060 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
27061 			    NULL, NULL, NULL, NULL, ipst);
27062 			ill_need_rele = B_TRUE;
27063 		} else {
27064 			ill = (ill_t *)ire->ire_stq->q_ptr;
27065 		}
27066 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
27067 		    ire);
27068 
27069 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
27070 		switch (ipsec_rc) {
27071 		case IPSEC_STATUS_SUCCESS:
27072 			break;
27073 		case IPSEC_STATUS_FAILED:
27074 			if (ill != NULL) {
27075 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
27076 			} else {
27077 				BUMP_MIB(&ipst->ips_ip_mib,
27078 				    ipIfStatsOutDiscards);
27079 			}
27080 			/* FALLTHRU */
27081 		case IPSEC_STATUS_PENDING:
27082 			if (ill != NULL && ill_need_rele)
27083 				ill_refrele(ill);
27084 			return;
27085 		}
27086 	}
27087 	/*
27088 	 * We are done with IPSEC processing. Send it over
27089 	 * the wire.
27090 	 */
27091 done:
27092 	mp = ipsec_mp->b_cont;
27093 	ipha = (ipha_t *)mp->b_rptr;
27094 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
27095 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
27096 	} else {
27097 		ip6h = (ip6_t *)ipha;
27098 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
27099 	}
27100 	if (ill != NULL && ill_need_rele)
27101 		ill_refrele(ill);
27102 }
27103 
27104 /* ARGSUSED */
27105 void
27106 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
27107 {
27108 	opt_restart_t	*or;
27109 	int	err;
27110 	conn_t	*connp;
27111 
27112 	ASSERT(CONN_Q(q));
27113 	connp = Q_TO_CONN(q);
27114 
27115 	ASSERT(first_mp->b_datap->db_type == M_CTL);
27116 	or = (opt_restart_t *)first_mp->b_rptr;
27117 	/*
27118 	 * We don't need to pass any credentials here since this is just
27119 	 * a restart. The credentials are passed in when svr4_optcom_req
27120 	 * is called the first time (from ip_wput_nondata).
27121 	 */
27122 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
27123 		err = svr4_optcom_req(q, first_mp, NULL,
27124 		    &ip_opt_obj);
27125 	} else {
27126 		ASSERT(or->or_type == T_OPTMGMT_REQ);
27127 		err = tpi_optcom_req(q, first_mp, NULL,
27128 		    &ip_opt_obj);
27129 	}
27130 	if (err != EINPROGRESS) {
27131 		/* operation is done */
27132 		CONN_OPER_PENDING_DONE(connp);
27133 	}
27134 }
27135 
27136 /*
27137  * ioctls that go through a down/up sequence may need to wait for the down
27138  * to complete. This involves waiting for the ire and ipif refcnts to go down
27139  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
27140  */
27141 /* ARGSUSED */
27142 void
27143 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27144 {
27145 	struct iocblk *iocp;
27146 	mblk_t *mp1;
27147 	ip_ioctl_cmd_t *ipip;
27148 	int err;
27149 	sin_t	*sin;
27150 	struct lifreq *lifr;
27151 	struct ifreq *ifr;
27152 
27153 	iocp = (struct iocblk *)mp->b_rptr;
27154 	ASSERT(ipsq != NULL);
27155 	/* Existence of mp1 verified in ip_wput_nondata */
27156 	mp1 = mp->b_cont->b_cont;
27157 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27158 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
27159 		/*
27160 		 * Special case where ipsq_current_ipif is not set:
27161 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
27162 		 * ill could also have become part of a ipmp group in the
27163 		 * process, we are here as were not able to complete the
27164 		 * operation in ipif_set_values because we could not become
27165 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
27166 		 * will not be set so we need to set it.
27167 		 */
27168 		ill_t *ill = q->q_ptr;
27169 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
27170 	}
27171 	ASSERT(ipsq->ipsq_current_ipif != NULL);
27172 
27173 	if (ipip->ipi_cmd_type == IF_CMD) {
27174 		/* This a old style SIOC[GS]IF* command */
27175 		ifr = (struct ifreq *)mp1->b_rptr;
27176 		sin = (sin_t *)&ifr->ifr_addr;
27177 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
27178 		/* This a new style SIOC[GS]LIF* command */
27179 		lifr = (struct lifreq *)mp1->b_rptr;
27180 		sin = (sin_t *)&lifr->lifr_addr;
27181 	} else {
27182 		sin = NULL;
27183 	}
27184 
27185 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_current_ipif, sin, q, mp,
27186 	    ipip, mp1->b_rptr);
27187 
27188 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27189 }
27190 
27191 /*
27192  * ioctl processing
27193  *
27194  * ioctl processing starts with ip_sioctl_copyin_setup which looks up
27195  * the ioctl command in the ioctl tables and determines the copyin data size
27196  * from the ioctl property ipi_copyin_size, and does an mi_copyin() of that
27197  * size.
27198  *
27199  * ioctl processing then continues when the M_IOCDATA makes its way down.
27200  * Now the ioctl is looked up again in the ioctl table, and its properties are
27201  * extracted. The associated 'conn' is then refheld till the end of the ioctl
27202  * and the general ioctl processing function ip_process_ioctl is called.
27203  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
27204  * so goes thru the serialization primitive ipsq_try_enter. Then the
27205  * appropriate function to handle the ioctl is called based on the entry in
27206  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
27207  * which also refreleases the 'conn' that was refheld at the start of the
27208  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
27209  * ip_extract_lifreq_cmn extracts the interface name from the lifreq/ifreq
27210  * struct and looks up the ipif. ip_extract_tunreq handles the case of tunnel.
27211  *
27212  * Many exclusive ioctls go thru an internal down up sequence as part of
27213  * the operation. For example an attempt to change the IP address of an
27214  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
27215  * does all the cleanup such as deleting all ires that use this address.
27216  * Then we need to wait till all references to the interface go away.
27217  */
27218 void
27219 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
27220 {
27221 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
27222 	ip_ioctl_cmd_t *ipip = (ip_ioctl_cmd_t *)arg;
27223 	cmd_info_t ci;
27224 	int err;
27225 	boolean_t entered_ipsq = B_FALSE;
27226 
27227 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
27228 
27229 	if (ipip == NULL)
27230 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27231 
27232 	/*
27233 	 * SIOCLIFADDIF needs to go thru a special path since the
27234 	 * ill may not exist yet. This happens in the case of lo0
27235 	 * which is created using this ioctl.
27236 	 */
27237 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
27238 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
27239 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27240 		return;
27241 	}
27242 
27243 	ci.ci_ipif = NULL;
27244 	switch (ipip->ipi_cmd_type) {
27245 	case IF_CMD:
27246 	case LIF_CMD:
27247 		/*
27248 		 * ioctls that pass in a [l]ifreq appear here.
27249 		 * ip_extract_lifreq_cmn returns a refheld ipif in
27250 		 * ci.ci_ipif
27251 		 */
27252 		err = ip_extract_lifreq_cmn(q, mp, ipip->ipi_cmd_type,
27253 		    ipip->ipi_flags, &ci, ip_process_ioctl);
27254 		if (err != 0) {
27255 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27256 			return;
27257 		}
27258 		ASSERT(ci.ci_ipif != NULL);
27259 		break;
27260 
27261 	case TUN_CMD:
27262 		/*
27263 		 * SIOC[GS]TUNPARAM appear here. ip_extract_tunreq returns
27264 		 * a refheld ipif in ci.ci_ipif
27265 		 */
27266 		err = ip_extract_tunreq(q, mp, &ci.ci_ipif, ip_process_ioctl);
27267 		if (err != 0) {
27268 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27269 			return;
27270 		}
27271 		ASSERT(ci.ci_ipif != NULL);
27272 		break;
27273 
27274 	case MISC_CMD:
27275 		/*
27276 		 * ioctls that neither pass in [l]ifreq or iftun_req come here
27277 		 * For eg. SIOCGLIFCONF will appear here.
27278 		 */
27279 		switch (ipip->ipi_cmd) {
27280 		case IF_UNITSEL:
27281 			/* ioctl comes down the ill */
27282 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
27283 			ipif_refhold(ci.ci_ipif);
27284 			break;
27285 		case SIOCGMSFILTER:
27286 		case SIOCSMSFILTER:
27287 		case SIOCGIPMSFILTER:
27288 		case SIOCSIPMSFILTER:
27289 			err = ip_extract_msfilter(q, mp, &ci.ci_ipif,
27290 			    ip_process_ioctl);
27291 			if (err != 0) {
27292 				ip_ioctl_finish(q, mp, err, IPI2MODE(ipip),
27293 				    NULL);
27294 			}
27295 			break;
27296 		}
27297 		err = 0;
27298 		ci.ci_sin = NULL;
27299 		ci.ci_sin6 = NULL;
27300 		ci.ci_lifr = NULL;
27301 		break;
27302 	}
27303 
27304 	/*
27305 	 * If ipsq is non-null, we are already being called exclusively
27306 	 */
27307 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
27308 	if (!(ipip->ipi_flags & IPI_WR)) {
27309 		/*
27310 		 * A return value of EINPROGRESS means the ioctl is
27311 		 * either queued and waiting for some reason or has
27312 		 * already completed.
27313 		 */
27314 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
27315 		    ci.ci_lifr);
27316 		if (ci.ci_ipif != NULL)
27317 			ipif_refrele(ci.ci_ipif);
27318 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27319 		return;
27320 	}
27321 
27322 	ASSERT(ci.ci_ipif != NULL);
27323 
27324 	if (ipsq == NULL) {
27325 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
27326 		    ip_process_ioctl, NEW_OP, B_TRUE);
27327 		entered_ipsq = B_TRUE;
27328 	}
27329 	/*
27330 	 * Release the ipif so that ipif_down and friends that wait for
27331 	 * references to go away are not misled about the current ipif_refcnt
27332 	 * values. We are writer so we can access the ipif even after releasing
27333 	 * the ipif.
27334 	 */
27335 	ipif_refrele(ci.ci_ipif);
27336 	if (ipsq == NULL)
27337 		return;
27338 
27339 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
27340 
27341 	/*
27342 	 * For most set ioctls that come here, this serves as a single point
27343 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
27344 	 * be any new references to the ipif. This helps functions that go
27345 	 * through this path and end up trying to wait for the refcnts
27346 	 * associated with the ipif to go down to zero. Some exceptions are
27347 	 * Failover, Failback, and Groupname commands that operate on more than
27348 	 * just the ci.ci_ipif. These commands internally determine the
27349 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
27350 	 * flags on that set. Another exception is the Removeif command that
27351 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
27352 	 * ipif to operate on.
27353 	 */
27354 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
27355 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
27356 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
27357 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
27358 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
27359 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
27360 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
27361 
27362 	/*
27363 	 * A return value of EINPROGRESS means the ioctl is
27364 	 * either queued and waiting for some reason or has
27365 	 * already completed.
27366 	 */
27367 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
27368 
27369 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27370 
27371 	if (entered_ipsq)
27372 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
27373 }
27374 
27375 /*
27376  * Complete the ioctl. Typically ioctls use the mi package and need to
27377  * do mi_copyout/mi_copy_done.
27378  */
27379 void
27380 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
27381 {
27382 	conn_t	*connp = NULL;
27383 
27384 	if (err == EINPROGRESS)
27385 		return;
27386 
27387 	if (CONN_Q(q)) {
27388 		connp = Q_TO_CONN(q);
27389 		ASSERT(connp->conn_ref >= 2);
27390 	}
27391 
27392 	switch (mode) {
27393 	case COPYOUT:
27394 		if (err == 0)
27395 			mi_copyout(q, mp);
27396 		else
27397 			mi_copy_done(q, mp, err);
27398 		break;
27399 
27400 	case NO_COPYOUT:
27401 		mi_copy_done(q, mp, err);
27402 		break;
27403 
27404 	default:
27405 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
27406 		break;
27407 	}
27408 
27409 	/*
27410 	 * The refhold placed at the start of the ioctl is released here.
27411 	 */
27412 	if (connp != NULL)
27413 		CONN_OPER_PENDING_DONE(connp);
27414 
27415 	if (ipsq != NULL)
27416 		ipsq_current_finish(ipsq);
27417 }
27418 
27419 /*
27420  * This is called from ip_wput_nondata to resume a deferred TCP bind.
27421  */
27422 /* ARGSUSED */
27423 void
27424 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
27425 {
27426 	conn_t *connp = arg;
27427 	tcp_t	*tcp;
27428 
27429 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
27430 	tcp = connp->conn_tcp;
27431 
27432 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
27433 		freemsg(mp);
27434 	else
27435 		tcp_rput_other(tcp, mp);
27436 	CONN_OPER_PENDING_DONE(connp);
27437 }
27438 
27439 /* Called from ip_wput for all non data messages */
27440 /* ARGSUSED */
27441 void
27442 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27443 {
27444 	mblk_t		*mp1;
27445 	ire_t		*ire, *fake_ire;
27446 	ill_t		*ill;
27447 	struct iocblk	*iocp;
27448 	ip_ioctl_cmd_t	*ipip;
27449 	cred_t		*cr;
27450 	conn_t		*connp;
27451 	int		cmd, err;
27452 	nce_t		*nce;
27453 	ipif_t		*ipif;
27454 	ip_stack_t	*ipst;
27455 	char		*proto_str;
27456 
27457 	if (CONN_Q(q)) {
27458 		connp = Q_TO_CONN(q);
27459 		ipst = connp->conn_netstack->netstack_ip;
27460 	} else {
27461 		connp = NULL;
27462 		ipst = ILLQ_TO_IPST(q);
27463 	}
27464 
27465 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
27466 
27467 	/* Check if it is a queue to /dev/sctp. */
27468 	if (connp != NULL && connp->conn_ulp == IPPROTO_SCTP &&
27469 	    connp->conn_rq == NULL) {
27470 		sctp_wput(q, mp);
27471 		return;
27472 	}
27473 
27474 	switch (DB_TYPE(mp)) {
27475 	case M_IOCTL:
27476 		/*
27477 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
27478 		 * will arrange to copy in associated control structures.
27479 		 */
27480 		ip_sioctl_copyin_setup(q, mp);
27481 		return;
27482 	case M_IOCDATA:
27483 		/*
27484 		 * Ensure that this is associated with one of our trans-
27485 		 * parent ioctls.  If it's not ours, discard it if we're
27486 		 * running as a driver, or pass it on if we're a module.
27487 		 */
27488 		iocp = (struct iocblk *)mp->b_rptr;
27489 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27490 		if (ipip == NULL) {
27491 			if (q->q_next == NULL) {
27492 				goto nak;
27493 			} else {
27494 				putnext(q, mp);
27495 			}
27496 			return;
27497 		} else if ((q->q_next != NULL) &&
27498 		    !(ipip->ipi_flags & IPI_MODOK)) {
27499 			/*
27500 			 * the ioctl is one we recognise, but is not
27501 			 * consumed by IP as a module, pass M_IOCDATA
27502 			 * for processing downstream, but only for
27503 			 * common Streams ioctls.
27504 			 */
27505 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27506 				putnext(q, mp);
27507 				return;
27508 			} else {
27509 				goto nak;
27510 			}
27511 		}
27512 
27513 		/* IOCTL continuation following copyin or copyout. */
27514 		if (mi_copy_state(q, mp, NULL) == -1) {
27515 			/*
27516 			 * The copy operation failed.  mi_copy_state already
27517 			 * cleaned up, so we're out of here.
27518 			 */
27519 			return;
27520 		}
27521 		/*
27522 		 * If we just completed a copy in, we become writer and
27523 		 * continue processing in ip_sioctl_copyin_done.  If it
27524 		 * was a copy out, we call mi_copyout again.  If there is
27525 		 * nothing more to copy out, it will complete the IOCTL.
27526 		 */
27527 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27528 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27529 				mi_copy_done(q, mp, EPROTO);
27530 				return;
27531 			}
27532 			/*
27533 			 * Check for cases that need more copying.  A return
27534 			 * value of 0 means a second copyin has been started,
27535 			 * so we return; a return value of 1 means no more
27536 			 * copying is needed, so we continue.
27537 			 */
27538 			cmd = iocp->ioc_cmd;
27539 			if ((cmd == SIOCGMSFILTER || cmd == SIOCSMSFILTER ||
27540 			    cmd == SIOCGIPMSFILTER || cmd == SIOCSIPMSFILTER) &&
27541 			    MI_COPY_COUNT(mp) == 1) {
27542 				if (ip_copyin_msfilter(q, mp) == 0)
27543 					return;
27544 			}
27545 			/*
27546 			 * Refhold the conn, till the ioctl completes. This is
27547 			 * needed in case the ioctl ends up in the pending mp
27548 			 * list. Every mp in the ill_pending_mp list and
27549 			 * the ipsq_pending_mp must have a refhold on the conn
27550 			 * to resume processing. The refhold is released when
27551 			 * the ioctl completes. (normally or abnormally)
27552 			 * In all cases ip_ioctl_finish is called to finish
27553 			 * the ioctl.
27554 			 */
27555 			if (connp != NULL) {
27556 				/* This is not a reentry */
27557 				ASSERT(ipsq == NULL);
27558 				CONN_INC_REF(connp);
27559 			} else {
27560 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27561 					mi_copy_done(q, mp, EINVAL);
27562 					return;
27563 				}
27564 			}
27565 
27566 			ip_process_ioctl(ipsq, q, mp, ipip);
27567 
27568 		} else {
27569 			mi_copyout(q, mp);
27570 		}
27571 		return;
27572 nak:
27573 		iocp->ioc_error = EINVAL;
27574 		mp->b_datap->db_type = M_IOCNAK;
27575 		iocp->ioc_count = 0;
27576 		qreply(q, mp);
27577 		return;
27578 
27579 	case M_IOCNAK:
27580 		/*
27581 		 * The only way we could get here is if a resolver didn't like
27582 		 * an IOCTL we sent it.	 This shouldn't happen.
27583 		 */
27584 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27585 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27586 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27587 		freemsg(mp);
27588 		return;
27589 	case M_IOCACK:
27590 		/* /dev/ip shouldn't see this */
27591 		if (CONN_Q(q))
27592 			goto nak;
27593 
27594 		/* Finish socket ioctls passed through to ARP. */
27595 		ip_sioctl_iocack(q, mp);
27596 		return;
27597 	case M_FLUSH:
27598 		if (*mp->b_rptr & FLUSHW)
27599 			flushq(q, FLUSHALL);
27600 		if (q->q_next) {
27601 			putnext(q, mp);
27602 			return;
27603 		}
27604 		if (*mp->b_rptr & FLUSHR) {
27605 			*mp->b_rptr &= ~FLUSHW;
27606 			qreply(q, mp);
27607 			return;
27608 		}
27609 		freemsg(mp);
27610 		return;
27611 	case IRE_DB_REQ_TYPE:
27612 		if (connp == NULL) {
27613 			proto_str = "IRE_DB_REQ_TYPE";
27614 			goto protonak;
27615 		}
27616 		/* An Upper Level Protocol wants a copy of an IRE. */
27617 		ip_ire_req(q, mp);
27618 		return;
27619 	case M_CTL:
27620 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27621 			break;
27622 
27623 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27624 		    TUN_HELLO) {
27625 			ASSERT(connp != NULL);
27626 			connp->conn_flags |= IPCL_IPTUN;
27627 			freeb(mp);
27628 			return;
27629 		}
27630 
27631 		if (connp != NULL && *(uint32_t *)mp->b_rptr ==
27632 		    IP_ULP_OUT_LABELED) {
27633 			out_labeled_t *olp;
27634 
27635 			if (mp->b_wptr - mp->b_rptr != sizeof (*olp))
27636 				break;
27637 			olp = (out_labeled_t *)mp->b_rptr;
27638 			connp->conn_ulp_labeled = olp->out_qnext == q;
27639 			freemsg(mp);
27640 			return;
27641 		}
27642 
27643 		/* M_CTL messages are used by ARP to tell us things. */
27644 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27645 			break;
27646 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27647 		case AR_ENTRY_SQUERY:
27648 			ip_wput_ctl(q, mp);
27649 			return;
27650 		case AR_CLIENT_NOTIFY:
27651 			ip_arp_news(q, mp);
27652 			return;
27653 		case AR_DLPIOP_DONE:
27654 			ASSERT(q->q_next != NULL);
27655 			ill = (ill_t *)q->q_ptr;
27656 			/* qwriter_ip releases the refhold */
27657 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27658 			ill_refhold(ill);
27659 			qwriter_ip(ill, q, mp, ip_arp_done, CUR_OP, B_FALSE);
27660 			return;
27661 		case AR_ARP_CLOSING:
27662 			/*
27663 			 * ARP (above us) is closing. If no ARP bringup is
27664 			 * currently pending, ack the message so that ARP
27665 			 * can complete its close. Also mark ill_arp_closing
27666 			 * so that new ARP bringups will fail. If any
27667 			 * ARP bringup is currently in progress, we will
27668 			 * ack this when the current ARP bringup completes.
27669 			 */
27670 			ASSERT(q->q_next != NULL);
27671 			ill = (ill_t *)q->q_ptr;
27672 			mutex_enter(&ill->ill_lock);
27673 			ill->ill_arp_closing = 1;
27674 			if (!ill->ill_arp_bringup_pending) {
27675 				mutex_exit(&ill->ill_lock);
27676 				qreply(q, mp);
27677 			} else {
27678 				mutex_exit(&ill->ill_lock);
27679 				freemsg(mp);
27680 			}
27681 			return;
27682 		case AR_ARP_EXTEND:
27683 			/*
27684 			 * The ARP module above us is capable of duplicate
27685 			 * address detection.  Old ATM drivers will not send
27686 			 * this message.
27687 			 */
27688 			ASSERT(q->q_next != NULL);
27689 			ill = (ill_t *)q->q_ptr;
27690 			ill->ill_arp_extend = B_TRUE;
27691 			freemsg(mp);
27692 			return;
27693 		default:
27694 			break;
27695 		}
27696 		break;
27697 	case M_PROTO:
27698 	case M_PCPROTO:
27699 		/*
27700 		 * The only PROTO messages we expect are ULP binds and
27701 		 * copies of option negotiation acknowledgements.
27702 		 */
27703 		switch (((union T_primitives *)mp->b_rptr)->type) {
27704 		case O_T_BIND_REQ:
27705 		case T_BIND_REQ: {
27706 			/* Request can get queued in bind */
27707 			if (connp == NULL) {
27708 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27709 				goto protonak;
27710 			}
27711 			/*
27712 			 * Both TCP and UDP call ip_bind_{v4,v6}() directly
27713 			 * instead of going through this path.  We only get
27714 			 * here in the following cases:
27715 			 *
27716 			 * a. Bind retries, where ipsq is non-NULL.
27717 			 * b. T_BIND_REQ is issued from non TCP/UDP
27718 			 *    transport, e.g. icmp for raw socket,
27719 			 *    in which case ipsq will be NULL.
27720 			 */
27721 			ASSERT(ipsq != NULL ||
27722 			    (!IPCL_IS_TCP(connp) && !IPCL_IS_UDP(connp)));
27723 
27724 			/* Don't increment refcnt if this is a re-entry */
27725 			if (ipsq == NULL)
27726 				CONN_INC_REF(connp);
27727 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27728 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27729 			if (mp == NULL)
27730 				return;
27731 			if (IPCL_IS_TCP(connp)) {
27732 				/*
27733 				 * In the case of TCP endpoint we
27734 				 * come here only for bind retries
27735 				 */
27736 				ASSERT(ipsq != NULL);
27737 				CONN_INC_REF(connp);
27738 				squeue_fill(connp->conn_sqp, mp,
27739 				    ip_resume_tcp_bind, connp,
27740 				    SQTAG_BIND_RETRY);
27741 				return;
27742 			} else if (IPCL_IS_UDP(connp)) {
27743 				/*
27744 				 * In the case of UDP endpoint we
27745 				 * come here only for bind retries
27746 				 */
27747 				ASSERT(ipsq != NULL);
27748 				udp_resume_bind(connp, mp);
27749 				return;
27750 			}
27751 			qreply(q, mp);
27752 			CONN_OPER_PENDING_DONE(connp);
27753 			return;
27754 		}
27755 		case T_SVR4_OPTMGMT_REQ:
27756 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27757 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27758 
27759 			if (connp == NULL) {
27760 				proto_str = "T_SVR4_OPTMGMT_REQ";
27761 				goto protonak;
27762 			}
27763 
27764 			if (!snmpcom_req(q, mp, ip_snmp_set,
27765 			    ip_snmp_get, cr)) {
27766 				/*
27767 				 * Call svr4_optcom_req so that it can
27768 				 * generate the ack. We don't come here
27769 				 * if this operation is being restarted.
27770 				 * ip_restart_optmgmt will drop the conn ref.
27771 				 * In the case of ipsec option after the ipsec
27772 				 * load is complete conn_restart_ipsec_waiter
27773 				 * drops the conn ref.
27774 				 */
27775 				ASSERT(ipsq == NULL);
27776 				CONN_INC_REF(connp);
27777 				if (ip_check_for_ipsec_opt(q, mp))
27778 					return;
27779 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj);
27780 				if (err != EINPROGRESS) {
27781 					/* Operation is done */
27782 					CONN_OPER_PENDING_DONE(connp);
27783 				}
27784 			}
27785 			return;
27786 		case T_OPTMGMT_REQ:
27787 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27788 			/*
27789 			 * Note: No snmpcom_req support through new
27790 			 * T_OPTMGMT_REQ.
27791 			 * Call tpi_optcom_req so that it can
27792 			 * generate the ack.
27793 			 */
27794 			if (connp == NULL) {
27795 				proto_str = "T_OPTMGMT_REQ";
27796 				goto protonak;
27797 			}
27798 
27799 			ASSERT(ipsq == NULL);
27800 			/*
27801 			 * We don't come here for restart. ip_restart_optmgmt
27802 			 * will drop the conn ref. In the case of ipsec option
27803 			 * after the ipsec load is complete
27804 			 * conn_restart_ipsec_waiter drops the conn ref.
27805 			 */
27806 			CONN_INC_REF(connp);
27807 			if (ip_check_for_ipsec_opt(q, mp))
27808 				return;
27809 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj);
27810 			if (err != EINPROGRESS) {
27811 				/* Operation is done */
27812 				CONN_OPER_PENDING_DONE(connp);
27813 			}
27814 			return;
27815 		case T_UNBIND_REQ:
27816 			if (connp == NULL) {
27817 				proto_str = "T_UNBIND_REQ";
27818 				goto protonak;
27819 			}
27820 			mp = ip_unbind(q, mp);
27821 			qreply(q, mp);
27822 			return;
27823 		default:
27824 			/*
27825 			 * Have to drop any DLPI messages coming down from
27826 			 * arp (such as an info_req which would cause ip
27827 			 * to receive an extra info_ack if it was passed
27828 			 * through.
27829 			 */
27830 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27831 			    (int)*(uint_t *)mp->b_rptr));
27832 			freemsg(mp);
27833 			return;
27834 		}
27835 		/* NOTREACHED */
27836 	case IRE_DB_TYPE: {
27837 		nce_t		*nce;
27838 		ill_t		*ill;
27839 		in6_addr_t	gw_addr_v6;
27840 
27841 
27842 		/*
27843 		 * This is a response back from a resolver.  It
27844 		 * consists of a message chain containing:
27845 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27846 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27847 		 * The LL_HDR_MBLK is the DLPI header to use to get
27848 		 * the attached packet, and subsequent ones for the
27849 		 * same destination, transmitted.
27850 		 */
27851 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27852 			break;
27853 		/*
27854 		 * First, check to make sure the resolution succeeded.
27855 		 * If it failed, the second mblk will be empty.
27856 		 * If it is, free the chain, dropping the packet.
27857 		 * (We must ire_delete the ire; that frees the ire mblk)
27858 		 * We're doing this now to support PVCs for ATM; it's
27859 		 * a partial xresolv implementation. When we fully implement
27860 		 * xresolv interfaces, instead of freeing everything here
27861 		 * we'll initiate neighbor discovery.
27862 		 *
27863 		 * For v4 (ARP and other external resolvers) the resolver
27864 		 * frees the message, so no check is needed. This check
27865 		 * is required, though, for a full xresolve implementation.
27866 		 * Including this code here now both shows how external
27867 		 * resolvers can NACK a resolution request using an
27868 		 * existing design that has no specific provisions for NACKs,
27869 		 * and also takes into account that the current non-ARP
27870 		 * external resolver has been coded to use this method of
27871 		 * NACKing for all IPv6 (xresolv) cases,
27872 		 * whether our xresolv implementation is complete or not.
27873 		 *
27874 		 */
27875 		ire = (ire_t *)mp->b_rptr;
27876 		ill = ire_to_ill(ire);
27877 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27878 		if (mp1->b_rptr == mp1->b_wptr) {
27879 			if (ire->ire_ipversion == IPV6_VERSION) {
27880 				/*
27881 				 * XRESOLV interface.
27882 				 */
27883 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27884 				mutex_enter(&ire->ire_lock);
27885 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27886 				mutex_exit(&ire->ire_lock);
27887 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27888 					nce = ndp_lookup_v6(ill,
27889 					    &ire->ire_addr_v6, B_FALSE);
27890 				} else {
27891 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
27892 					    B_FALSE);
27893 				}
27894 				if (nce != NULL) {
27895 					nce_resolv_failed(nce);
27896 					ndp_delete(nce);
27897 					NCE_REFRELE(nce);
27898 				}
27899 			}
27900 			mp->b_cont = NULL;
27901 			freemsg(mp1);		/* frees the pkt as well */
27902 			ASSERT(ire->ire_nce == NULL);
27903 			ire_delete((ire_t *)mp->b_rptr);
27904 			return;
27905 		}
27906 
27907 		/*
27908 		 * Split them into IRE_MBLK and pkt and feed it into
27909 		 * ire_add_then_send. Then in ire_add_then_send
27910 		 * the IRE will be added, and then the packet will be
27911 		 * run back through ip_wput. This time it will make
27912 		 * it to the wire.
27913 		 */
27914 		mp->b_cont = NULL;
27915 		mp = mp1->b_cont;		/* now, mp points to pkt */
27916 		mp1->b_cont = NULL;
27917 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27918 		if (ire->ire_ipversion == IPV6_VERSION) {
27919 			/*
27920 			 * XRESOLV interface. Find the nce and put a copy
27921 			 * of the dl_unitdata_req in nce_res_mp
27922 			 */
27923 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27924 			mutex_enter(&ire->ire_lock);
27925 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27926 			mutex_exit(&ire->ire_lock);
27927 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27928 				nce = ndp_lookup_v6(ill, &ire->ire_addr_v6,
27929 				    B_FALSE);
27930 			} else {
27931 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
27932 			}
27933 			if (nce != NULL) {
27934 				/*
27935 				 * We have to protect nce_res_mp here
27936 				 * from being accessed by other threads
27937 				 * while we change the mblk pointer.
27938 				 * Other functions will also lock the nce when
27939 				 * accessing nce_res_mp.
27940 				 *
27941 				 * The reason we change the mblk pointer
27942 				 * here rather than copying the resolved address
27943 				 * into the template is that, unlike with
27944 				 * ethernet, we have no guarantee that the
27945 				 * resolved address length will be
27946 				 * smaller than or equal to the lla length
27947 				 * with which the template was allocated,
27948 				 * (for ethernet, they're equal)
27949 				 * so we have to use the actual resolved
27950 				 * address mblk - which holds the real
27951 				 * dl_unitdata_req with the resolved address.
27952 				 *
27953 				 * Doing this is the same behavior as was
27954 				 * previously used in the v4 ARP case.
27955 				 */
27956 				mutex_enter(&nce->nce_lock);
27957 				if (nce->nce_res_mp != NULL)
27958 					freemsg(nce->nce_res_mp);
27959 				nce->nce_res_mp = mp1;
27960 				mutex_exit(&nce->nce_lock);
27961 				/*
27962 				 * We do a fastpath probe here because
27963 				 * we have resolved the address without
27964 				 * using Neighbor Discovery.
27965 				 * In the non-XRESOLV v6 case, the fastpath
27966 				 * probe is done right after neighbor
27967 				 * discovery completes.
27968 				 */
27969 				if (nce->nce_res_mp != NULL) {
27970 					int res;
27971 					nce_fastpath_list_add(nce);
27972 					res = ill_fastpath_probe(ill,
27973 					    nce->nce_res_mp);
27974 					if (res != 0 && res != EAGAIN)
27975 						nce_fastpath_list_delete(nce);
27976 				}
27977 
27978 				ire_add_then_send(q, ire, mp);
27979 				/*
27980 				 * Now we have to clean out any packets
27981 				 * that may have been queued on the nce
27982 				 * while it was waiting for address resolution
27983 				 * to complete.
27984 				 */
27985 				mutex_enter(&nce->nce_lock);
27986 				mp1 = nce->nce_qd_mp;
27987 				nce->nce_qd_mp = NULL;
27988 				mutex_exit(&nce->nce_lock);
27989 				while (mp1 != NULL) {
27990 					mblk_t *nxt_mp;
27991 					queue_t *fwdq = NULL;
27992 					ill_t   *inbound_ill;
27993 					uint_t ifindex;
27994 
27995 					nxt_mp = mp1->b_next;
27996 					mp1->b_next = NULL;
27997 					/*
27998 					 * Retrieve ifindex stored in
27999 					 * ip_rput_data_v6()
28000 					 */
28001 					ifindex =
28002 					    (uint_t)(uintptr_t)mp1->b_prev;
28003 					inbound_ill =
28004 					    ill_lookup_on_ifindex(ifindex,
28005 					    B_TRUE, NULL, NULL, NULL,
28006 					    NULL, ipst);
28007 					mp1->b_prev = NULL;
28008 					if (inbound_ill != NULL)
28009 						fwdq = inbound_ill->ill_rq;
28010 
28011 					if (fwdq != NULL) {
28012 						put(fwdq, mp1);
28013 						ill_refrele(inbound_ill);
28014 					} else
28015 						put(WR(ill->ill_rq), mp1);
28016 					mp1 = nxt_mp;
28017 				}
28018 				NCE_REFRELE(nce);
28019 			} else {	/* nce is NULL; clean up */
28020 				ire_delete(ire);
28021 				freemsg(mp);
28022 				freemsg(mp1);
28023 				return;
28024 			}
28025 		} else {
28026 			nce_t *arpce;
28027 			/*
28028 			 * Link layer resolution succeeded. Recompute the
28029 			 * ire_nce.
28030 			 */
28031 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
28032 			if ((arpce = ndp_lookup_v4(ill,
28033 			    (ire->ire_gateway_addr != INADDR_ANY ?
28034 			    &ire->ire_gateway_addr : &ire->ire_addr),
28035 			    B_FALSE)) == NULL) {
28036 				freeb(ire->ire_mp);
28037 				freeb(mp1);
28038 				freemsg(mp);
28039 				return;
28040 			}
28041 			mutex_enter(&arpce->nce_lock);
28042 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
28043 			if (arpce->nce_state == ND_REACHABLE) {
28044 				/*
28045 				 * Someone resolved this before us;
28046 				 * cleanup the res_mp. Since ire has
28047 				 * not been added yet, the call to ire_add_v4
28048 				 * from ire_add_then_send (when a dup is
28049 				 * detected) will clean up the ire.
28050 				 */
28051 				freeb(mp1);
28052 			} else {
28053 				if (arpce->nce_res_mp != NULL)
28054 					freemsg(arpce->nce_res_mp);
28055 				arpce->nce_res_mp = mp1;
28056 				arpce->nce_state = ND_REACHABLE;
28057 			}
28058 			mutex_exit(&arpce->nce_lock);
28059 			if (ire->ire_marks & IRE_MARK_NOADD) {
28060 				/*
28061 				 * this ire will not be added to the ire
28062 				 * cache table, so we can set the ire_nce
28063 				 * here, as there are no atomicity constraints.
28064 				 */
28065 				ire->ire_nce = arpce;
28066 				/*
28067 				 * We are associating this nce with the ire
28068 				 * so change the nce ref taken in
28069 				 * ndp_lookup_v4() from
28070 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
28071 				 */
28072 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
28073 			} else {
28074 				NCE_REFRELE(arpce);
28075 			}
28076 			ire_add_then_send(q, ire, mp);
28077 		}
28078 		return;	/* All is well, the packet has been sent. */
28079 	}
28080 	case IRE_ARPRESOLVE_TYPE: {
28081 
28082 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
28083 			break;
28084 		mp1 = mp->b_cont;		/* dl_unitdata_req */
28085 		mp->b_cont = NULL;
28086 		/*
28087 		 * First, check to make sure the resolution succeeded.
28088 		 * If it failed, the second mblk will be empty.
28089 		 */
28090 		if (mp1->b_rptr == mp1->b_wptr) {
28091 			/* cleanup  the incomplete ire, free queued packets */
28092 			freemsg(mp); /* fake ire */
28093 			freeb(mp1);  /* dl_unitdata response */
28094 			return;
28095 		}
28096 
28097 		/*
28098 		 * update any incomplete nce_t found. we lookup the ctable
28099 		 * and find the nce from the ire->ire_nce because we need
28100 		 * to pass the ire to ip_xmit_v4 later, and can find both
28101 		 * ire and nce in one lookup from the ctable.
28102 		 */
28103 		fake_ire = (ire_t *)mp->b_rptr;
28104 		/*
28105 		 * By the time we come back here from ARP
28106 		 * the logical outgoing interface  of the incomplete ire
28107 		 * we added in ire_forward could have disappeared,
28108 		 * causing the incomplete ire to also have
28109 		 * dissapeared. So we need to retreive the
28110 		 * proper ipif for the ire  before looking
28111 		 * in ctable;  do the ctablelookup based on ire_ipif_seqid
28112 		 */
28113 		ill = q->q_ptr;
28114 
28115 		/* Get the outgoing ipif */
28116 		mutex_enter(&ill->ill_lock);
28117 		if (ill->ill_state_flags & ILL_CONDEMNED) {
28118 			mutex_exit(&ill->ill_lock);
28119 			freemsg(mp); /* fake ire */
28120 			freeb(mp1);  /* dl_unitdata response */
28121 			return;
28122 		}
28123 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
28124 
28125 		if (ipif == NULL) {
28126 			mutex_exit(&ill->ill_lock);
28127 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
28128 			freemsg(mp);
28129 			freeb(mp1);
28130 			return;
28131 		}
28132 		ipif_refhold_locked(ipif);
28133 		mutex_exit(&ill->ill_lock);
28134 		ire = ire_ctable_lookup(fake_ire->ire_addr,
28135 		    fake_ire->ire_gateway_addr, IRE_CACHE,
28136 		    ipif, fake_ire->ire_zoneid, NULL,
28137 		    (MATCH_IRE_GW|MATCH_IRE_IPIF|MATCH_IRE_ZONEONLY), ipst);
28138 		ipif_refrele(ipif);
28139 		if (ire == NULL) {
28140 			/*
28141 			 * no ire was found; check if there is an nce
28142 			 * for this lookup; if it has no ire's pointing at it
28143 			 * cleanup.
28144 			 */
28145 			if ((nce = ndp_lookup_v4(ill,
28146 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
28147 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
28148 			    B_FALSE)) != NULL) {
28149 				/*
28150 				 * cleanup:
28151 				 * We check for refcnt 2 (one for the nce
28152 				 * hash list + 1 for the ref taken by
28153 				 * ndp_lookup_v4) to check that there are
28154 				 * no ire's pointing at the nce.
28155 				 */
28156 				if (nce->nce_refcnt == 2)
28157 					ndp_delete(nce);
28158 				NCE_REFRELE(nce);
28159 			}
28160 			freeb(mp1);  /* dl_unitdata response */
28161 			freemsg(mp); /* fake ire */
28162 			return;
28163 		}
28164 		nce = ire->ire_nce;
28165 		DTRACE_PROBE2(ire__arpresolve__type,
28166 		    ire_t *, ire, nce_t *, nce);
28167 		ASSERT(nce->nce_state != ND_INITIAL);
28168 		mutex_enter(&nce->nce_lock);
28169 		nce->nce_last = TICK_TO_MSEC(lbolt64);
28170 		if (nce->nce_state == ND_REACHABLE) {
28171 			/*
28172 			 * Someone resolved this before us;
28173 			 * our response is not needed any more.
28174 			 */
28175 			mutex_exit(&nce->nce_lock);
28176 			freeb(mp1);  /* dl_unitdata response */
28177 		} else {
28178 			if (nce->nce_res_mp != NULL) {
28179 				freemsg(nce->nce_res_mp);
28180 				/* existing dl_unitdata template */
28181 			}
28182 			nce->nce_res_mp = mp1;
28183 			nce->nce_state = ND_REACHABLE;
28184 			mutex_exit(&nce->nce_lock);
28185 			nce_fastpath(nce);
28186 		}
28187 		/*
28188 		 * The cached nce_t has been updated to be reachable;
28189 		 * Set the IRE_MARK_UNCACHED flag and free the fake_ire.
28190 		 */
28191 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
28192 		freemsg(mp);
28193 		/*
28194 		 * send out queued packets.
28195 		 */
28196 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
28197 
28198 		IRE_REFRELE(ire);
28199 		return;
28200 	}
28201 	default:
28202 		break;
28203 	}
28204 	if (q->q_next) {
28205 		putnext(q, mp);
28206 	} else
28207 		freemsg(mp);
28208 	return;
28209 
28210 protonak:
28211 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
28212 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
28213 		qreply(q, mp);
28214 }
28215 
28216 /*
28217  * Process IP options in an outbound packet.  Modify the destination if there
28218  * is a source route option.
28219  * Returns non-zero if something fails in which case an ICMP error has been
28220  * sent and mp freed.
28221  */
28222 static int
28223 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
28224     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
28225 {
28226 	ipoptp_t	opts;
28227 	uchar_t		*opt;
28228 	uint8_t		optval;
28229 	uint8_t		optlen;
28230 	ipaddr_t	dst;
28231 	intptr_t	code = 0;
28232 	mblk_t		*mp;
28233 	ire_t		*ire = NULL;
28234 
28235 	ip2dbg(("ip_wput_options\n"));
28236 	mp = ipsec_mp;
28237 	if (mctl_present) {
28238 		mp = ipsec_mp->b_cont;
28239 	}
28240 
28241 	dst = ipha->ipha_dst;
28242 	for (optval = ipoptp_first(&opts, ipha);
28243 	    optval != IPOPT_EOL;
28244 	    optval = ipoptp_next(&opts)) {
28245 		opt = opts.ipoptp_cur;
28246 		optlen = opts.ipoptp_len;
28247 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
28248 		    optval, optlen));
28249 		switch (optval) {
28250 			uint32_t off;
28251 		case IPOPT_SSRR:
28252 		case IPOPT_LSRR:
28253 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28254 				ip1dbg((
28255 				    "ip_wput_options: bad option offset\n"));
28256 				code = (char *)&opt[IPOPT_OLEN] -
28257 				    (char *)ipha;
28258 				goto param_prob;
28259 			}
28260 			off = opt[IPOPT_OFFSET];
28261 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
28262 			    ntohl(dst)));
28263 			/*
28264 			 * For strict: verify that dst is directly
28265 			 * reachable.
28266 			 */
28267 			if (optval == IPOPT_SSRR) {
28268 				ire = ire_ftable_lookup(dst, 0, 0,
28269 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
28270 				    MBLK_GETLABEL(mp),
28271 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
28272 				if (ire == NULL) {
28273 					ip1dbg(("ip_wput_options: SSRR not"
28274 					    " directly reachable: 0x%x\n",
28275 					    ntohl(dst)));
28276 					goto bad_src_route;
28277 				}
28278 				ire_refrele(ire);
28279 			}
28280 			break;
28281 		case IPOPT_RR:
28282 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28283 				ip1dbg((
28284 				    "ip_wput_options: bad option offset\n"));
28285 				code = (char *)&opt[IPOPT_OLEN] -
28286 				    (char *)ipha;
28287 				goto param_prob;
28288 			}
28289 			break;
28290 		case IPOPT_TS:
28291 			/*
28292 			 * Verify that length >=5 and that there is either
28293 			 * room for another timestamp or that the overflow
28294 			 * counter is not maxed out.
28295 			 */
28296 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
28297 			if (optlen < IPOPT_MINLEN_IT) {
28298 				goto param_prob;
28299 			}
28300 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28301 				ip1dbg((
28302 				    "ip_wput_options: bad option offset\n"));
28303 				code = (char *)&opt[IPOPT_OFFSET] -
28304 				    (char *)ipha;
28305 				goto param_prob;
28306 			}
28307 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
28308 			case IPOPT_TS_TSONLY:
28309 				off = IPOPT_TS_TIMELEN;
28310 				break;
28311 			case IPOPT_TS_TSANDADDR:
28312 			case IPOPT_TS_PRESPEC:
28313 			case IPOPT_TS_PRESPEC_RFC791:
28314 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
28315 				break;
28316 			default:
28317 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
28318 				    (char *)ipha;
28319 				goto param_prob;
28320 			}
28321 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
28322 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
28323 				/*
28324 				 * No room and the overflow counter is 15
28325 				 * already.
28326 				 */
28327 				goto param_prob;
28328 			}
28329 			break;
28330 		}
28331 	}
28332 
28333 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
28334 		return (0);
28335 
28336 	ip1dbg(("ip_wput_options: error processing IP options."));
28337 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
28338 
28339 param_prob:
28340 	/*
28341 	 * Since ip_wput() isn't close to finished, we fill
28342 	 * in enough of the header for credible error reporting.
28343 	 */
28344 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28345 		/* Failed */
28346 		freemsg(ipsec_mp);
28347 		return (-1);
28348 	}
28349 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
28350 	return (-1);
28351 
28352 bad_src_route:
28353 	/*
28354 	 * Since ip_wput() isn't close to finished, we fill
28355 	 * in enough of the header for credible error reporting.
28356 	 */
28357 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28358 		/* Failed */
28359 		freemsg(ipsec_mp);
28360 		return (-1);
28361 	}
28362 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
28363 	return (-1);
28364 }
28365 
28366 /*
28367  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
28368  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
28369  * thru /etc/system.
28370  */
28371 #define	CONN_MAXDRAINCNT	64
28372 
28373 static void
28374 conn_drain_init(ip_stack_t *ipst)
28375 {
28376 	int i;
28377 
28378 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
28379 
28380 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
28381 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
28382 		/*
28383 		 * Default value of the number of drainers is the
28384 		 * number of cpus, subject to maximum of 8 drainers.
28385 		 */
28386 		if (boot_max_ncpus != -1)
28387 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
28388 		else
28389 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
28390 	}
28391 
28392 	ipst->ips_conn_drain_list = kmem_zalloc(ipst->ips_conn_drain_list_cnt *
28393 	    sizeof (idl_t), KM_SLEEP);
28394 
28395 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28396 		mutex_init(&ipst->ips_conn_drain_list[i].idl_lock, NULL,
28397 		    MUTEX_DEFAULT, NULL);
28398 	}
28399 }
28400 
28401 static void
28402 conn_drain_fini(ip_stack_t *ipst)
28403 {
28404 	int i;
28405 
28406 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++)
28407 		mutex_destroy(&ipst->ips_conn_drain_list[i].idl_lock);
28408 	kmem_free(ipst->ips_conn_drain_list,
28409 	    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
28410 	ipst->ips_conn_drain_list = NULL;
28411 }
28412 
28413 /*
28414  * Note: For an overview of how flowcontrol is handled in IP please see the
28415  * IP Flowcontrol notes at the top of this file.
28416  *
28417  * Flow control has blocked us from proceeding. Insert the given conn in one
28418  * of the conn drain lists. These conn wq's will be qenabled later on when
28419  * STREAMS flow control does a backenable. conn_walk_drain will enable
28420  * the first conn in each of these drain lists. Each of these qenabled conns
28421  * in turn enables the next in the list, after it runs, or when it closes,
28422  * thus sustaining the drain process.
28423  *
28424  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
28425  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
28426  * running at any time, on a given conn, since there can be only 1 service proc
28427  * running on a queue at any time.
28428  */
28429 void
28430 conn_drain_insert(conn_t *connp)
28431 {
28432 	idl_t	*idl;
28433 	uint_t	index;
28434 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28435 
28436 	mutex_enter(&connp->conn_lock);
28437 	if (connp->conn_state_flags & CONN_CLOSING) {
28438 		/*
28439 		 * The conn is closing as a result of which CONN_CLOSING
28440 		 * is set. Return.
28441 		 */
28442 		mutex_exit(&connp->conn_lock);
28443 		return;
28444 	} else if (connp->conn_idl == NULL) {
28445 		/*
28446 		 * Assign the next drain list round robin. We dont' use
28447 		 * a lock, and thus it may not be strictly round robin.
28448 		 * Atomicity of load/stores is enough to make sure that
28449 		 * conn_drain_list_index is always within bounds.
28450 		 */
28451 		index = ipst->ips_conn_drain_list_index;
28452 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
28453 		connp->conn_idl = &ipst->ips_conn_drain_list[index];
28454 		index++;
28455 		if (index == ipst->ips_conn_drain_list_cnt)
28456 			index = 0;
28457 		ipst->ips_conn_drain_list_index = index;
28458 	}
28459 	mutex_exit(&connp->conn_lock);
28460 
28461 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28462 	if ((connp->conn_drain_prev != NULL) ||
28463 	    (connp->conn_state_flags & CONN_CLOSING)) {
28464 		/*
28465 		 * The conn is already in the drain list, OR
28466 		 * the conn is closing. We need to check again for
28467 		 * the closing case again since close can happen
28468 		 * after we drop the conn_lock, and before we
28469 		 * acquire the CONN_DRAIN_LIST_LOCK.
28470 		 */
28471 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28472 		return;
28473 	} else {
28474 		idl = connp->conn_idl;
28475 	}
28476 
28477 	/*
28478 	 * The conn is not in the drain list. Insert it at the
28479 	 * tail of the drain list. The drain list is circular
28480 	 * and doubly linked. idl_conn points to the 1st element
28481 	 * in the list.
28482 	 */
28483 	if (idl->idl_conn == NULL) {
28484 		idl->idl_conn = connp;
28485 		connp->conn_drain_next = connp;
28486 		connp->conn_drain_prev = connp;
28487 	} else {
28488 		conn_t *head = idl->idl_conn;
28489 
28490 		connp->conn_drain_next = head;
28491 		connp->conn_drain_prev = head->conn_drain_prev;
28492 		head->conn_drain_prev->conn_drain_next = connp;
28493 		head->conn_drain_prev = connp;
28494 	}
28495 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28496 }
28497 
28498 /*
28499  * This conn is closing, and we are called from ip_close. OR
28500  * This conn has been serviced by ip_wsrv, and we need to do the tail
28501  * processing.
28502  * If this conn is part of the drain list, we may need to sustain the drain
28503  * process by qenabling the next conn in the drain list. We may also need to
28504  * remove this conn from the list, if it is done.
28505  */
28506 static void
28507 conn_drain_tail(conn_t *connp, boolean_t closing)
28508 {
28509 	idl_t *idl;
28510 
28511 	/*
28512 	 * connp->conn_idl is stable at this point, and no lock is needed
28513 	 * to check it. If we are called from ip_close, close has already
28514 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28515 	 * called us only because conn_idl is non-null. If we are called thru
28516 	 * service, conn_idl could be null, but it cannot change because
28517 	 * service is single-threaded per queue, and there cannot be another
28518 	 * instance of service trying to call conn_drain_insert on this conn
28519 	 * now.
28520 	 */
28521 	ASSERT(!closing || (connp->conn_idl != NULL));
28522 
28523 	/*
28524 	 * If connp->conn_idl is null, the conn has not been inserted into any
28525 	 * drain list even once since creation of the conn. Just return.
28526 	 */
28527 	if (connp->conn_idl == NULL)
28528 		return;
28529 
28530 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28531 
28532 	if (connp->conn_drain_prev == NULL) {
28533 		/* This conn is currently not in the drain list.  */
28534 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28535 		return;
28536 	}
28537 	idl = connp->conn_idl;
28538 	if (idl->idl_conn_draining == connp) {
28539 		/*
28540 		 * This conn is the current drainer. If this is the last conn
28541 		 * in the drain list, we need to do more checks, in the 'if'
28542 		 * below. Otherwwise we need to just qenable the next conn,
28543 		 * to sustain the draining, and is handled in the 'else'
28544 		 * below.
28545 		 */
28546 		if (connp->conn_drain_next == idl->idl_conn) {
28547 			/*
28548 			 * This conn is the last in this list. This round
28549 			 * of draining is complete. If idl_repeat is set,
28550 			 * it means another flow enabling has happened from
28551 			 * the driver/streams and we need to another round
28552 			 * of draining.
28553 			 * If there are more than 2 conns in the drain list,
28554 			 * do a left rotate by 1, so that all conns except the
28555 			 * conn at the head move towards the head by 1, and the
28556 			 * the conn at the head goes to the tail. This attempts
28557 			 * a more even share for all queues that are being
28558 			 * drained.
28559 			 */
28560 			if ((connp->conn_drain_next != connp) &&
28561 			    (idl->idl_conn->conn_drain_next != connp)) {
28562 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28563 			}
28564 			if (idl->idl_repeat) {
28565 				qenable(idl->idl_conn->conn_wq);
28566 				idl->idl_conn_draining = idl->idl_conn;
28567 				idl->idl_repeat = 0;
28568 			} else {
28569 				idl->idl_conn_draining = NULL;
28570 			}
28571 		} else {
28572 			/*
28573 			 * If the next queue that we are now qenable'ing,
28574 			 * is closing, it will remove itself from this list
28575 			 * and qenable the subsequent queue in ip_close().
28576 			 * Serialization is acheived thru idl_lock.
28577 			 */
28578 			qenable(connp->conn_drain_next->conn_wq);
28579 			idl->idl_conn_draining = connp->conn_drain_next;
28580 		}
28581 	}
28582 	if (!connp->conn_did_putbq || closing) {
28583 		/*
28584 		 * Remove ourself from the drain list, if we did not do
28585 		 * a putbq, or if the conn is closing.
28586 		 * Note: It is possible that q->q_first is non-null. It means
28587 		 * that these messages landed after we did a enableok() in
28588 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28589 		 * service them.
28590 		 */
28591 		if (connp->conn_drain_next == connp) {
28592 			/* Singleton in the list */
28593 			ASSERT(connp->conn_drain_prev == connp);
28594 			idl->idl_conn = NULL;
28595 			idl->idl_conn_draining = NULL;
28596 		} else {
28597 			connp->conn_drain_prev->conn_drain_next =
28598 			    connp->conn_drain_next;
28599 			connp->conn_drain_next->conn_drain_prev =
28600 			    connp->conn_drain_prev;
28601 			if (idl->idl_conn == connp)
28602 				idl->idl_conn = connp->conn_drain_next;
28603 			ASSERT(idl->idl_conn_draining != connp);
28604 
28605 		}
28606 		connp->conn_drain_next = NULL;
28607 		connp->conn_drain_prev = NULL;
28608 	}
28609 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28610 }
28611 
28612 /*
28613  * Write service routine. Shared perimeter entry point.
28614  * ip_wsrv can be called in any of the following ways.
28615  * 1. The device queue's messages has fallen below the low water mark
28616  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28617  *    the drain lists and backenable the first conn in each list.
28618  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28619  *    qenabled non-tcp upper layers. We start dequeing messages and call
28620  *    ip_wput for each message.
28621  */
28622 
28623 void
28624 ip_wsrv(queue_t *q)
28625 {
28626 	conn_t	*connp;
28627 	ill_t	*ill;
28628 	mblk_t	*mp;
28629 
28630 	if (q->q_next) {
28631 		ill = (ill_t *)q->q_ptr;
28632 		if (ill->ill_state_flags == 0) {
28633 			/*
28634 			 * The device flow control has opened up.
28635 			 * Walk through conn drain lists and qenable the
28636 			 * first conn in each list. This makes sense only
28637 			 * if the stream is fully plumbed and setup.
28638 			 * Hence the if check above.
28639 			 */
28640 			ip1dbg(("ip_wsrv: walking\n"));
28641 			conn_walk_drain(ill->ill_ipst);
28642 		}
28643 		return;
28644 	}
28645 
28646 	connp = Q_TO_CONN(q);
28647 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28648 
28649 	/*
28650 	 * 1. Set conn_draining flag to signal that service is active.
28651 	 *
28652 	 * 2. ip_output determines whether it has been called from service,
28653 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28654 	 *    has been called from service.
28655 	 *
28656 	 * 3. Message ordering is preserved by the following logic.
28657 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28658 	 *    the message at the tail, if conn_draining is set (i.e. service
28659 	 *    is running) or if q->q_first is non-null.
28660 	 *
28661 	 *    ii. If ip_output is called from service, and if ip_output cannot
28662 	 *    putnext due to flow control, it does a putbq.
28663 	 *
28664 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28665 	 *    (causing an infinite loop).
28666 	 */
28667 	ASSERT(!connp->conn_did_putbq);
28668 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28669 		connp->conn_draining = 1;
28670 		noenable(q);
28671 		while ((mp = getq(q)) != NULL) {
28672 			ASSERT(CONN_Q(q));
28673 
28674 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28675 			if (connp->conn_did_putbq) {
28676 				/* ip_wput did a putbq */
28677 				break;
28678 			}
28679 		}
28680 		/*
28681 		 * At this point, a thread coming down from top, calling
28682 		 * ip_wput, may end up queueing the message. We have not yet
28683 		 * enabled the queue, so ip_wsrv won't be called again.
28684 		 * To avoid this race, check q->q_first again (in the loop)
28685 		 * If the other thread queued the message before we call
28686 		 * enableok(), we will catch it in the q->q_first check.
28687 		 * If the other thread queues the message after we call
28688 		 * enableok(), ip_wsrv will be called again by STREAMS.
28689 		 */
28690 		connp->conn_draining = 0;
28691 		enableok(q);
28692 	}
28693 
28694 	/* Enable the next conn for draining */
28695 	conn_drain_tail(connp, B_FALSE);
28696 
28697 	connp->conn_did_putbq = 0;
28698 }
28699 
28700 /*
28701  * Walk the list of all conn's calling the function provided with the
28702  * specified argument for each.	 Note that this only walks conn's that
28703  * have been bound.
28704  * Applies to both IPv4 and IPv6.
28705  */
28706 static void
28707 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid, ip_stack_t *ipst)
28708 {
28709 	conn_walk_fanout_table(ipst->ips_ipcl_udp_fanout,
28710 	    ipst->ips_ipcl_udp_fanout_size,
28711 	    func, arg, zoneid);
28712 	conn_walk_fanout_table(ipst->ips_ipcl_conn_fanout,
28713 	    ipst->ips_ipcl_conn_fanout_size,
28714 	    func, arg, zoneid);
28715 	conn_walk_fanout_table(ipst->ips_ipcl_bind_fanout,
28716 	    ipst->ips_ipcl_bind_fanout_size,
28717 	    func, arg, zoneid);
28718 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout,
28719 	    IPPROTO_MAX, func, arg, zoneid);
28720 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout_v6,
28721 	    IPPROTO_MAX, func, arg, zoneid);
28722 }
28723 
28724 /*
28725  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28726  * of conns that need to be drained, check if drain is already in progress.
28727  * If so set the idl_repeat bit, indicating that the last conn in the list
28728  * needs to reinitiate the drain once again, for the list. If drain is not
28729  * in progress for the list, initiate the draining, by qenabling the 1st
28730  * conn in the list. The drain is self-sustaining, each qenabled conn will
28731  * in turn qenable the next conn, when it is done/blocked/closing.
28732  */
28733 static void
28734 conn_walk_drain(ip_stack_t *ipst)
28735 {
28736 	int i;
28737 	idl_t *idl;
28738 
28739 	IP_STAT(ipst, ip_conn_walk_drain);
28740 
28741 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28742 		idl = &ipst->ips_conn_drain_list[i];
28743 		mutex_enter(&idl->idl_lock);
28744 		if (idl->idl_conn == NULL) {
28745 			mutex_exit(&idl->idl_lock);
28746 			continue;
28747 		}
28748 		/*
28749 		 * If this list is not being drained currently by
28750 		 * an ip_wsrv thread, start the process.
28751 		 */
28752 		if (idl->idl_conn_draining == NULL) {
28753 			ASSERT(idl->idl_repeat == 0);
28754 			qenable(idl->idl_conn->conn_wq);
28755 			idl->idl_conn_draining = idl->idl_conn;
28756 		} else {
28757 			idl->idl_repeat = 1;
28758 		}
28759 		mutex_exit(&idl->idl_lock);
28760 	}
28761 }
28762 
28763 /*
28764  * Walk an conn hash table of `count' buckets, calling func for each entry.
28765  */
28766 static void
28767 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
28768     zoneid_t zoneid)
28769 {
28770 	conn_t	*connp;
28771 
28772 	while (count-- > 0) {
28773 		mutex_enter(&connfp->connf_lock);
28774 		for (connp = connfp->connf_head; connp != NULL;
28775 		    connp = connp->conn_next) {
28776 			if (zoneid == GLOBAL_ZONEID ||
28777 			    zoneid == connp->conn_zoneid) {
28778 				CONN_INC_REF(connp);
28779 				mutex_exit(&connfp->connf_lock);
28780 				(*func)(connp, arg);
28781 				mutex_enter(&connfp->connf_lock);
28782 				CONN_DEC_REF(connp);
28783 			}
28784 		}
28785 		mutex_exit(&connfp->connf_lock);
28786 		connfp++;
28787 	}
28788 }
28789 
28790 /* ipcl_walk routine invoked for ip_conn_report for each conn. */
28791 static void
28792 conn_report1(conn_t *connp, void *mp)
28793 {
28794 	char	buf1[INET6_ADDRSTRLEN];
28795 	char	buf2[INET6_ADDRSTRLEN];
28796 	uint_t	print_len, buf_len;
28797 
28798 	ASSERT(connp != NULL);
28799 
28800 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
28801 	if (buf_len <= 0)
28802 		return;
28803 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1));
28804 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2));
28805 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
28806 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
28807 	    "%5d %s/%05d %s/%05d\n",
28808 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
28809 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
28810 	    buf1, connp->conn_lport,
28811 	    buf2, connp->conn_fport);
28812 	if (print_len < buf_len) {
28813 		((mblk_t *)mp)->b_wptr += print_len;
28814 	} else {
28815 		((mblk_t *)mp)->b_wptr += buf_len;
28816 	}
28817 }
28818 
28819 /*
28820  * Named Dispatch routine to produce a formatted report on all conns
28821  * that are listed in one of the fanout tables.
28822  * This report is accessed by using the ndd utility to "get" ND variable
28823  * "ip_conn_status".
28824  */
28825 /* ARGSUSED */
28826 static int
28827 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
28828 {
28829 	conn_t *connp = Q_TO_CONN(q);
28830 
28831 	(void) mi_mpprintf(mp,
28832 	    "CONN      " MI_COL_HDRPAD_STR
28833 	    "rfq      " MI_COL_HDRPAD_STR
28834 	    "stq      " MI_COL_HDRPAD_STR
28835 	    " zone local                 remote");
28836 
28837 	/*
28838 	 * Because of the ndd constraint, at most we can have 64K buffer
28839 	 * to put in all conn info.  So to be more efficient, just
28840 	 * allocate a 64K buffer here, assuming we need that large buffer.
28841 	 * This should be OK as only privileged processes can do ndd /dev/ip.
28842 	 */
28843 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
28844 		/* The following may work even if we cannot get a large buf. */
28845 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
28846 		return (0);
28847 	}
28848 
28849 	conn_walk_fanout(conn_report1, mp->b_cont, connp->conn_zoneid,
28850 	    connp->conn_netstack->netstack_ip);
28851 	return (0);
28852 }
28853 
28854 /*
28855  * Determine if the ill and multicast aspects of that packets
28856  * "matches" the conn.
28857  */
28858 boolean_t
28859 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28860     zoneid_t zoneid)
28861 {
28862 	ill_t *in_ill;
28863 	boolean_t found;
28864 	ipif_t *ipif;
28865 	ire_t *ire;
28866 	ipaddr_t dst, src;
28867 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28868 
28869 	dst = ipha->ipha_dst;
28870 	src = ipha->ipha_src;
28871 
28872 	/*
28873 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28874 	 * unicast, broadcast and multicast reception to
28875 	 * conn_incoming_ill. conn_wantpacket itself is called
28876 	 * only for BROADCAST and multicast.
28877 	 *
28878 	 * 1) ip_rput supresses duplicate broadcasts if the ill
28879 	 *    is part of a group. Hence, we should be receiving
28880 	 *    just one copy of broadcast for the whole group.
28881 	 *    Thus, if it is part of the group the packet could
28882 	 *    come on any ill of the group and hence we need a
28883 	 *    match on the group. Otherwise, match on ill should
28884 	 *    be sufficient.
28885 	 *
28886 	 * 2) ip_rput does not suppress duplicate multicast packets.
28887 	 *    If there are two interfaces in a ill group and we have
28888 	 *    2 applications (conns) joined a multicast group G on
28889 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
28890 	 *    will give us two packets because we join G on both the
28891 	 *    interfaces rather than nominating just one interface
28892 	 *    for receiving multicast like broadcast above. So,
28893 	 *    we have to call ilg_lookup_ill to filter out duplicate
28894 	 *    copies, if ill is part of a group.
28895 	 */
28896 	in_ill = connp->conn_incoming_ill;
28897 	if (in_ill != NULL) {
28898 		if (in_ill->ill_group == NULL) {
28899 			if (in_ill != ill)
28900 				return (B_FALSE);
28901 		} else if (in_ill->ill_group != ill->ill_group) {
28902 			return (B_FALSE);
28903 		}
28904 	}
28905 
28906 	if (!CLASSD(dst)) {
28907 		if (IPCL_ZONE_MATCH(connp, zoneid))
28908 			return (B_TRUE);
28909 		/*
28910 		 * The conn is in a different zone; we need to check that this
28911 		 * broadcast address is configured in the application's zone and
28912 		 * on one ill in the group.
28913 		 */
28914 		ipif = ipif_get_next_ipif(NULL, ill);
28915 		if (ipif == NULL)
28916 			return (B_FALSE);
28917 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28918 		    connp->conn_zoneid, NULL,
28919 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
28920 		ipif_refrele(ipif);
28921 		if (ire != NULL) {
28922 			ire_refrele(ire);
28923 			return (B_TRUE);
28924 		} else {
28925 			return (B_FALSE);
28926 		}
28927 	}
28928 
28929 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28930 	    connp->conn_zoneid == zoneid) {
28931 		/*
28932 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28933 		 * disabled, therefore we don't dispatch the multicast packet to
28934 		 * the sending zone.
28935 		 */
28936 		return (B_FALSE);
28937 	}
28938 
28939 	if (IS_LOOPBACK(ill) && connp->conn_zoneid != zoneid) {
28940 		/*
28941 		 * Multicast packet on the loopback interface: we only match
28942 		 * conns who joined the group in the specified zone.
28943 		 */
28944 		return (B_FALSE);
28945 	}
28946 
28947 	if (connp->conn_multi_router) {
28948 		/* multicast packet and multicast router socket: send up */
28949 		return (B_TRUE);
28950 	}
28951 
28952 	mutex_enter(&connp->conn_lock);
28953 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28954 	mutex_exit(&connp->conn_lock);
28955 	return (found);
28956 }
28957 
28958 /*
28959  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28960  */
28961 /* ARGSUSED */
28962 static void
28963 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28964 {
28965 	ill_t *ill = (ill_t *)q->q_ptr;
28966 	mblk_t	*mp1, *mp2;
28967 	ipif_t  *ipif;
28968 	int err = 0;
28969 	conn_t *connp = NULL;
28970 	ipsq_t	*ipsq;
28971 	arc_t	*arc;
28972 
28973 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28974 
28975 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28976 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28977 
28978 	ASSERT(IAM_WRITER_ILL(ill));
28979 	mp2 = mp->b_cont;
28980 	mp->b_cont = NULL;
28981 
28982 	/*
28983 	 * We have now received the arp bringup completion message
28984 	 * from ARP. Mark the arp bringup as done. Also if the arp
28985 	 * stream has already started closing, send up the AR_ARP_CLOSING
28986 	 * ack now since ARP is waiting in close for this ack.
28987 	 */
28988 	mutex_enter(&ill->ill_lock);
28989 	ill->ill_arp_bringup_pending = 0;
28990 	if (ill->ill_arp_closing) {
28991 		mutex_exit(&ill->ill_lock);
28992 		/* Let's reuse the mp for sending the ack */
28993 		arc = (arc_t *)mp->b_rptr;
28994 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28995 		arc->arc_cmd = AR_ARP_CLOSING;
28996 		qreply(q, mp);
28997 	} else {
28998 		mutex_exit(&ill->ill_lock);
28999 		freeb(mp);
29000 	}
29001 
29002 	ipsq = ill->ill_phyint->phyint_ipsq;
29003 	ipif = ipsq->ipsq_pending_ipif;
29004 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
29005 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
29006 	if (mp1 == NULL) {
29007 		/* bringup was aborted by the user */
29008 		freemsg(mp2);
29009 		return;
29010 	}
29011 
29012 	/*
29013 	 * If an IOCTL is waiting on this (ipsq_current_ioctl != 0), then we
29014 	 * must have an associated conn_t.  Otherwise, we're bringing this
29015 	 * interface back up as part of handling an asynchronous event (e.g.,
29016 	 * physical address change).
29017 	 */
29018 	if (ipsq->ipsq_current_ioctl != 0) {
29019 		ASSERT(connp != NULL);
29020 		q = CONNP_TO_WQ(connp);
29021 	} else {
29022 		ASSERT(connp == NULL);
29023 		q = ill->ill_rq;
29024 	}
29025 
29026 	/*
29027 	 * If the DL_BIND_REQ fails, it is noted
29028 	 * in arc_name_offset.
29029 	 */
29030 	err = *((int *)mp2->b_rptr);
29031 	if (err == 0) {
29032 		if (ipif->ipif_isv6) {
29033 			if ((err = ipif_up_done_v6(ipif)) != 0)
29034 				ip0dbg(("ip_arp_done: init failed\n"));
29035 		} else {
29036 			if ((err = ipif_up_done(ipif)) != 0)
29037 				ip0dbg(("ip_arp_done: init failed\n"));
29038 		}
29039 	} else {
29040 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
29041 	}
29042 
29043 	freemsg(mp2);
29044 
29045 	if ((err == 0) && (ill->ill_up_ipifs)) {
29046 		err = ill_up_ipifs(ill, q, mp1);
29047 		if (err == EINPROGRESS)
29048 			return;
29049 	}
29050 
29051 	if (ill->ill_up_ipifs)
29052 		ill_group_cleanup(ill);
29053 
29054 	/*
29055 	 * The operation must complete without EINPROGRESS since
29056 	 * ipsq_pending_mp_get() has removed the mblk from ipsq_pending_mp.
29057 	 * Otherwise, the operation will be stuck forever in the ipsq.
29058 	 */
29059 	ASSERT(err != EINPROGRESS);
29060 	if (ipsq->ipsq_current_ioctl != 0)
29061 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
29062 	else
29063 		ipsq_current_finish(ipsq);
29064 }
29065 
29066 /* Allocate the private structure */
29067 static int
29068 ip_priv_alloc(void **bufp)
29069 {
29070 	void	*buf;
29071 
29072 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
29073 		return (ENOMEM);
29074 
29075 	*bufp = buf;
29076 	return (0);
29077 }
29078 
29079 /* Function to delete the private structure */
29080 void
29081 ip_priv_free(void *buf)
29082 {
29083 	ASSERT(buf != NULL);
29084 	kmem_free(buf, sizeof (ip_priv_t));
29085 }
29086 
29087 /*
29088  * The entry point for IPPF processing.
29089  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
29090  * routine just returns.
29091  *
29092  * When called, ip_process generates an ipp_packet_t structure
29093  * which holds the state information for this packet and invokes the
29094  * the classifier (via ipp_packet_process). The classification, depending on
29095  * configured filters, results in a list of actions for this packet. Invoking
29096  * an action may cause the packet to be dropped, in which case the resulting
29097  * mblk (*mpp) is NULL. proc indicates the callout position for
29098  * this packet and ill_index is the interface this packet on or will leave
29099  * on (inbound and outbound resp.).
29100  */
29101 void
29102 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
29103 {
29104 	mblk_t		*mp;
29105 	ip_priv_t	*priv;
29106 	ipp_action_id_t	aid;
29107 	int		rc = 0;
29108 	ipp_packet_t	*pp;
29109 #define	IP_CLASS	"ip"
29110 
29111 	/* If the classifier is not loaded, return  */
29112 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
29113 		return;
29114 	}
29115 
29116 	mp = *mpp;
29117 	ASSERT(mp != NULL);
29118 
29119 	/* Allocate the packet structure */
29120 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
29121 	if (rc != 0) {
29122 		*mpp = NULL;
29123 		freemsg(mp);
29124 		return;
29125 	}
29126 
29127 	/* Allocate the private structure */
29128 	rc = ip_priv_alloc((void **)&priv);
29129 	if (rc != 0) {
29130 		*mpp = NULL;
29131 		freemsg(mp);
29132 		ipp_packet_free(pp);
29133 		return;
29134 	}
29135 	priv->proc = proc;
29136 	priv->ill_index = ill_index;
29137 	ipp_packet_set_private(pp, priv, ip_priv_free);
29138 	ipp_packet_set_data(pp, mp);
29139 
29140 	/* Invoke the classifier */
29141 	rc = ipp_packet_process(&pp);
29142 	if (pp != NULL) {
29143 		mp = ipp_packet_get_data(pp);
29144 		ipp_packet_free(pp);
29145 		if (rc != 0) {
29146 			freemsg(mp);
29147 			*mpp = NULL;
29148 		}
29149 	} else {
29150 		*mpp = NULL;
29151 	}
29152 #undef	IP_CLASS
29153 }
29154 
29155 /*
29156  * Propagate a multicast group membership operation (add/drop) on
29157  * all the interfaces crossed by the related multirt routes.
29158  * The call is considered successful if the operation succeeds
29159  * on at least one interface.
29160  */
29161 static int
29162 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
29163     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
29164     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
29165     mblk_t *first_mp)
29166 {
29167 	ire_t		*ire_gw;
29168 	irb_t		*irb;
29169 	int		error = 0;
29170 	opt_restart_t	*or;
29171 	ip_stack_t	*ipst = ire->ire_ipst;
29172 
29173 	irb = ire->ire_bucket;
29174 	ASSERT(irb != NULL);
29175 
29176 	ASSERT(DB_TYPE(first_mp) == M_CTL);
29177 
29178 	or = (opt_restart_t *)first_mp->b_rptr;
29179 	IRB_REFHOLD(irb);
29180 	for (; ire != NULL; ire = ire->ire_next) {
29181 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
29182 			continue;
29183 		if (ire->ire_addr != group)
29184 			continue;
29185 
29186 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
29187 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
29188 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
29189 		/* No resolver exists for the gateway; skip this ire. */
29190 		if (ire_gw == NULL)
29191 			continue;
29192 
29193 		/*
29194 		 * This function can return EINPROGRESS. If so the operation
29195 		 * will be restarted from ip_restart_optmgmt which will
29196 		 * call ip_opt_set and option processing will restart for
29197 		 * this option. So we may end up calling 'fn' more than once.
29198 		 * This requires that 'fn' is idempotent except for the
29199 		 * return value. The operation is considered a success if
29200 		 * it succeeds at least once on any one interface.
29201 		 */
29202 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
29203 		    NULL, fmode, src, first_mp);
29204 		if (error == 0)
29205 			or->or_private = CGTP_MCAST_SUCCESS;
29206 
29207 		if (ip_debug > 0) {
29208 			ulong_t	off;
29209 			char	*ksym;
29210 			ksym = kobj_getsymname((uintptr_t)fn, &off);
29211 			ip2dbg(("ip_multirt_apply_membership: "
29212 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
29213 			    "error %d [success %u]\n",
29214 			    ksym ? ksym : "?",
29215 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
29216 			    error, or->or_private));
29217 		}
29218 
29219 		ire_refrele(ire_gw);
29220 		if (error == EINPROGRESS) {
29221 			IRB_REFRELE(irb);
29222 			return (error);
29223 		}
29224 	}
29225 	IRB_REFRELE(irb);
29226 	/*
29227 	 * Consider the call as successful if we succeeded on at least
29228 	 * one interface. Otherwise, return the last encountered error.
29229 	 */
29230 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
29231 }
29232 
29233 
29234 /*
29235  * Issue a warning regarding a route crossing an interface with an
29236  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
29237  * amount of time is logged.
29238  */
29239 static void
29240 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
29241 {
29242 	hrtime_t	current = gethrtime();
29243 	char		buf[INET_ADDRSTRLEN];
29244 	ip_stack_t	*ipst = ire->ire_ipst;
29245 
29246 	/* Convert interval in ms to hrtime in ns */
29247 	if (ipst->ips_multirt_bad_mtu_last_time +
29248 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
29249 	    current) {
29250 		cmn_err(CE_WARN, "ip: ignoring multiroute "
29251 		    "to %s, incorrect MTU %u (expected %u)\n",
29252 		    ip_dot_addr(ire->ire_addr, buf),
29253 		    ire->ire_max_frag, max_frag);
29254 
29255 		ipst->ips_multirt_bad_mtu_last_time = current;
29256 	}
29257 }
29258 
29259 
29260 /*
29261  * Get the CGTP (multirouting) filtering status.
29262  * If 0, the CGTP hooks are transparent.
29263  */
29264 /* ARGSUSED */
29265 static int
29266 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
29267 {
29268 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
29269 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29270 
29271 	/*
29272 	 * Only applies to the shared stack since the filter_ops
29273 	 * do not carry an ip_stack_t or zoneid.
29274 	 */
29275 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
29276 		return (ENOTSUP);
29277 
29278 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
29279 	return (0);
29280 }
29281 
29282 
29283 /*
29284  * Set the CGTP (multirouting) filtering status.
29285  * If the status is changed from active to transparent
29286  * or from transparent to active, forward the new status
29287  * to the filtering module (if loaded).
29288  */
29289 /* ARGSUSED */
29290 static int
29291 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
29292     cred_t *ioc_cr)
29293 {
29294 	long		new_value;
29295 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
29296 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29297 
29298 	if (secpolicy_net_config(ioc_cr, B_FALSE) != 0)
29299 		return (EPERM);
29300 
29301 	/*
29302 	 * Only applies to the shared stack since the filter_ops
29303 	 * do not carry an ip_stack_t or zoneid.
29304 	 */
29305 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
29306 		return (ENOTSUP);
29307 
29308 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
29309 	    new_value < 0 || new_value > 1) {
29310 		return (EINVAL);
29311 	}
29312 
29313 	/*
29314 	 * Do not enable CGTP filtering - thus preventing the hooks
29315 	 * from being invoked - if the version number of the
29316 	 * filtering module hooks does not match.
29317 	 */
29318 	if ((ip_cgtp_filter_ops != NULL) &&
29319 	    (ip_cgtp_filter_ops->cfo_filter_rev != CGTP_FILTER_REV)) {
29320 		cmn_err(CE_WARN, "IP: CGTP filtering version mismatch "
29321 		    "(module hooks version %d, expecting %d)\n",
29322 		    ip_cgtp_filter_ops->cfo_filter_rev,
29323 		    CGTP_FILTER_REV);
29324 		return (ENOTSUP);
29325 	}
29326 
29327 	if ((!*ip_cgtp_filter_value) && new_value) {
29328 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
29329 		    ip_cgtp_filter_ops == NULL ?
29330 		    " (module not loaded)" : "");
29331 	}
29332 	if (*ip_cgtp_filter_value && (!new_value)) {
29333 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
29334 		    ip_cgtp_filter_ops == NULL ?
29335 		    " (module not loaded)" : "");
29336 	}
29337 
29338 	if (ip_cgtp_filter_ops != NULL) {
29339 		int	res;
29340 
29341 		res = ip_cgtp_filter_ops->cfo_change_state(new_value);
29342 		if (res)
29343 			return (res);
29344 	}
29345 
29346 	*ip_cgtp_filter_value = (boolean_t)new_value;
29347 
29348 	return (0);
29349 }
29350 
29351 
29352 /*
29353  * Return the expected CGTP hooks version number.
29354  */
29355 int
29356 ip_cgtp_filter_supported(void)
29357 {
29358 	ip_stack_t *ipst;
29359 	int ret;
29360 
29361 	ipst = netstack_find_by_stackid(GLOBAL_NETSTACKID)->netstack_ip;
29362 	if (ipst == NULL)
29363 		return (-1);
29364 	ret = ip_cgtp_filter_rev;
29365 	netstack_rele(ipst->ips_netstack);
29366 	return (ret);
29367 }
29368 
29369 
29370 /*
29371  * CGTP hooks can be registered by directly touching ip_cgtp_filter_ops
29372  * or by invoking this function. In the first case, the version number
29373  * of the registered structure is checked at hooks activation time
29374  * in ip_cgtp_filter_set().
29375  *
29376  * Only applies to the shared stack since the filter_ops
29377  * do not carry an ip_stack_t or zoneid.
29378  */
29379 int
29380 ip_cgtp_filter_register(cgtp_filter_ops_t *ops)
29381 {
29382 	ip_stack_t *ipst;
29383 
29384 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
29385 		return (ENOTSUP);
29386 
29387 	ipst = netstack_find_by_stackid(GLOBAL_NETSTACKID)->netstack_ip;
29388 	if (ipst == NULL)
29389 		return (EINVAL);
29390 
29391 	ip_cgtp_filter_ops = ops;
29392 	netstack_rele(ipst->ips_netstack);
29393 	return (0);
29394 }
29395 
29396 static squeue_func_t
29397 ip_squeue_switch(int val)
29398 {
29399 	squeue_func_t rval = squeue_fill;
29400 
29401 	switch (val) {
29402 	case IP_SQUEUE_ENTER_NODRAIN:
29403 		rval = squeue_enter_nodrain;
29404 		break;
29405 	case IP_SQUEUE_ENTER:
29406 		rval = squeue_enter;
29407 		break;
29408 	default:
29409 		break;
29410 	}
29411 	return (rval);
29412 }
29413 
29414 /* ARGSUSED */
29415 static int
29416 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
29417     caddr_t addr, cred_t *cr)
29418 {
29419 	int *v = (int *)addr;
29420 	long new_value;
29421 
29422 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29423 		return (EPERM);
29424 
29425 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29426 		return (EINVAL);
29427 
29428 	ip_input_proc = ip_squeue_switch(new_value);
29429 	*v = new_value;
29430 	return (0);
29431 }
29432 
29433 /* ARGSUSED */
29434 static int
29435 ip_int_set(queue_t *q, mblk_t *mp, char *value,
29436     caddr_t addr, cred_t *cr)
29437 {
29438 	int *v = (int *)addr;
29439 	long new_value;
29440 
29441 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29442 		return (EPERM);
29443 
29444 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29445 		return (EINVAL);
29446 
29447 	*v = new_value;
29448 	return (0);
29449 }
29450 
29451 /*
29452  * Handle changes to ipmp_hook_emulation ndd variable.
29453  * Need to update phyint_hook_ifindex.
29454  * Also generate a nic plumb event should a new ifidex be assigned to a group.
29455  */
29456 static void
29457 ipmp_hook_emulation_changed(ip_stack_t *ipst)
29458 {
29459 	phyint_t *phyi;
29460 	phyint_t *phyi_tmp;
29461 	char *groupname;
29462 	int namelen;
29463 	ill_t	*ill;
29464 	boolean_t new_group;
29465 
29466 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29467 	/*
29468 	 * Group indicies are stored in the phyint - a common structure
29469 	 * to both IPv4 and IPv6.
29470 	 */
29471 	phyi = avl_first(&ipst->ips_phyint_g_list->phyint_list_avl_by_index);
29472 	for (; phyi != NULL;
29473 	    phyi = avl_walk(&ipst->ips_phyint_g_list->phyint_list_avl_by_index,
29474 	    phyi, AVL_AFTER)) {
29475 		/* Ignore the ones that do not have a group */
29476 		if (phyi->phyint_groupname_len == 0)
29477 			continue;
29478 
29479 		/*
29480 		 * Look for other phyint in group.
29481 		 * Clear name/namelen so the lookup doesn't find ourselves.
29482 		 */
29483 		namelen = phyi->phyint_groupname_len;
29484 		groupname = phyi->phyint_groupname;
29485 		phyi->phyint_groupname_len = 0;
29486 		phyi->phyint_groupname = NULL;
29487 
29488 		phyi_tmp = phyint_lookup_group(groupname, B_FALSE, ipst);
29489 		/* Restore */
29490 		phyi->phyint_groupname_len = namelen;
29491 		phyi->phyint_groupname = groupname;
29492 
29493 		new_group = B_FALSE;
29494 		if (ipst->ips_ipmp_hook_emulation) {
29495 			/*
29496 			 * If the group already exists and has already
29497 			 * been assigned a group ifindex, we use the existing
29498 			 * group_ifindex, otherwise we pick a new group_ifindex
29499 			 * here.
29500 			 */
29501 			if (phyi_tmp != NULL &&
29502 			    phyi_tmp->phyint_group_ifindex != 0) {
29503 				phyi->phyint_group_ifindex =
29504 				    phyi_tmp->phyint_group_ifindex;
29505 			} else {
29506 				/* XXX We need a recovery strategy here. */
29507 				if (!ip_assign_ifindex(
29508 				    &phyi->phyint_group_ifindex, ipst))
29509 					cmn_err(CE_PANIC,
29510 					    "ip_assign_ifindex() failed");
29511 				new_group = B_TRUE;
29512 			}
29513 		} else {
29514 			phyi->phyint_group_ifindex = 0;
29515 		}
29516 		if (ipst->ips_ipmp_hook_emulation)
29517 			phyi->phyint_hook_ifindex = phyi->phyint_group_ifindex;
29518 		else
29519 			phyi->phyint_hook_ifindex = phyi->phyint_ifindex;
29520 
29521 		/*
29522 		 * For IP Filter to find out the relationship between
29523 		 * names and interface indicies, we need to generate
29524 		 * a NE_PLUMB event when a new group can appear.
29525 		 * We always generate events when a new interface appears
29526 		 * (even when ipmp_hook_emulation is set) so there
29527 		 * is no need to generate NE_PLUMB events when
29528 		 * ipmp_hook_emulation is turned off.
29529 		 * And since it isn't critical for IP Filter to get
29530 		 * the NE_UNPLUMB events we skip those here.
29531 		 */
29532 		if (new_group) {
29533 			/*
29534 			 * First phyint in group - generate group PLUMB event.
29535 			 * Since we are not running inside the ipsq we do
29536 			 * the dispatch immediately.
29537 			 */
29538 			if (phyi->phyint_illv4 != NULL)
29539 				ill = phyi->phyint_illv4;
29540 			else
29541 				ill = phyi->phyint_illv6;
29542 
29543 			if (ill != NULL) {
29544 				mutex_enter(&ill->ill_lock);
29545 				ill_nic_info_plumb(ill, B_TRUE);
29546 				ill_nic_info_dispatch(ill);
29547 				mutex_exit(&ill->ill_lock);
29548 			}
29549 		}
29550 	}
29551 	rw_exit(&ipst->ips_ill_g_lock);
29552 }
29553 
29554 /* ARGSUSED */
29555 static int
29556 ipmp_hook_emulation_set(queue_t *q, mblk_t *mp, char *value,
29557     caddr_t addr, cred_t *cr)
29558 {
29559 	int *v = (int *)addr;
29560 	long new_value;
29561 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29562 
29563 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29564 		return (EINVAL);
29565 
29566 	if (*v != new_value) {
29567 		*v = new_value;
29568 		ipmp_hook_emulation_changed(ipst);
29569 	}
29570 	return (0);
29571 }
29572 
29573 static void *
29574 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
29575 {
29576 	kstat_t *ksp;
29577 
29578 	ip_stat_t template = {
29579 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
29580 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
29581 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
29582 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
29583 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
29584 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
29585 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
29586 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
29587 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
29588 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
29589 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
29590 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
29591 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
29592 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
29593 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
29594 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
29595 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
29596 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
29597 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
29598 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
29599 		{ "ip_opt",			KSTAT_DATA_UINT64 },
29600 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
29601 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
29602 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29603 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29604 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29605 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29606 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29607 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29608 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29609 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29610 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29611 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29612 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29613 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29614 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29615 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29616 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29617 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29618 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29619 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29620 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29621 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29622 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29623 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29624 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29625 	};
29626 
29627 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29628 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29629 	    KSTAT_FLAG_VIRTUAL, stackid);
29630 
29631 	if (ksp == NULL)
29632 		return (NULL);
29633 
29634 	bcopy(&template, ip_statisticsp, sizeof (template));
29635 	ksp->ks_data = (void *)ip_statisticsp;
29636 	ksp->ks_private = (void *)(uintptr_t)stackid;
29637 
29638 	kstat_install(ksp);
29639 	return (ksp);
29640 }
29641 
29642 static void
29643 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29644 {
29645 	if (ksp != NULL) {
29646 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29647 		kstat_delete_netstack(ksp, stackid);
29648 	}
29649 }
29650 
29651 static void *
29652 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29653 {
29654 	kstat_t	*ksp;
29655 
29656 	ip_named_kstat_t template = {
29657 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29658 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29659 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29660 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29661 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29662 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29663 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29664 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29665 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29666 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29667 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29668 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29669 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29670 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29671 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29672 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29673 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29674 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29675 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29676 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29677 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29678 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29679 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29680 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29681 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29682 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29683 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29684 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29685 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29686 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29687 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29688 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29689 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29690 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29691 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29692 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29693 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29694 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29695 	};
29696 
29697 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29698 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
29699 	if (ksp == NULL || ksp->ks_data == NULL)
29700 		return (NULL);
29701 
29702 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29703 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29704 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29705 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29706 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29707 
29708 	template.netToMediaEntrySize.value.i32 =
29709 	    sizeof (mib2_ipNetToMediaEntry_t);
29710 
29711 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29712 
29713 	bcopy(&template, ksp->ks_data, sizeof (template));
29714 	ksp->ks_update = ip_kstat_update;
29715 	ksp->ks_private = (void *)(uintptr_t)stackid;
29716 
29717 	kstat_install(ksp);
29718 	return (ksp);
29719 }
29720 
29721 static void
29722 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29723 {
29724 	if (ksp != NULL) {
29725 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29726 		kstat_delete_netstack(ksp, stackid);
29727 	}
29728 }
29729 
29730 static int
29731 ip_kstat_update(kstat_t *kp, int rw)
29732 {
29733 	ip_named_kstat_t *ipkp;
29734 	mib2_ipIfStatsEntry_t ipmib;
29735 	ill_walk_context_t ctx;
29736 	ill_t *ill;
29737 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29738 	netstack_t	*ns;
29739 	ip_stack_t	*ipst;
29740 
29741 	if (kp == NULL || kp->ks_data == NULL)
29742 		return (EIO);
29743 
29744 	if (rw == KSTAT_WRITE)
29745 		return (EACCES);
29746 
29747 	ns = netstack_find_by_stackid(stackid);
29748 	if (ns == NULL)
29749 		return (-1);
29750 	ipst = ns->netstack_ip;
29751 	if (ipst == NULL) {
29752 		netstack_rele(ns);
29753 		return (-1);
29754 	}
29755 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29756 
29757 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29758 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29759 	ill = ILL_START_WALK_V4(&ctx, ipst);
29760 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29761 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29762 	rw_exit(&ipst->ips_ill_g_lock);
29763 
29764 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29765 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29766 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29767 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29768 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29769 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29770 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29771 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29772 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29773 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29774 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29775 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29776 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29777 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29778 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29779 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29780 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29781 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29782 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29783 
29784 	ipkp->routingDiscards.value.ui32 =	0;
29785 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29786 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29787 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29788 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29789 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29790 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29791 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29792 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29793 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29794 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29795 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29796 
29797 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29798 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29799 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29800 
29801 	netstack_rele(ns);
29802 
29803 	return (0);
29804 }
29805 
29806 static void *
29807 icmp_kstat_init(netstackid_t stackid)
29808 {
29809 	kstat_t	*ksp;
29810 
29811 	icmp_named_kstat_t template = {
29812 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29813 		{ "inErrors",		KSTAT_DATA_UINT32 },
29814 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29815 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29816 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29817 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29818 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29819 		{ "inEchos",		KSTAT_DATA_UINT32 },
29820 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29821 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29822 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29823 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29824 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29825 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29826 		{ "outErrors",		KSTAT_DATA_UINT32 },
29827 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29828 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29829 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29830 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29831 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29832 		{ "outEchos",		KSTAT_DATA_UINT32 },
29833 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29834 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29835 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29836 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29837 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29838 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29839 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29840 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29841 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29842 		{ "outDrops",		KSTAT_DATA_UINT32 },
29843 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29844 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29845 	};
29846 
29847 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29848 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
29849 	if (ksp == NULL || ksp->ks_data == NULL)
29850 		return (NULL);
29851 
29852 	bcopy(&template, ksp->ks_data, sizeof (template));
29853 
29854 	ksp->ks_update = icmp_kstat_update;
29855 	ksp->ks_private = (void *)(uintptr_t)stackid;
29856 
29857 	kstat_install(ksp);
29858 	return (ksp);
29859 }
29860 
29861 static void
29862 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29863 {
29864 	if (ksp != NULL) {
29865 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29866 		kstat_delete_netstack(ksp, stackid);
29867 	}
29868 }
29869 
29870 static int
29871 icmp_kstat_update(kstat_t *kp, int rw)
29872 {
29873 	icmp_named_kstat_t *icmpkp;
29874 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29875 	netstack_t	*ns;
29876 	ip_stack_t	*ipst;
29877 
29878 	if ((kp == NULL) || (kp->ks_data == NULL))
29879 		return (EIO);
29880 
29881 	if (rw == KSTAT_WRITE)
29882 		return (EACCES);
29883 
29884 	ns = netstack_find_by_stackid(stackid);
29885 	if (ns == NULL)
29886 		return (-1);
29887 	ipst = ns->netstack_ip;
29888 	if (ipst == NULL) {
29889 		netstack_rele(ns);
29890 		return (-1);
29891 	}
29892 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29893 
29894 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29895 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29896 	icmpkp->inDestUnreachs.value.ui32 =
29897 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29898 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29899 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29900 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29901 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29902 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29903 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29904 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29905 	icmpkp->inTimestampReps.value.ui32 =
29906 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29907 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29908 	icmpkp->inAddrMaskReps.value.ui32 =
29909 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29910 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29911 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29912 	icmpkp->outDestUnreachs.value.ui32 =
29913 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29914 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29915 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29916 	icmpkp->outSrcQuenchs.value.ui32 =
29917 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29918 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29919 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29920 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29921 	icmpkp->outTimestamps.value.ui32 =
29922 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29923 	icmpkp->outTimestampReps.value.ui32 =
29924 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29925 	icmpkp->outAddrMasks.value.ui32 =
29926 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29927 	icmpkp->outAddrMaskReps.value.ui32 =
29928 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29929 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29930 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29931 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29932 	icmpkp->outFragNeeded.value.ui32 =
29933 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29934 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29935 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29936 	icmpkp->inBadRedirects.value.ui32 =
29937 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29938 
29939 	netstack_rele(ns);
29940 	return (0);
29941 }
29942 
29943 /*
29944  * This is the fanout function for raw socket opened for SCTP.  Note
29945  * that it is called after SCTP checks that there is no socket which
29946  * wants a packet.  Then before SCTP handles this out of the blue packet,
29947  * this function is called to see if there is any raw socket for SCTP.
29948  * If there is and it is bound to the correct address, the packet will
29949  * be sent to that socket.  Note that only one raw socket can be bound to
29950  * a port.  This is assured in ipcl_sctp_hash_insert();
29951  */
29952 void
29953 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29954     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29955     zoneid_t zoneid)
29956 {
29957 	conn_t		*connp;
29958 	queue_t		*rq;
29959 	mblk_t		*first_mp;
29960 	boolean_t	secure;
29961 	ip6_t		*ip6h;
29962 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29963 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29964 
29965 	first_mp = mp;
29966 	if (mctl_present) {
29967 		mp = first_mp->b_cont;
29968 		secure = ipsec_in_is_secure(first_mp);
29969 		ASSERT(mp != NULL);
29970 	} else {
29971 		secure = B_FALSE;
29972 	}
29973 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29974 
29975 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29976 	if (connp == NULL) {
29977 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29978 		return;
29979 	}
29980 	rq = connp->conn_rq;
29981 	if (!canputnext(rq)) {
29982 		CONN_DEC_REF(connp);
29983 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29984 		freemsg(first_mp);
29985 		return;
29986 	}
29987 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29988 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29989 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29990 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29991 		if (first_mp == NULL) {
29992 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29993 			CONN_DEC_REF(connp);
29994 			return;
29995 		}
29996 	}
29997 	/*
29998 	 * We probably should not send M_CTL message up to
29999 	 * raw socket.
30000 	 */
30001 	if (mctl_present)
30002 		freeb(first_mp);
30003 
30004 	/* Initiate IPPF processing here if needed. */
30005 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
30006 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
30007 		ip_process(IPP_LOCAL_IN, &mp,
30008 		    recv_ill->ill_phyint->phyint_ifindex);
30009 		if (mp == NULL) {
30010 			CONN_DEC_REF(connp);
30011 			return;
30012 		}
30013 	}
30014 
30015 	if (connp->conn_recvif || connp->conn_recvslla ||
30016 	    ((connp->conn_ip_recvpktinfo ||
30017 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
30018 	    (flags & IP_FF_IPINFO))) {
30019 		int in_flags = 0;
30020 
30021 		/*
30022 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
30023 		 * IPF_RECVIF.
30024 		 */
30025 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
30026 			in_flags = IPF_RECVIF;
30027 		}
30028 		if (connp->conn_recvslla) {
30029 			in_flags |= IPF_RECVSLLA;
30030 		}
30031 		if (isv4) {
30032 			mp = ip_add_info(mp, recv_ill, in_flags,
30033 			    IPCL_ZONEID(connp), ipst);
30034 		} else {
30035 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
30036 			if (mp == NULL) {
30037 				BUMP_MIB(recv_ill->ill_ip_mib,
30038 				    ipIfStatsInDiscards);
30039 				CONN_DEC_REF(connp);
30040 				return;
30041 			}
30042 		}
30043 	}
30044 
30045 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
30046 	/*
30047 	 * We are sending the IPSEC_IN message also up. Refer
30048 	 * to comments above this function.
30049 	 */
30050 	putnext(rq, mp);
30051 	CONN_DEC_REF(connp);
30052 }
30053 
30054 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
30055 {									\
30056 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
30057 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
30058 }
30059 /*
30060  * This function should be called only if all packet processing
30061  * including fragmentation is complete. Callers of this function
30062  * must set mp->b_prev to one of these values:
30063  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
30064  * prior to handing over the mp as first argument to this function.
30065  *
30066  * If the ire passed by caller is incomplete, this function
30067  * queues the packet and if necessary, sends ARP request and bails.
30068  * If the ire passed is fully resolved, we simply prepend
30069  * the link-layer header to the packet, do ipsec hw acceleration
30070  * work if necessary, and send the packet out on the wire.
30071  *
30072  * NOTE: IPSEC will only call this function with fully resolved
30073  * ires if hw acceleration is involved.
30074  * TODO list :
30075  * 	a Handle M_MULTIDATA so that
30076  *	  tcp_multisend->tcp_multisend_data can
30077  *	  call ip_xmit_v4 directly
30078  *	b Handle post-ARP work for fragments so that
30079  *	  ip_wput_frag can call this function.
30080  */
30081 ipxmit_state_t
30082 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io, boolean_t flow_ctl_enabled)
30083 {
30084 	nce_t		*arpce;
30085 	queue_t		*q;
30086 	int		ill_index;
30087 	mblk_t		*nxt_mp, *first_mp;
30088 	boolean_t	xmit_drop = B_FALSE;
30089 	ip_proc_t	proc;
30090 	ill_t		*out_ill;
30091 	int		pkt_len;
30092 
30093 	arpce = ire->ire_nce;
30094 	ASSERT(arpce != NULL);
30095 
30096 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
30097 
30098 	mutex_enter(&arpce->nce_lock);
30099 	switch (arpce->nce_state) {
30100 	case ND_REACHABLE:
30101 		/* If there are other queued packets, queue this packet */
30102 		if (arpce->nce_qd_mp != NULL) {
30103 			if (mp != NULL)
30104 				nce_queue_mp_common(arpce, mp, B_FALSE);
30105 			mp = arpce->nce_qd_mp;
30106 		}
30107 		arpce->nce_qd_mp = NULL;
30108 		mutex_exit(&arpce->nce_lock);
30109 
30110 		/*
30111 		 * Flush the queue.  In the common case, where the
30112 		 * ARP is already resolved,  it will go through the
30113 		 * while loop only once.
30114 		 */
30115 		while (mp != NULL) {
30116 
30117 			nxt_mp = mp->b_next;
30118 			mp->b_next = NULL;
30119 			ASSERT(mp->b_datap->db_type != M_CTL);
30120 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
30121 			/*
30122 			 * This info is needed for IPQOS to do COS marking
30123 			 * in ip_wput_attach_llhdr->ip_process.
30124 			 */
30125 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
30126 			mp->b_prev = NULL;
30127 
30128 			/* set up ill index for outbound qos processing */
30129 			out_ill = ire->ire_ipif->ipif_ill;
30130 			ill_index = out_ill->ill_phyint->phyint_ifindex;
30131 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
30132 			    ill_index);
30133 			if (first_mp == NULL) {
30134 				xmit_drop = B_TRUE;
30135 				BUMP_MIB(out_ill->ill_ip_mib,
30136 				    ipIfStatsOutDiscards);
30137 				goto next_mp;
30138 			}
30139 			/* non-ipsec hw accel case */
30140 			if (io == NULL || !io->ipsec_out_accelerated) {
30141 				/* send it */
30142 				q = ire->ire_stq;
30143 				if (proc == IPP_FWD_OUT) {
30144 					UPDATE_IB_PKT_COUNT(ire);
30145 				} else {
30146 					UPDATE_OB_PKT_COUNT(ire);
30147 				}
30148 				ire->ire_last_used_time = lbolt;
30149 
30150 				if (flow_ctl_enabled || canputnext(q)) {
30151 					if (proc == IPP_FWD_OUT) {
30152 
30153 					BUMP_MIB(out_ill->ill_ip_mib,
30154 					    ipIfStatsHCOutForwDatagrams);
30155 
30156 					}
30157 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
30158 					    pkt_len);
30159 
30160 					putnext(q, first_mp);
30161 				} else {
30162 					BUMP_MIB(out_ill->ill_ip_mib,
30163 					    ipIfStatsOutDiscards);
30164 					xmit_drop = B_TRUE;
30165 					freemsg(first_mp);
30166 				}
30167 			} else {
30168 				/*
30169 				 * Safety Pup says: make sure this
30170 				 *  is going to the right interface!
30171 				 */
30172 				ill_t *ill1 =
30173 				    (ill_t *)ire->ire_stq->q_ptr;
30174 				int ifindex =
30175 				    ill1->ill_phyint->phyint_ifindex;
30176 				if (ifindex !=
30177 				    io->ipsec_out_capab_ill_index) {
30178 					xmit_drop = B_TRUE;
30179 					freemsg(mp);
30180 				} else {
30181 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
30182 					    pkt_len);
30183 					ipsec_hw_putnext(ire->ire_stq, mp);
30184 				}
30185 			}
30186 next_mp:
30187 			mp = nxt_mp;
30188 		} /* while (mp != NULL) */
30189 		if (xmit_drop)
30190 			return (SEND_FAILED);
30191 		else
30192 			return (SEND_PASSED);
30193 
30194 	case ND_INITIAL:
30195 	case ND_INCOMPLETE:
30196 
30197 		/*
30198 		 * While we do send off packets to dests that
30199 		 * use fully-resolved CGTP routes, we do not
30200 		 * handle unresolved CGTP routes.
30201 		 */
30202 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
30203 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
30204 
30205 		if (mp != NULL) {
30206 			/* queue the packet */
30207 			nce_queue_mp_common(arpce, mp, B_FALSE);
30208 		}
30209 
30210 		if (arpce->nce_state == ND_INCOMPLETE) {
30211 			mutex_exit(&arpce->nce_lock);
30212 			DTRACE_PROBE3(ip__xmit__incomplete,
30213 			    (ire_t *), ire, (mblk_t *), mp,
30214 			    (ipsec_out_t *), io);
30215 			return (LOOKUP_IN_PROGRESS);
30216 		}
30217 
30218 		arpce->nce_state = ND_INCOMPLETE;
30219 		mutex_exit(&arpce->nce_lock);
30220 		/*
30221 		 * Note that ire_add() (called from ire_forward())
30222 		 * holds a ref on the ire until ARP is completed.
30223 		 */
30224 
30225 		ire_arpresolve(ire, ire_to_ill(ire));
30226 		return (LOOKUP_IN_PROGRESS);
30227 	default:
30228 		ASSERT(0);
30229 		mutex_exit(&arpce->nce_lock);
30230 		return (LLHDR_RESLV_FAILED);
30231 	}
30232 }
30233 
30234 #undef	UPDATE_IP_MIB_OB_COUNTERS
30235 
30236 /*
30237  * Return B_TRUE if the buffers differ in length or content.
30238  * This is used for comparing extension header buffers.
30239  * Note that an extension header would be declared different
30240  * even if all that changed was the next header value in that header i.e.
30241  * what really changed is the next extension header.
30242  */
30243 boolean_t
30244 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
30245     uint_t blen)
30246 {
30247 	if (!b_valid)
30248 		blen = 0;
30249 
30250 	if (alen != blen)
30251 		return (B_TRUE);
30252 	if (alen == 0)
30253 		return (B_FALSE);	/* Both zero length */
30254 	return (bcmp(abuf, bbuf, alen));
30255 }
30256 
30257 /*
30258  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
30259  * Return B_FALSE if memory allocation fails - don't change any state!
30260  */
30261 boolean_t
30262 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
30263     const void *src, uint_t srclen)
30264 {
30265 	void *dst;
30266 
30267 	if (!src_valid)
30268 		srclen = 0;
30269 
30270 	ASSERT(*dstlenp == 0);
30271 	if (src != NULL && srclen != 0) {
30272 		dst = mi_alloc(srclen, BPRI_MED);
30273 		if (dst == NULL)
30274 			return (B_FALSE);
30275 	} else {
30276 		dst = NULL;
30277 	}
30278 	if (*dstp != NULL)
30279 		mi_free(*dstp);
30280 	*dstp = dst;
30281 	*dstlenp = dst == NULL ? 0 : srclen;
30282 	return (B_TRUE);
30283 }
30284 
30285 /*
30286  * Replace what is in *dst, *dstlen with the source.
30287  * Assumes ip_allocbuf has already been called.
30288  */
30289 void
30290 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
30291     const void *src, uint_t srclen)
30292 {
30293 	if (!src_valid)
30294 		srclen = 0;
30295 
30296 	ASSERT(*dstlenp == srclen);
30297 	if (src != NULL && srclen != 0)
30298 		bcopy(src, *dstp, srclen);
30299 }
30300 
30301 /*
30302  * Free the storage pointed to by the members of an ip6_pkt_t.
30303  */
30304 void
30305 ip6_pkt_free(ip6_pkt_t *ipp)
30306 {
30307 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
30308 
30309 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
30310 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
30311 		ipp->ipp_hopopts = NULL;
30312 		ipp->ipp_hopoptslen = 0;
30313 	}
30314 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
30315 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
30316 		ipp->ipp_rtdstopts = NULL;
30317 		ipp->ipp_rtdstoptslen = 0;
30318 	}
30319 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
30320 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
30321 		ipp->ipp_dstopts = NULL;
30322 		ipp->ipp_dstoptslen = 0;
30323 	}
30324 	if (ipp->ipp_fields & IPPF_RTHDR) {
30325 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
30326 		ipp->ipp_rthdr = NULL;
30327 		ipp->ipp_rthdrlen = 0;
30328 	}
30329 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
30330 	    IPPF_RTHDR);
30331 }
30332